command-code 0.26.5 → 0.26.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +5 -5
- package/package.json +3 -3
- package/vsix/commandcode-vscode.vsix +0 -0
package/dist/index.mjs
CHANGED
|
@@ -278,9 +278,9 @@ import*as e from"path";import t,{join as n,dirname as r,parse as o,relative as s
|
|
|
278
278
|
WHERE user_id = ${Rw}
|
|
279
279
|
AND role IN ('owner', 'admin')
|
|
280
280
|
)
|
|
281
|
-
`})])),b($w)}}),Zw=__esm({"../shared/src/database/schema/device-fingerprints.ts"(){Ot(),cd(),md(),ff(),yf(),Dw=pgEnum("device_fingerprint_source",["signup","api_key_create","checkout","session"]),c(Ow=gc("device_fingerprints",{id:uuid("id").defaultRandom().primaryKey(),userId:uuid("user_id").references(()=>nf.id,{onUpdate:"cascade",onDelete:"cascade"}).notNull(),thumbmark:text("thumbmark").notNull(),components:jsonb("components").default("{}").notNull(),ipAddress:text("ip_address"),userAgent:text("user_agent"),firstSource:Dw("first_source").notNull(),lastSource:Dw("last_source").notNull(),seenCount:integer("seen_count").default(1).notNull(),firstSeenAt:timestamp("first_seen_at",{withTimezone:!0}).defaultNow().notNull(),lastSeenAt:timestamp("last_seen_at",{withTimezone:!0}).defaultNow().notNull()},e=>[uniqueIndex("device_fingerprints_user_thumbmark_idx").on(e.userId,e.thumbmark),index("device_fingerprints_thumbmark_idx").on(e.thumbmark),index("device_fingerprints_user_id_idx").on(e.userId),pgPolicy("device_fingerprints_select_admin",{as:"permissive",to:"app_user",for:"select",using:sql`(public.current_user_is_app_admin())`}),pgPolicy("device_fingerprints_insert_admin",{as:"permissive",to:"app_user",for:"insert",withCheck:sql`(public.current_user_is_app_admin())`}),pgPolicy("device_fingerprints_update_admin",{as:"permissive",to:"app_user",for:"update",using:sql`(public.current_user_is_app_admin())`}),pgPolicy("device_fingerprints_delete_admin",{as:"permissive",to:"app_user",for:"delete",using:sql`(public.current_user_is_app_admin())`})])),b(Ow)}}),eS=__esm({"../shared/src/database/schema/index.ts"(){Ot(),wf(),Bw(),zw(),yf(),Hw(),Ww(),Gw(),Vw(),Qw(),Kw(),Yw(),Jw(),Xw(),Sf(),Zw()}}),tS=__esm({"../shared/src/database/config/database.ts"(){Ot(),Uw(),eS()}}),nS=__esm({"../shared/src/database/index.ts"(){Ot(),tS(),eS()}}),rS=__esm({"../shared/src/deals.ts"(){Ot()}}),oS=__esm({"../shared/src/index.ts"(){Ot(),Ms(),Ls(),$f(),Of(),Ff(),Qr(),qf(),jf(),Gf(),wn(),Ft(),Vf(),nS(),rS()}}),sS=__esm({"src/api/request.ts"(){Ot(),Ns(),Co(),Rs(),hs(),Oo(),co(),oS(),Fw=getPackageJson(),qw="string"==typeof Fw.version&&Fw.version.trim()?Fw.version:"unknown",jw=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,cliVersion:qw}),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 Es({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}if(r.end({statusCode:s.status}),e.onHeaders)try{e.onHeaders(s.headers)}catch{}return 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,i=getTelemetryEnv(),a="prod"===i?"production":i,l="1"===process.env.CMD_ZDR;return{"Content-Type":"application/json",[Ut.CLI_ENVIRONMENT]:a,...n?{Authorization:`Bearer ${n}`}:{},...s?{traceparent:s}:{},...e,[Ut.CLI_VERSION]:qw,...l?{[Ut.CMD_ZDR]:"1"}:{}}}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:Ss.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 getApiBaseUrl(){const e="true"===process.env.COMMANDCODE_SANDBOX,t=process.env.COMMANDCODE_API_URL;if(e&&t)return t;const n=process.argv.includes("--local"),r=process.argv.includes("--staging");return n?"http://localhost:9090":r?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}var iS,aS,lS,cS,uS,dS,mS,pS,gS,hS,fS=__esm({"src/api/utils.ts"(){Ot(),__name(getApiBaseUrl,"getApiBaseUrl")}}),yS=__esm({"../shared/src/constants/tools.ts"(){Ot(),iS={READ_FILE:"read_file",EDIT_FILE:"edit_file",WRITE_FILE:"write_file",READ_DIRECTORY:"read_directory",READ_MULTIPLE_FILES:"read_multiple_files",GREP:"grep",GLOB:"glob",SHELL_COMMAND:"shell_command",THINKING:"think",TODO_WRITE:"todo_write",QUESTION:"ask_user_question",EXPLORE:"explore",KILL_SHELL:"kill_shell",ENTER_PLAN_MODE:"enter_plan_mode",EXIT_PLAN_MODE:"exit_plan_mode",DIAGNOSTICS:"diagnostics",GET_SELF_KNOWLEDGE:"get_self_knowledge"},aS={WEB_SEARCH:"web_search",WEB_FETCH:"web_fetch"},lS=__name(e=>e===aS.WEB_SEARCH,"isWebSearchTool"),cS=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],uS=__name(({serverToolBlock:e,contentBlocks:t})=>{const n=e.toolCallId??e.id,r=e.toolName??e.name??"",o=t.find(e=>"tool-result"===e.type&&e.providerExecuted&&e.toolCallId===n);if(o)return"error-text"===o.output?.type||"error-json"===o.output?.type?{message:o.output?.value??"Error",isError:!0}:"string"==typeof o.output?.value&&o.output.value.trim()?{message:lS(r)?"Found results":"Content fetched",isError:!1}:{message:lS(r)?"Found 10 results":"Content fetched",isError:!1};const s=t.find(e=>("web_search_tool_result"===e.type||"web_fetch_tool_result"===e.type)&&e.tool_use_id===n);return cS.includes(s?.content?.type)?{message:`Error: ${s?.content?.error_code||"unknown_error"}`,isError:!0}:lS(r)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),dS=["create_file","delete_file",iS.EDIT_FILE,iS.WRITE_FILE,iS.SHELL_COMMAND],mS=[iS.SHELL_COMMAND]}}),wS=__esm({"src/mcp/constants.ts"(){Ot(),pS="2025-03-26",gS={name:"command-code",version:"1.0.0"},Promise.resolve().then(()=>(Co(),uo)).then(({getPackageJson:e})=>{gS.version=e().version??"1.0.0"}).catch(()=>{})}});function originOf(e){try{return new URL(e).origin}catch{return null}}function getTokenFilePath(){return e.join(S.homedir(),".commandcode",hS)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await v.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 v.mkdir(r,{recursive:!0}),await v.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await v.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,expectedUrl:t,refreshCallback:n}){const r=await getTokens(e);if(!r)return null;const o=originOf(t);if(!o)return dlog("[MCP] Refusing to attach token: invalid expectedUrl",t),null;if(!r.issuerUrl)return dlog(`[MCP] Stored token for "${e}" has no issuerUrl; refusing and clearing. Re-authenticate to continue.`),await deleteTokens(e),null;if(originOf(r.issuerUrl)!==o)return dlog(`[MCP] Refusing to attach token for "${e}": configured url ${o} does not match issuer ${r.issuerUrl}`),null;if(!isTokenExpired(r))return r.accessToken;if(r.refreshToken&&n)try{const t=await n(r.refreshToken);return await storeTokens(e,{...t,issuerUrl:r.issuerUrl}),t.accessToken}catch(t){return dlog("[MCP] Token refresh failed",t),await deleteTokens(e),null}return await deleteTokens(e),null}async function migrateLegacyTokens(e){const t=await loadTokenStorage(),n={bound:[],cleared:[]};let r=!1;for(const[o,s]of Object.entries(t.tokens)){if(s.issuerUrl)continue;const i=await e(o);i&&originOf(i)?(t.tokens[o]={...s,issuerUrl:i},n.bound.push(o),dlog(`[MCP] Migrated legacy token "${o}" → issuerUrl=${i}`)):(delete t.tokens[o],n.cleared.push(o),dlog(`[MCP] No trusted URL for legacy token "${o}"; cleared.`)),r=!0}return r&&await saveTokenStorage(t),n}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 SS,ES,bS,CS,vS=__esm({"src/mcp/auth/token-storage.ts"(){Ot(),wn(),Kn(),__name(originOf,"originOf"),hS="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(migrateLegacyTokens,"migrateLegacyTokens"),__name(listServersWithTokens,"listServersWithTokens"),__name(storeClientSecret,"storeClientSecret"),__name(getClientSecret,"getClientSecret")}});function isSecureOrLoopback(e){try{const t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol&&("localhost"===t.hostname||"127.0.0.1"===t.hostname||"[::1]"===t.hostname)}catch{return!1}}var kS,TS,_S=__esm({"src/mcp/types.ts"(){Ot(),__name(isSecureOrLoopback,"isSecureOrLoopback"),SS=f.string().url().refine(isSecureOrLoopback,{message:"URL must use https:// (or http:// for loopback hosts)"}),ES=f.object({authorizationUrl:SS,tokenUrl:SS,clientId:f.string(),clientSecret:f.string().optional(),scopes:f.array(f.string()).optional()}),bS=f.object({transport:f.enum(["stdio","http"]),enabled:f.boolean().default(!0),command:f.string().optional(),args:f.array(f.string()).optional(),url:f.string().url().optional(),headers:f.record(f.string(),f.string()).optional(),oauth:ES.optional(),env:f.record(f.string(),f.string()).optional()}).refine(e=>!e.oauth||!e.url||isSecureOrLoopback(e.url),{message:"OAuth requires the server url to use https:// (or http:// for loopback hosts)",path:["url"]}),CS=f.object({mcpServers:f.record(f.string(),bS)})}});function getUserMcpConfigPath(){return e.join(S.homedir(),".commandcode",kS)}function getLocalMcpConfigPath(t=process.cwd()){const n=Fe(t);return e.join(S.homedir(),".commandcode","projects",n,kS)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,TS)}function getMcpConfigPath({scope:e,projectPath:t=process.cwd()}){switch(e){case"user":return getUserMcpConfigPath();case"local":return getLocalMcpConfigPath(t);case"project":return getProjectMcpConfigPath(t)}}function getAllMcpConfigPaths(e=process.cwd()){return[{scope:"user",path:getUserMcpConfigPath()},{scope:"project",path:getProjectMcpConfigPath(e)},{scope:"local",path:getLocalMcpConfigPath(e)}]}var xS=__esm({"src/mcp/config/scopes.ts"(){Ot(),wn(),kS="mcp.json",TS=".mcp.json",__name(getUserMcpConfigPath,"getUserMcpConfigPath"),__name(getLocalMcpConfigPath,"getLocalMcpConfigPath"),__name(getProjectMcpConfigPath,"getProjectMcpConfigPath"),__name(getMcpConfigPath,"getMcpConfigPath"),__name(getAllMcpConfigPaths,"getAllMcpConfigPaths")}});async function loadMcpConfig({scope:e,projectPath:t=process.cwd()}){try{const n=getMcpConfigPath({scope:e,projectPath:t}),r=await v.readFile(n,"utf-8"),o=JSON.parse(r),s=CS.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 v.mkdir(s,{recursive:!0}),await v.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()}){const o=bS.safeParse(t);if(!o.success){const t=o.error.issues.map(e=>`${e.path.join(".")||"<root>"}: ${e.message}`).join("; ");throw new Error(`Invalid MCP server config for "${e}": ${t}`)}let s=await loadMcpConfig({scope:n,projectPath:r});s||(s={mcpServers:{}});let i=t;if("project"===n&&t.oauth?.clientSecret){await storeClientSecret(e,t.oauth.clientSecret);const{clientSecret:n,...r}=t.oauth;i={...i,oauth:r}}i={...i,enabled:i.enabled??!0},s.mcpServers[e]=i,await saveMcpConfig({config:s,scope:n,projectPath:r})}async function removeMcpServer({name:e,scope:t,projectPath:n=process.cwd()}){const r=await loadMcpConfig({scope:t,projectPath:n});return!!r?.mcpServers[e]&&(delete r.mcpServers[e],await saveMcpConfig({config:r,scope:t,projectPath:n}),!0)}async function updateMcpServerStatus({name:e,enabled:t,scope:n,projectPath:r=process.cwd()}){const o=await loadMcpConfig({scope:n,projectPath:r});return!!o?.mcpServers[e]&&(o.mcpServers[e]={...o.mcpServers[e],enabled:t},await saveMcpConfig({config:o,scope:n,projectPath:r}),!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)}))}var AS,PS,IS=__esm({"src/mcp/config/mcp-config.ts"(){Ot(),Kn(),vS(),_S(),xS(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(updateMcpServerStatus,"updateMcpServerStatus"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers")}}),NS=__esm({"src/mcp/client/stdio-transport.ts"(){Ot(),AS=class _StdioTransport extends qe{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=be(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)}}}});function fetchWithTimeout(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),PS);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var RS,MS,LS=__esm({"src/mcp/fetch.ts"(){Ot(),PS=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),$S={};function generateRandomString(e){return N.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:N.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 i=new Promise((e,t)=>{o=e,s=t}),a=G.createServer((n,r)=>{const i=new g(n.url||"/",`http://${MS}:${e}`);if("/callback"===i.pathname){const e=i.searchParams.get("code"),n=i.searchParams.get("error"),a=i.searchParams.get("error_description");if(i.searchParams.get("state")!==t)r.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),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(a||n);r.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),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(a||n))}else e?(r.writeHead(200,{"Content-Type":"text/html",Connection:"close"}),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",Connection:"close"}),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,{Connection:"close"}),r.end("Not Found")});a.on("error",r),a.keepAliveTimeout=1,a.headersTimeout=5e3,a.listen(e,MS,()=>{n({server:a,getCode:__name(()=>i,"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 i=await s.json();return{accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?Date.now()+1e3*i.expires_in:void 0,tokenType:i.token_type,scope:i.scope}}async function refreshAccessToken({config:e,refreshToken:t}){const n=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId});e.clientSecret&&n.set("client_secret",e.clientSecret);const r=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});if(!r.ok){const e=await r.text();throw new Error(`Token refresh failed: ${r.status} ${e}`)}const 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,r){if(!isSecureOrLoopback(t))return{success:!1,error:`MCP server url must use https:// when OAuth is configured (got "${t}"). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]).`};const o=r?.port||RS,s=r?.timeout||12e4,i=r?.onStatus||(()=>{});let a=null;try{const r=generatePKCE(),l=generateRandomString(32),u=`http://${MS}:${o}/callback`;i("Starting authentication server...");const{server:d,getCode:m}=await startCallbackServer(o,l);a=d;const h=new g(n.authorizationUrl);if(h.searchParams.set("response_type","code"),h.searchParams.set("client_id",n.clientId),h.searchParams.set("redirect_uri",u),h.searchParams.set("state",l),h.searchParams.set("code_challenge",r.challenge),h.searchParams.set("code_challenge_method","S256"),n.scopes&&n.scopes.length>0&&h.searchParams.set("scope",n.scopes.join(" ")),n.extraParams)for(const[e,t]of Object.entries(n.extraParams))h.searchParams.set(e,t);i("Opening browser for authentication..."),await pe(h.toString()),i("Waiting for authorization...");const f=m();let y;const w=new Promise((e,t)=>{y=setTimeout(()=>t(new Error("Authentication timed out")),s)}),S=await Promise.race([f,w]);clearTimeout(y),i("Exchanging authorization code for tokens...");const E=await exchangeCodeForTokens(n,S,r.verifier,u);return await storeTokens(e,{...E,issuerUrl:t}),i("Authentication successful!"),{success:!0,tokens:E}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{a&&(a.closeIdleConnections?.(),a.closeAllConnections?.(),a.close(),a.unref())}}function createRefreshCallback(e){return t=>refreshAccessToken({config:e,refreshToken:t})}__export($S,{DEFAULT_OAUTH_CALLBACK_PORT:()=>RS,LOCALHOST_IP:()=>MS,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var DS,OS,FS,qS=__esm({"src/mcp/auth/oauth-flow.ts"(){Ot(),vS(),LS(),_S(),RS=8085,MS="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")}}),jS=__esm({"src/mcp/client/http-transport.ts"(){Ot(),_S(),wS(),vS(),LS(),DS=class _HttpTransport extends qe{constructor(e){if(super(),this.options=e,e.oauth&&!isSecureOrLoopback(e.url))throw new Error(`MCP server url must use https:// when OAuth is configured (got "${e.url}"). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]).`)}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":`${gS.name}/${gS.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(()=>(qS(),$S));return t({config:this.options.oauth,refreshToken:e})},"refreshCallback"),n=await getValidAccessToken({serverName:this.options.serverName,expectedUrl:this.options.url,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(),PS);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 401===t.status&&this.options.oauth&&this.options.serverName&&(e+=` — token rejected. Re-authenticate: cmd mcp auth ${this.options.serverName}`),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")||"",i=await t.text();if(s.includes("text/event-stream")||i.startsWith("event:")||i.startsWith("data:")){const e=this.parseSSEResponse(i);if(e)return e;throw new Error("Failed to parse SSE response")}return JSON.parse(i)}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new Error("Request timed out");throw e}finally{clearTimeout(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(),PS);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}}}});function getMcpConnectionManager(){return FS||(FS=new OS),FS}var US=__esm({"src/mcp/client/connection-manager.ts"(){Ot(),wS(),IS(),vS(),NS(),jS(),BS(),OS=class extends qe{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 t=await migrateLegacyTokens(async t=>{const n=await loadMcpConfig({scope:"user",projectPath:e});return n?.mcpServers?.[t]?.url??null});t.cleared.length>0&&this.emit("legacyTokensCleared",t.cleared);const{config:n,serverScopes:r}=await loadMergedMcpConfig(e),o=[];for(const[e,t]of Object.entries(n.mcpServers)){if(!t.enabled)continue;const n=r.get(e);o.push(this.connectServer(e,t,n))}await Promise.allSettled(o),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 AS?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?AS.fromConfig(e):DS.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:pS,capabilities:{roots:{}},clientInfo:gS});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)}async ensureServerConnection(e,t=process.cwd()){const{config:n,serverScopes:r}=await loadMergedMcpConfig(t),o=n.mcpServers[e];if(!o)throw new Error(`Server '${e}' not found`);if(!1===o.enabled)throw new Error(`Server '${e}' is disabled`);if(this.connections.get(e))return void await this.reconnectServer(e);const s=r.get(e);if(!s)throw new Error(`Server '${e}' scope not found`);await this.connectServer(e,o,s)}get isInitialized(){return this.initialized}},FS=null,__name(getMcpConnectionManager,"getMcpConnectionManager")}});function mcpToolToSchema({serverName:e,tool:t}){const n=`mcp__${e}__${t.name}`,r=t.inputSchema||{},o=r.properties??{},s=r.required;return{name:n,description:t.description||`MCP tool: ${t.name} (from ${e})`,input_schema:{type:"object",properties:o,...s&&s.length>0?{required:s}:{}}}}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)}}}var BS=__esm({"src/mcp/client/tool-adapter.ts"(){Ot(),US(),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool")}});function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",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}var zS,HS,WS,GS,VS,QS,KS,YS,JS,XS,ZS,eE,tE,nE,rE,oE,sE,iE,aE,lE,cE,uE,dE,mE,pE,gE,hE,fE,yE,wE,SE,EE,bE,CE,vE=__esm({"src/tools/utils/path-display.ts"(){Ot(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText")}}),kE={};function setPreHookLines(e,t){if(0===t.length)return;const n=e.metadata??{};n.preHookLines=t,e.metadata=n}function setPostHookLines(e,t){if(0===t.length)return;const n=e.metadata??{};n.postHookLines=t,e.metadata=n}function setHookOutcome(e,t){const n=e.metadata??{};n.hookOutcome=t,e.metadata=n}__export(kE,{FeedEntrySchema:()=>tE,LLM_STATUS_MESSAGES:()=>yE,createAgentToolEntry:()=>mE,createAssistantEntry:()=>oE,createBashEntry:()=>iE,createCommandResultEntry:()=>uE,createErrorEntry:()=>lE,createIDEStatusEntry:()=>dE,createInfoEntry:()=>rE,createSystemEntry:()=>aE,createTasteOnboardingEntry:()=>cE,createToolEntry:()=>sE,createUserEntry:()=>nE,formatError:()=>gE,getRandomLLMStatus:()=>wE,getToolDisplayName:()=>SE,getToolInputContent:()=>bE,isErrorEntry:()=>hE,isPendingEntry:()=>fE,parseTodosFromOutput:()=>CE,setHookOutcome:()=>setHookOutcome,setPostHookLines:()=>setPostHookLines,setPreHookLines:()=>setPreHookLines,updateEntryWithOutput:()=>pE});var TE,_E=__esm({"src/types/feed.ts"(){Ot(),yS(),BS(),vE(),as(),zS=f.object({id:f.string(),timestamp:f.number(),type:f.literal("image"),source:f.object({type:f.enum(["base64","url"]),media_type:f.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:f.string()})}),HS=f.object({id:f.string(),timestamp:f.number(),input:f.string(),output:f.string().optional(),metadata:f.record(f.string(),f.any()).optional(),images:f.array(zS).optional().default([])}),WS=HS.extend({role:f.literal("user")}),GS=HS.extend({role:f.literal("assistant")}),VS=HS.extend({role:f.literal("tool"),name:f.string(),description:f.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),QS=HS.extend({role:f.literal("bash"),command:f.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),KS=HS.extend({role:f.literal("system")}),YS=HS.extend({role:f.literal("error")}),JS=HS.extend({role:f.literal("info")}),XS=HS.extend({role:f.literal("taste-onboarding")}),ZS=HS.extend({role:f.literal("command-result"),hasError:f.boolean().optional(),details:f.string().optional()}),eE=HS.extend({role:f.literal("ide-status"),status:f.enum(["connected","installed","up_to_date","needs_reload","not_in_ide","failed"]),ide:f.string().nullable(),details:f.array(f.string()).optional()}),tE=f.discriminatedUnion("role",[WS,GS,VS,QS,KS,YS,JS,XS,ZS,eE]),__name(setPreHookLines,"setPreHookLines"),__name(setPostHookLines,"setPostHookLines"),__name(setHookOutcome,"setHookOutcome"),nE=__name((e,t)=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),rE=__name((e,t)=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),oE=__name(e=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),sE=__name((e,t,n)=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),iE=__name(e=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),aE=__name((e,t)=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e,metadata:t}),"createSystemEntry"),lE=__name(e=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),cE=__name(()=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),uE=__name((e,t=!1,n)=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),dE=__name((e,t,n)=>tE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),mE=__name(({name:e,input:t})=>{const n=Date.now();return tE.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"),pE=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return tE.parse(n)},"updateEntryWithOutput"),gE=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),hE=__name(e=>/^error:/i.test(e.output??""),"isErrorEntry"),fE=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),yE=["Pondering…","Contemplating…","Reasoning…","Reflecting…","Considering…","Deliberating…","Analyzing…","Evaluating…","Examining…","Inspecting…","Investigating…","Reviewing…","Researching…","Studying…","Exploring…","Mapping…","Tracing…","Parsing…","Processing…","Calculating…","Computing…","Synthesizing…","Planning…","Outlining…","Sketching…","Drafting…","Composing…","Crafting…","Building…","Assembling…","Constructing…","Designing…","Formulating…","Structuring…","Organizing…","Preparing…","Refining…","Polishing…","Honing…","Tuning…","Aligning…","Connecting…","Resolving…","Weaving…","Threading…","Sculpting…","Crystallizing…","Channeling…","Conjuring…","Brewing…","Working…","Cogitating…","Ruminating…","Hypothesizing…","Conceptualizing…","Philosophizing…","Deciphering…","Demystifying…","Articulating…","Illuminating…","Elaborating…","Orchestrating…","Choreographing…","Architecting…","Calibrating…","Materializing…","Visualizing…","Harmonizing…","Contemplificating…","Supercalifragilisting…","Bibbidibobbidibooing…","Abracadabraing…","Hocuspocusing…","Razzmatazzing…"],wE=__name(()=>yE[Math.floor(Math.random()*yE.length)],"getRandomLLMStatus"),SE=__name(e=>{switch(e){case iS.READ_FILE:return"READ";case iS.EDIT_FILE:return"EDIT";case iS.WRITE_FILE:return"WRITE";case iS.READ_DIRECTORY:return"LIST";case iS.READ_MULTIPLE_FILES:return"READ[n]";case iS.GREP:return"SEARCH";case iS.SHELL_COMMAND:return"SHELL";case iS.TODO_WRITE:return"TODOS";case iS.THINKING:return"thinking…";case aS.WEB_SEARCH:return"WEB SEARCH";case aS.WEB_FETCH:return"WEB FETCH";case iS.QUESTION:return"QUESTION";case iS.EXPLORE:return"EXPLORE";case iS.KILL_SHELL:return"KILL SHELL";default:if(isMcpTool(e)){const t=parseMcpToolName(e);if(t){const e=t.toolName.replace(/[-_]/g," ").toUpperCase();return`${t.serverName}: ${e} (MCP)`}}return e.replace(/_/g," ").toUpperCase()}},"getToolDisplayName"),EE=__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:Xo})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),bE=__name((e,t)=>{try{switch(e){case iS.READ_FILE:case iS.WRITE_FILE:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case iS.EDIT_FILE:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case iS.READ_DIRECTORY:return toRelativePath(t.path||"directory");case iS.GREP:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case iS.SHELL_COMMAND:if(t.command){const e=Array.isArray(t.args)&&t.args.length>0?` ${t.args.join(" ")}`:"string"==typeof t.args&&t.args?` ${t.args}`:"";return`${t.command}${e}`}return t.command||"";case iS.TODO_WRITE:let o;try{o="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=CE(o);return`${e?e.length:0} items`}catch{return"items"}case iS.THINKING:return t.content||"planning";case iS.READ_MULTIPLE_FILES:const s=t.include||[];if(!Array.isArray(s)||0===s.length)return"multiple files";const i=s.slice(0,es).map(toRelativePath).join(", "),a=s.length-es;return a>0?`${i} (+${a} more)`:i;case aS.WEB_SEARCH:return t.query||"search";case aS.WEB_FETCH:return t.url||"fetch";case iS.QUESTION:return"User answered questions";case iS.KILL_SHELL:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case iS.ENTER_PLAN_MODE:case iS.EXIT_PLAN_MODE:return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return EE(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:Zo})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),CE=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput")}});async function 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=Me.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=G.createServer((e,o)=>{const i=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],a=e.headers.origin||"",l=i.includes(a)?a:i[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 TE(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const i=e;if(!(i.apiKey&&i.state&&i.userId&&i.userName&&i.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(i.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const a={success:!0};o.writeHead(200),o.end(JSON.stringify(a)),n(i),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()})})}var xE,AE=__esm({"src/utils/auth/local-server.ts"(){Ot(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable"),TE=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}},__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer")}});function generateStateToken(){return N.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await pe(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:cs.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(yn()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await v.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 v.writeFile(n,r,{mode:384}),await v.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await v.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}var PE,IE,NE,RE=__esm({"src/utils/auth/auth-flow.ts"(){Ot(),AE(),Sn(),Rn(),hs(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl"),xE=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}},__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials")}});async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${Bt.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:cs.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=PE}=e,[s,i]=Y("initializing"),[a,l]=Y("Starting authentication..."),[u,d]=Y(""),[m,g]=Y(null),h=J(null),f=J(!1),y=J(!1),w=J(null),S=J(null),E=J(t),C=J(n),v=J(r);X(()=>{E.current=t,C.current=n,v.current=r});const k=ee(()=>{w.current&&(clearTimeout(w.current),w.current=null),S.current&&(clearTimeout(S.current),S.current=null),h.current&&(stopServer(h.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),h.current=null)},[]),T=ee(()=>{y.current||(y.current=!0,f.current=!0,k(),v.current())},[k]),_=ee((e,t)=>{y.current||(y.current=!0,k(),E.current(e,t))},[k]),x=ee((e,t)=>{y.current||(y.current=!0,k(),C.current(e,t))},[k]),A=ee(async e=>{const t=sanitizeApiKey(e);if(!t)return;i("validating"),l("Validating API key...");const n=await validateApiKey(t);if(f.current)return;if(y.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return i("invalid_key"),l(e),void(w.current=setTimeout(()=>{f.current||y.current||(i("manual_entry"),l("Paste a valid API key below.")),w.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(y.current)return;await storeCredentials(e),i("success"),_(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:cs.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),l("Failed to save API key. Please try again."),i("manual_entry")}},[_]);return X(()=>{let e=!0;return __name(async()=>{if(!f.current)try{const t=await findAvailablePort(IE,NE);if(!e||f.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);g(r);const{server:s,waitForCallback:a}=createAuthServer(t,n);if(h.current=s,!e||f.current)return void await stopServer(s);i("waiting_browser"),l("Complete login in your browser...");const u=await openBrowser(r);if(!e||f.current)return;if(!u)return k(),l("Could not open browser. Paste your API key below."),void i("manual_entry");const d=new Promise((e,t)=>{S.current=setTimeout(()=>{S.current=null,t(new xE("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([a,d]);if(!e||f.current)return;if(y.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(y.current)return;if(await storeCredentials(n),!e||f.current||y.current)return;i("browser_success"),_(n,"browser")}catch(t){if(y.current)return;if(!e||f.current)return;if(t instanceof TE)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:cs.AUTH_FLOW,heading:"Authorization denied by user"}}),i("denied"),void x("denied","Authorization denied by user.");k(),t instanceof xE&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:cs.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:cs.AUTH_FLOW,heading:"Browser auth failed"}}),l("Browser auth failed. Paste your API key below.")),i("manual_entry")}}catch(t){if(y.current)return;if(!e||f.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:cs.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),k(),i("manual_entry"),l("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,k()}},[o,_,x,k]),{authState:s,statusMessage:a,browserUrl:m,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:A,cancel:T,hasCompleted:y.current}}var ME=__esm({"src/tui/hooks/use-auth-flow.ts"(){Ot(),RE(),AE(),fS(),wn(),hs(),PE=12e4,IE=5959,NE=10,__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow")}});function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){return"waiting_browser"===e?"Authorize in browser, or paste API key here":"invalid_key"===e?"That key was invalid. Try again.":"Paste your API key and press Enter"}function getAuthUrlLabel(e){return"waiting_browser"===e?"Login: ":"Get API key: "}var LE,$E,DE,OE=__esm({"src/utils/auth/auth-status.ts"(){Ot(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel")}}),FE=__esm({"src/tui/auth-flow-ui.tsx"(){Ot(),$r(),OE(),Rr(),Xr(),(LE=Q.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:o})=>{const s="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,i=t&&("waiting_browser"===e||"manual_entry"===e);return Q.createElement(Q.Fragment,null,s&&Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?ar.YELLOW:ar.GRAY,paddingX:1},Q.createElement(ne,{color:ar.DIM},"API Key: "),Q.createElement(te,{flexGrow:1},Q.createElement(TextInput,{value:n,onChange:r,onSubmit:o,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},getAuthHelpText(e))),i&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},getAuthUrlLabel(e)),Q.createElement(Kr,{url:t,text:"Open login page ↗",color:ar.CYAN,dimColor:!0}))),"validating"===e&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Ctrl+C to cancel")))})).displayName="AuthInputSection",$E=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const i=__name(()=>{switch(e){case"initializing":case"validating":default:return Q.createElement(je,{type:"dots"});case"waiting_browser":return Q.createElement(ne,{color:ar.CYAN},Pe.ellipsis);case"browser_success":case"success":return Q.createElement(ne,{color:ar.GREEN},Pe.tick);case"denied":case"invalid_key":return Q.createElement(ne,{color:ar.RED},Pe.cross);case"manual_entry":return Q.createElement(ne,{color:ar.YELLOW},Pe.arrowDown);case"error":return Q.createElement(ne,{color:ar.RED},Pe.warning)}},"getStatusIcon"),a=__name(()=>getAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:Q.createElement(te,{flexDirection:"column",paddingY:1},Q.createElement(te,{marginBottom:1},Q.createElement(te,{marginRight:1},i()),Q.createElement(ne,{color:a()},t)),Q.createElement(LE,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s}))},"AuthFlowUI")}}),qE=__esm({"src/tui/login-with-api-key.tsx"(){Ot(),ME(),FE(),DE=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i,cancel:a}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return se((e,t)=>{t.ctrl&&"c"===e&&a()}),Q.createElement($E,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i})},"LoginWithApiKey")}});function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${ue.bgGreen(ue.black(` ${e} `))}${o}`:n?`${ue.bgBlack(ue.white(` ${e} `))}${o}`:`${ue.bold(ue.bgCyan(ue.black(` ${e} `)))}${o}`}var jE=__esm({"src/utils/heading.ts"(){Ot(),__name(heading,"heading")}});async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=On.createAuthorizationUrl(),r=await ze({message:"Open the Anthropic auth page?",initialValue:!0});if(Ve(r))return{success:!1,error:"Anthropic authentication cancelled"};console.log(),console.log(ue.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log(),!0===r?(await pe(e),console.log(ue.yellow(" Copy your authorization code and paste it below.")),console.log()):(console.log(ue.yellow(" Open the URL above and copy your authorization code below.")),console.log());const o=await Qe({message:"Paste your authorization code:",mask:"*"});if(Ve(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 On.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}var UE=__esm({"src/commands/auth/anthropic-auth.ts"(){Ot(),Wn(),ro(),__name(performAnthropicAuth,"performAnthropicAuth")}});async function performCodexAuth(){try{const e=await ze({message:"Open browser to sign in with ChatGPT (Codex)?",initialValue:!0});return Ve(e)?{success:!1,error:"Codex authentication cancelled"}:(await Gn.login({onAuth:__name(({authorizeUrl:t})=>{console.log(),!0===e?pe(t).catch(()=>{console.log(ue.dim(" Could not auto-open browser.")),console.log(` ${createOSC8Link(t,"Open auth page ↗")}`)}):console.log(` ${createOSC8Link(t,"Open auth page ↗")}`),console.log()},"onAuth"),onProgress:__name(e=>{console.log(` ${ue.dim(Pe.circleFilled)} ${ue.dim(e)}`)},"onProgress")}),{success:!0})}catch(e){const t=e instanceof Error?e.message:"Unknown error";return dlog("[CodexAuth] performCodexAuth failed",{error:t}),{success:!1,error:t}}}var BE=__esm({"src/commands/auth/codex-auth.ts"(){Ot(),Yn(),ro(),Kn(),__name(performCodexAuth,"performCodexAuth")}});async function performCopilotAuth(){try{const e=await ze({message:"Open GitHub to authorize Copilot access?",initialValue:!0});return Ve(e)?{success:!1,error:"Copilot authentication cancelled"}:(await Vn.login({onAuth:__name(({userCode:t,verificationUri:n})=>{console.log(),console.log(ue.yellow(` Enter this code on GitHub: ${ue.bold(t)}`)),console.log(),!0===e?pe(n).catch(()=>{console.log(ue.dim(` Open: ${n}`))}):(console.log(ue.dim(" Open this URL in your browser:")),console.log(` ${n}`),console.log())},"onAuth"),onProgress:__name(e=>{console.log(` ${ue.dim(Pe.circleFilled)} ${ue.dim(e)}`)},"onProgress")}),{success:!0})}catch(e){const t=e instanceof Error?e.message:"Unknown error";return dlog("[CopilotAuth] performCopilotAuth failed",{error:t}),{success:!1,error:t}}}var zE=__esm({"src/commands/auth/copilot-auth.ts"(){Ot(),Jn(),Kn(),__name(performCopilotAuth,"performCopilotAuth")}});async function trackLifecycleEvent({eventType:e,metadata:t}){if(isTelemetryEnabled())try{const n=getApiBaseUrl(),r=new jw({baseUrl:n});await r.post({endpoint:Bt.ALPHA.LIFECYCLE_EVENTS.TRACK,body:{eventType:e,metadata:t}}),dlog("[lifecycle-event tracked]",{eventType:e})}catch(t){dlog("[lifecycle-event failed]",{eventType:e,error:t})}}var HE,WE=__esm({"src/api/track-lifecycle-event.ts"(){Ot(),sS(),fS(),wn(),Kn(),co(),__name(trackLifecycleEvent,"trackLifecycleEvent")}});async function hasBeenInstalled(){try{return!0===(await loadUserConfig()).installed}catch{return!1}}async function markAsInstalled(){try{await updateUserConfig({installed:!0})}catch(e){dlog("[detect-first-install] failed to mark as installed",{error:e})}}async function detectAndTrackFirstInstall(){if(!await hasBeenInstalled())return HE||(HE=(async()=>{try{const e=getPackageJson().version||"unknown";await trackLifecycleEvent({eventType:"cli_installed",metadata:{cliVersion:e}}),await markAsInstalled(),dlog("[detect-first-install] tracked first install")}catch(e){dlog("[detect-first-install] failed to track",{error:e})}finally{HE=null}})())}var GE,VE,QE,KE,YE,JE,XE,ZE=__esm({"src/utils/detect-first-install.ts"(){Ot(),WE(),Co(),Kn(),Jr(),HE=null,__name(hasBeenInstalled,"hasBeenInstalled"),__name(markAsInstalled,"markAsInstalled"),__name(detectAndTrackFirstInstall,"detectAndTrackFirstInstall")}}),eb=__esm({"src/commands/auth/errors.ts"(){Ot(),GE=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},VE=class extends Error{static{__name(this,"AuthorizationDeniedError")}constructor(e){super(e),this.name="AuthorizationDeniedError"}}}});function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,i]=Y("loading"),[a,l]=Y(null);return X(()=>{n().then(e=>{l(e),i(o?"success":"done")})},[n,o]),X(()=>{if("done"===s&&null!==a&&r(a),"success"===s&&null!==a){const e=setTimeout(()=>r(a),100);return()=>clearTimeout(e)}},[s,a,r]),"done"===s?null:Q.createElement(YE,null,"loading"===s?Q.createElement(QE,{message:e}):Q.createElement(KE,{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 buildAlreadyLoggedInMessage(e){return formatAlreadyLoggedInStyled(e)}function buildSuccessMessage(e,t){return formatLoginSuccessStyled({userName:e,authFileName:t})}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 VE(e.message):isLoginCancelled(e)?new GE(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 isCopilotProvider(e){return"github-copilot"===e}function isCodexProvider(e){return"codex"===e}function isUserCancellation(e){return e instanceof GE||e instanceof VE}function getErrorMessage2(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Ue.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await Ge({message:"Select provider",options:e});if(Ve(t))throw We(`${Pe.cross} No provider selected.`),new GE("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){We(`${Pe.cross} ${e}`)}function showAnthropicAuthNote(){He("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=>{i(),o(e)},"handleComplete"),{unmount:i}=ie(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}=ie(Q.createElement(DE,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=ie(Q.createElement(JE,{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 handleProviderAuth(e){if(dlog("[Auth] handleProviderAuth",e),isAnthropicProvider(e))return showAnthropicAuthNote(),void await performAnthropicAuth();if(isCopilotProvider(e))return dlog("[Auth] starting copilot auth flow"),He("Command Code authentication complete. Now authenticating with GitHub Copilot..."),void await performCopilotAuth();if(isCodexProvider(e)){dlog("[Auth] starting codex auth flow"),He("Command Code authentication complete. Now authenticating with ChatGPT (Codex)...");const e=await performCodexAuth();if(!e.success)throw new Error(e.error??"Codex authentication failed")}}async function finalizeLogin(e,t,n){await saveConfigWithSpinner(e),printMessage(buildSuccessMessage(t,getAuthFileName(n)))}async function runLogin(){const e=yn(),t=await checkAuthWithSpinner(e);if(t.isAuthenticated)return printMessage(buildAlreadyLoggedInMessage(t.userName)),!0;showAuthIntro();const n=await executeLoginFlow();detectAndTrackFirstInstall().catch(()=>{});let r="command-code";return isInternalTeamFlagEnforced()&&(r=await selectProvider(),await handleProviderAuth(r)),await finalizeLogin(r,n,e),!0}async function loginAction(){try{await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${Pe.cross} Login failed:`,getErrorMessage2(e)),process.exit(1)}}var tb=__esm({"src/tui/auth/login.tsx"(){Ot(),wn(),qE(),Hn(),Sn(),jE(),io(),Jr(),UE(),BE(),zE(),Kn(),ZE(),eb(),Ns(),ws(),Rr(),QE=__name(({message:e})=>Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.CYAN},Q.createElement(je,{type:"dots"})),Q.createElement(ne,null," ",e)),"LoadingIndicator"),KE=__name(({message:e})=>Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.GREEN},Pe.tick),Q.createElement(ne,null," ",e)),"SuccessIndicator"),YE=__name(({children:e})=>Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,null," "),Q.createElement(te,null,e)),"StatusContainer"),__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__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(isCopilotProvider,"isCopilotProvider"),__name(isCodexProvider,"isCodexProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage2,"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"),JE=__name(({env:e,onComplete:t})=>{const[n,r]=Y("checking"),[o,s]=Y(null);return X(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),X(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),Q.createElement(YE,null,"checking"===n&&Q.createElement(QE,{message:"Checking authentication status..."}),"logged_in"===n&&Q.createElement(KE,{message:"Authenticated"}),"not_logged_in"===n&&Q.createElement(KE,{message:"Ready to log in"}))},"AuthCheckSpinner"),__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleProviderAuth,"handleProviderAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction"),XE=new Ie("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction)}});async function safeRemoveFile(e,t){try{return await k.unlink(e),{existed:!0}}catch(e){return"ENOENT"===e.code?{existed:!1}:{existed:!0,warning:`Could not remove ${t}: ${e.message}`}}}function collectWarnings(...e){return e.map(e=>e.warning).filter(e=>void 0!==e)}async function performLogout(){try{const e=await safeRemoveFile(getAuthFile(),"auth file"),t=collectWarnings(e);return{success:!0,wasAuthenticated:e.existed,warnings:t}}catch(e){return{success:!1,wasAuthenticated:!1,warnings:[],error:e instanceof Error?e.message:"Unknown error"}}}var nb,rb,ob,sb,ib,ab,lb=__esm({"src/utils/auth/logout.ts"(){Ot(),Rn(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout")}});function printWarnings(e){e.length>0&&(console.warn(ue.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(ue.yellow(` - ${e}`))))}async function renderLogoutUI(){let e;try{const t=await getUserName();e=t||void 0}catch{e=void 0}return new Promise(t=>{const{unmount:n}=ie(Q.createElement(ib,{onComplete:e=>{n(),t(e)},userName:e}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}var cb,ub,db,mb,pb,gb,hb=__esm({"src/tui/auth/logout.tsx"(){Ot(),lb(),fs(),Rr(),ws(),nb=__name(({userName:e})=>{const t=e?`Logging out ${e}...`:"Logging out...";return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.CYAN},Q.createElement(je,{type:"dots"})),Q.createElement(ne,null," ",t))},"LoadingIndicator"),rb=__name(({userName:e,wasAuthenticated:t})=>{const n=!1===t?"Not currently authenticated":formatLogoutSuccess(e);return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.GREEN},Pe.tick),Q.createElement(ne,null," ",n))},"SuccessIndicator"),ob=__name(({errorMessage:e})=>Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.RED},Pe.cross),Q.createElement(ne,{color:ar.RED}," Logout failed: ",e)),"ErrorIndicator"),sb=__name(({status:e,errorMessage:t,userName:n,wasAuthenticated:r})=>"loading"===e?Q.createElement(nb,{userName:n}):"success"===e?Q.createElement(rb,{userName:n,wasAuthenticated:r}):Q.createElement(ob,{errorMessage:t}),"StatusDisplay"),ib=__name(({onComplete:e,userName:t})=>{const[n,r]=Y("loading"),[o,s]=Y(""),[i,a]=Y(null);return X(()=>{performLogout().then(e=>{a(e),e.success?r("success"):(s(e.error||"Unknown error"),r("error"))})},[]),X(()=>{if(("success"===n||"error"===n)&&i){const t=setTimeout(()=>e(i),100);return()=>clearTimeout(t)}},[n,i,e]),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,null," "),Q.createElement(te,null,Q.createElement(sb,{status:n,errorMessage:o,userName:t,wasAuthenticated:i?.wasAuthenticated})))},"LogoutSpinner"),__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction"),ab=new Ie("logout").description("Log out of Command Code").allowUnknownOption().allowExcessArguments().action(logoutAction)}}),fb=__esm({"src/commands/auth/index.ts"(){Ot(),tb(),hb(),Ns(),eb(),Ns(),hb(),ws(),tb(),UE(),zE(),Sn(),Rn(),new Ie("auth").description("Manage authentication with Command Code").addCommand(XE).addCommand(ab).addCommand(ys)}});function ensureSession(){if(!db){db=!0;try{j(r(ub),{recursive:!0});const e=`\n=== SESSION ${(new Date).toISOString()} pid=${process.pid} cols=${process.stdout.columns??"?"} rows=${process.stdout.rows??"?"} ===\n`;W(ub,e,"utf-8")}catch{}}}function emit(e,t){if(!cb)return;ensureSession();const n=++mb,r=Date.now()-pb,o=process.stdout.columns??0,s=[`+${r.toString().padStart(7)}ms`,`#${n.toString().padStart(5)}`,e.padEnd(14),`cols=${o}`];for(const[e,n]of Object.entries(t)){const t="string"==typeof n?JSON.stringify(n):String(n);s.push(`${e}=${t}`)}try{W(ub,s.join(" ")+"\n","utf-8")}catch{}}var yb,wb=__esm({"src/utils/resize-flicker-debug.ts"(){Ot(),cb="1"===process.env.CMD_FLICKER_DEBUG,ub=process.env.CMD_FLICKER_LOG??n(C(),".commandcode","logs","flicker.log"),db=!1,mb=0,pb=Date.now(),__name(ensureSession,"ensureSession"),__name(emit,"emit"),gb={enabled:cb,logFile:ub,resize(e){emit("RESIZE",e)},clearConsole(){emit("CLEAR_CONSOLE",{})},statusRender(e){emit("STATUS_RENDER",e)},custom(e,t){emit(e,t)}}}}),Sb=__esm({"src/utils/clear-console.ts"(){Ot(),wb(),yb=__name(()=>{gb.clearConsole(),process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H")},"clearConsole")}});async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new jw({baseUrl:e});return await t.get({endpoint:Bt.ALPHA.WHOAMI})}var Eb=__esm({"src/utils/get-entity.ts"(){Ot(),fS(),sS(),wn(),__name(getAuthenticatedEntity,"getAuthenticatedEntity")}}),bb={};function isModelPremium(e){const t=Object.values(sn).find(t=>t.id===e);return!!t&&"premium"===getModelCategory({provider:t.provider,model:e})}async function getBillingLink({billingLink:e,setBillingLink:t}){if(e)return e;try{const e=await getAuthKey();if(!e)return;const n=await getAuthenticatedEntity();if(e.startsWith("user_")){const e=`https://commandcode.ai/${n.user.userName}/settings/billing`;return t(e),e}if(n.org){const e=`https://commandcode.ai/${n.org.login}/settings/billing`;return t(e),e}}catch{return"https://commandcode.ai/settings/billing"}}async function handleSubmit({role:e,input:t,images:n,ideContext:r,ideHint:o,displayMessage:s,isAutomated:i,hiddenMessages:a,feed:l,setFeed:u,isCmdCodeBusy:d,setIsCmdCodeBusy:m,setQueuedMessages:g,setStatus:h,setInteractionTokens:f,updateStatus:y,setUpdateStatus:w,billingLink:S,setBillingLink:E,currentModel:C,premiumCreditsExhausted:v,setPremiumCreditsExhausted:k,setCurrentModel:T,contextEngineRef:_,isSubmittingRef:x,setInput:A,setStaticKey:P,executeBash:I}){if(!t.length)return;if(y&&w(null),f(0),"bash"===e){if(x.current)return;x.current=!0;const e=iE(t);return u([...l,e]),A(""),await I(t,e=>{u(e)},()=>{yb(),P(e=>e+1)}),void(x.current=!1)}if(d)return g(e=>[...e,{input:t,displayMessage:s,isAutomated:i,hiddenMessages:a}]),void A("");if(x.current)return;x.current=!0,m(!0),h(wE()),A("");let N=!1;if(v&&C&&isModelPremium(C))return N=!0,h("Premium credits exhausted"),u(e=>[...e,rE("Premium model requests already consumed. Pick a standard model instead.\nRun /upgrade to check plans or /extra to buy on-demand credits")]),m(!1),void(x.current=!1);try{if(_.current){const e=i||a?{...i?{isAutomated:!0}:{},...a?{hiddenMessages:a}:{}}:void 0;await _.current.sendMessage(t,n,r,s,e,o)}}catch(e){const t=e instanceof Error?e.message:"An unexpected error occurred",n=e instanceof Error?e.name:"",r=null!==e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"";if("Interrupted by user"===t||t.toLowerCase().includes("interrupt")||t.toLowerCase().includes("abort")||"InterruptedError"===n||"AbortError"===n||"ECONNABORTED"===r)return void(N=!0);if(N=!0,"Insufficient credits"===t){h("Insufficient credits");const e=`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${await getBillingLink({billingLink:S,setBillingLink:E})}`;return void u(t=>[...t,lE(e)])}if("Premium credits exhausted"===t){k?.(!0);const e=sn.KIMI_K2_5.id;return await setSelectedModel({model:e}),T?.(e),yb(),P(e=>e+1),h("Switched to Kimi K2"),void u(e=>[...e,rE("Auto switched model to Kimi K2. Plan Premium requests used.\n`/upgrade` plan or buy `/extra` on-demand credits")])}if(t.startsWith("Model not in plan:")){const e=t.slice(19);return h("Model not available"),void u(t=>[...t,rE(`${e}\nRun /upgrade to check plans or /extra to buy on-demand credits`)])}if(t.startsWith("Error:"))return h("Error"),void u(e=>[...e,lE(t)]);h("Error"),u(e=>[...e,lE(t)])}finally{m(!1),N||h("Ready..."),x.current=!1}}__export(bb,{getBillingLink:()=>getBillingLink,handleSubmit:()=>handleSubmit});var Cb,vb=__esm({"src/tui/actions/submit.ts"(){Ot(),_E(),fb(),Eb(),wn(),Jr(),Sb(),__name(isModelPremium,"isModelPremium"),__name(getBillingLink,"getBillingLink"),__name(handleSubmit,"handleSubmit")}});function isCorruptedArchiveError(e){const t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("zlib")||t.includes("unexpected end")||t.includes("tar_bad_archive")||t.includes("unrecognized archive")||t.includes("invalid tar header")}async function clearGigetCache(e,n){const r=t.join(S.homedir(),".cache","giget","gh",`${e}-${n}`);await k.rm(r,{recursive:!0,force:!0}).catch(()=>{})}async function cleanupStaleTempDirectories(){try{const e=S.tmpdir(),n=await k.readdir(e,{withFileTypes:!0}),r=Date.now();for(const o of n)if(o.isDirectory()&&(o.name.startsWith("commandcode-skill-")||o.name.startsWith("commandcode-skill-discovery-")))try{const n=t.join(e,o.name);r-(await k.stat(n)).mtimeMs>Cb&&await k.rm(n,{recursive:!0,force:!0})}catch(e){}}catch(e){}}function wrapFetchError(e,t,n){const r=e instanceof Error?e.message:String(e),o=r.toLowerCase();return o.includes("could not find commit hash")||o.includes("not found")||o.includes("404")?new Error(`Repository "${t}/${n}" not found on GitHub.\nIf the repo doesn't use "main" branch, specify the branch: ${t}/${n}@<branch>`):o.includes("403")||o.includes("401")||o.includes("forbidden")||o.includes("unauthorized")||o.includes("could not download")?new Error(`Repository "${t}/${n}" is private or inaccessible.\nSkills can only be installed from public repositories.`):o.includes("enotfound")||o.includes("econnrefused")||o.includes("etimedout")?new Error("Network error: unable to reach GitHub. Check your internet connection."):o.includes("zlib")||o.includes("unexpected end")||o.includes("tar_bad_archive")||o.includes("unrecognized archive")||o.includes("invalid tar header")?new Error(`Download of "${t}/${n}" failed (corrupted archive).\nThis is usually a transient GitHub issue. Please try again.`):new Error(`Failed to fetch "${t}/${n}": ${r}`)}var kb,Tb,_b=__esm({"src/services/skill-utils.ts"(){Ot(),Cb=864e5,__name(isCorruptedArchiveError,"isCorruptedArchiveError"),__name(clearGigetCache,"clearGigetCache"),__name(cleanupStaleTempDirectories,"cleanupStaleTempDirectories"),__name(wrapFetchError,"wrapFetchError")}}),xb={};async function findSkillMdFiles(e){const{dir:n,maxDepth:r=5,currentDepth:o=0,relativePath:s="",foundCount:i={value:0}}=e;if(o>r)return[];if(i.value>=kb)return[];const a=[];try{const e=await k.readdir(n,{withFileTypes:!0}),l=e.find(e=>("SKILL.md"===e.name||"skill.md"===e.name)&&e.isFile());if(l){const e=t.join(n,l.name);try{if((await k.stat(e)).size>Tb);else{const r=await k.readFile(e,"utf-8"),{data:o}=Ke(r),l=s.split("/").filter(Boolean),u=l[l.length-1]||t.basename(n);a.push({name:o.name||u,path:s||".",description:o.description}),i.value++}}catch(e){process.env.DEBUG&&console.error(`Failed to parse SKILL.md at ${s||"."}: ${e instanceof Error?e.message:String(e)}`)}}const u=e.filter(e=>e.isDirectory());for(const e of u){if("node_modules"===e.name||".git"===e.name||"dist"===e.name||"build"===e.name||".next"===e.name)continue;const l=t.join(n,e.name),u=s?`${s}/${e.name}`:e.name,d=await findSkillMdFiles({dir:l,maxDepth:r,currentDepth:o+1,relativePath:u,foundCount:i});a.push(...d)}}catch(e){process.env.DEBUG&&console.error(`Failed to read directory ${s||"."}: ${e instanceof Error?e.message:String(e)}`)}return a}async function discoverSkillsLocally(e){const{owner:n,repo:r,path:o,branch:s,keepTempDir:i=!1}=e;await cleanupStaleTempDirectories();const a=t.join(S.tmpdir(),`commandcode-skill-discovery-${M()}`);try{await k.mkdir(a,{recursive:!0});let e=`gh:${n}/${r}`;o&&(e+=`/${o}`),s&&(e+=`#${s}`);const{downloadTemplate:t}=await import("giget");try{await t(e,{dir:a,force:!0,silent:!0})}catch(o){if(!isCorruptedArchiveError(o))throw o;await clearGigetCache(n,r),await t(e,{dir:a,force:!0,silent:!0})}const l=await findSkillMdFiles({dir:a,maxDepth:5});return i?{skills:l,tempDir:a}:(await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),{skills:l})}catch(e){throw await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),wrapFetchError(e,n,r)}}__export(xb,{discoverSkillsLocally:()=>discoverSkillsLocally});var Ab=__esm({"src/services/local-skill-discovery.ts"(){Ot(),_b(),kb=100,Tb=1048576,__name(findSkillMdFiles,"findSkillMdFiles"),__name(discoverSkillsLocally,"discoverSkillsLocally")}});Ot(),Ot();var Pb=process.argv.includes("-d")||process.argv.includes("--debug");Pb&&(process.env.DEBUG="true"),Pb||(process.removeAllListeners("warning"),process.on("warning",()=>{})),globalThis.AI_SDK_LOG_WARNINGS=!1,Ot(),Ot(),hs();var{red:Ib,yellow:Nb,dim:Rb}=ce,Mb=__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:cs.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Je.error} ${Ib(t)}`),console.log(`${Je.error} ${Ib("ERROR →")} ${n.name}`),console.log(`${Je.info} ${Ib("REASON →")} ${n.message}`),console.log(`${Je.info} ${Ib("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Je.info} ${Rb(`Request ID: ${e}`)}`),console.log(`${Rb(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Je.warning} ${Nb(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:cs.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),Mb({heading:Ye`CRITICAL: Unhandled Promise Rejection!
|
|
282
|
-
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:cs.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),
|
|
283
|
-
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)})})}function getEnterpriseMemoryPath(){switch(w.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=w.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:D(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(D(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:D(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return D(e)&&z(e).isFile()?await v.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=[],i=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(s.push(e),`__CODE_BLOCK_${s.length-1}__`)),a=Array.from(i.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let l=i;for(const t of a){const s=t[1];let i=s;s.startsWith("~/")?i=e.join(w.homedir(),s.slice(2)):e.isAbsolute(s)||(i=e.resolve(e.dirname(n),s));const a=await loadMemoryFile(i);if(a){const e=await processImports(a,i,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(D(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(D(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const i=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of i)if(D(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(D(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 D(r)||await v.mkdir(r,{recursive:!0}),D(t)||await v.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=be(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 D(n)||await v.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(),i=getUserMemoryPath(),a=[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(i)&&o.push(`# Memory from: ${i}\n\n${r.get(i)}`);for(const e of a)if(r.has(e)){o.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===s||e===i||a.includes(e)||o.push(`# Memory from: ${e}\n\n${t}`);return o.join("\n\n---\n\n")}catch(e){return null}}hs(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ot(),Ot(),Ns(),sS(),fS(),wn(),yS(),Jr(),ao(),Lo(),Ot(),wn(),__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"),Ot(),wn(),Ot();var Lb="# Taste (Continuously Learned by [CommandCode][cmd])",$b="[cmd]: https://commandcode.ai/",Db=`${Lb}\n\n${$b}`,Ob="# Taste (Continuously Learned by CommandCode)",Fb="# Taste (Continuously Learned by CommandCode.ai)",qb=/^(\s*)# Taste \(Continuously Learned by CommandCode\)(?!\.ai)/,jb=/^(\s*)# Taste \(Continuously Learned by CommandCode\.ai\)/;function migrateHeader(e){const{content:t}=e;if(t.includes(Lb))return t.includes(Db)?t:t.includes($b)?t.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"").replace(Lb,Db):t.replace(Lb,Db);let n=t;return n.includes($b)&&(n=n.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"")),qb.test(n)?n=n.replace(qb,`$1${Db}`):jb.test(n)&&(n=n.replace(jb,`$1${Db}`)),n}async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!D(n))return null;const r=await v.readFile(n,"utf-8"),o=r.trim();return o&&o!==Db&&o!==Lb&&o!==Fb&&o!==Ob?r:null}catch(e){return null}}function getGlobalSkillsDir(){return t.join(S.homedir(),".commandcode","skills")}function getGlobalAgentsCompatSkillsDir(){return t.join(S.homedir(),".agents","skills")}function findGitRoot(){return walkUpToFindDir({dirName:".git"})}function walkUpToFindDir(e){const{dirName:n}=e,r=S.homedir();let o=process.cwd();for(let e=0;e<10&&o!==r;e++){if(D(t.join(o,n)))return o;const e=t.dirname(o);if(e===o)break;o=e}}function getProjectSkillsDir(e){const n=e?.gitRoot??findGitRoot();if(n)return t.join(n,".commandcode","skills");const r=walkUpToFindDir({dirName:".commandcode"});return r?t.join(r,".commandcode","skills"):t.join(process.cwd(),".commandcode","skills")}function getProjectAgentsCompatSkillsDir(e){const n=e?.gitRoot??findGitRoot();if(n)return t.join(n,".agents","skills");const r=walkUpToFindDir({dirName:".agents"});return r?t.join(r,".agents","skills"):t.join(process.cwd(),".agents","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await k.access(r),r}catch{}const o=t.join(n,"skill.md");try{return await k.access(o),o}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await k.access(n);const e=await k.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await k.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 k.readFile(r,"utf-8"),{data:s}=Ke(o),i=hf.parse(s);return i.name!==e.name?null:{name:i.name,description:i.description,filePath:r}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}function mergeSkillSummaries(e){const{primary:t,secondary:n}=e,r=new Set(t.map(e=>e.name)),o=n.filter(e=>!r.has(e.name));return[...t,...o]}async function loadAllSkillSummaries(){const e=findGitRoot(),n=process.cwd(),r=S.homedir(),o=t.join(n,".commandcode","skills"),s=t.join(n,".agents","skills"),i=getProjectSkillsDir({gitRoot:e}),a=getProjectAgentsCompatSkillsDir({gitRoot:e}),l=n!==r,u=[...l&&o!==i?[o]:[],...l&&s!==a?[s]:[],i,a],[d,m,...g]=await Promise.all([loadSkillSummariesFromDirectory({dir:getGlobalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getGlobalAgentsCompatSkillsDir()}),...u.map(e=>loadSkillSummariesFromDirectory({dir:e}))]),h=g.reduce((e,t)=>mergeSkillSummaries({primary:e,secondary:t}),[]);return{global:mergeSkillSummaries({primary:d,secondary:m}),project:h}}function deduplicateSkills(e){const t=new Set,n=[];for(const r of[...e.project,...e.global])t.has(r.name)||(t.add(r.name),n.push(r));return n}async function loadSkill(e){const{filePath:t}=e,n=await k.readFile(t,"utf-8"),r=Ke(n),o=hf.parse(r.data);return{name:o.name,description:o.description,content:r.content.trim(),filePath:t}}function escapeXML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function generateSkillsXML(e){const n=deduplicateSkills(e);return 0===n.length?"":`<available_skills>\n${n.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>`}__name(migrateHeader,"migrateHeader"),__name(getTasteContent,"getTasteContent"),Ot(),Ot(),Ot(),Rf(),wn(),__name(getGlobalSkillsDir,"getGlobalSkillsDir"),__name(getGlobalAgentsCompatSkillsDir,"getGlobalAgentsCompatSkillsDir"),__name(findGitRoot,"findGitRoot"),__name(walkUpToFindDir,"walkUpToFindDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(getProjectAgentsCompatSkillsDir,"getProjectAgentsCompatSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(mergeSkillSummaries,"mergeSkillSummaries"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),__name(deduplicateSkills,"deduplicateSkills"),__name(loadSkill,"loadSkill"),Ot(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),Ot(),Ot();var Ub=f.object({disabledSkills:f.array(f.string()).optional()}).passthrough();Ot(),wn(),Ot();var Bb=1048576;Kn(),Ot(),Ot();var zb=(e=>(e.PreToolUse="PreToolUse",e.PostToolUse="PostToolUse",e))(zb||{}),Hb=new Set(["PreToolUse"]);function formatZodErrorForModel(e,t){return[`Invalid input for tool "${e}". Please correct and retry:`,...t.issues.map(e=>0===e.path.length?` • (root): ${e.message}`:` • ${e.path.join(".")}: ${e.message}`)].join("\n")}function recordRepairOutcome(e){try{emitRepairOutcomeTelemetry(e)}catch{}}function emitRepairOutcomeTelemetry(e){const{toolName:t,outcome:n,validationError:r}=e,o="recovered"===n?`tool_input_repaired:${t}`:`tool_input_invalid:${t}`,s=Array.from(new Set(r.issues.map(e=>e.code))).join(",");trackError({error:r,context:{component:cs.TOOL_REPAIR,heading:o,code:n,"tool.name":t,"repair.outcome":n,"repair.issue_count":r.issues.length,"repair.issue_codes":s}})}function deepCloneToolInput(e){if(null===e)return e;if("object"!=typeof e)return e;if(Array.isArray(e))return e.map(deepCloneToolInput);const t=e,n={};for(const[e,r]of Object.entries(t))n[e]=deepCloneToolInput(r);return n}yS(),Ot(),Ot(),Ot(),Ot(),__name(formatZodErrorForModel,"formatZodErrorForModel"),Ot(),ps(),gs(),__name(recordRepairOutcome,"recordRepairOutcome"),__name(emitRepairOutcomeTelemetry,"emitRepairOutcomeTelemetry"),Ot(),Ot(),__name(deepCloneToolInput,"deepCloneToolInput"),Ot();var Wb=__name(({parent:e,key:t,value:n,issue:r})=>"invalid_type"===r.code&&"array"===r.expected&&"object"==typeof n&&null!==n&&!Array.isArray(n)&&0===Object.keys(n).length&&(delete e[t],!0),"dropEmptyObjectPlaceholder");Ot();var Gb=__name(({parent:e,key:t,value:n})=>null==n&&(delete e[t],!0),"dropNullOrUndefinedField");Ot();var Vb=__name(({parent:e,key:t,value:n,issue:r})=>{if("invalid_type"!==r.code)return!1;if("array"!==r.expected)return!1;if("string"!=typeof n)return!1;const o=n.trim();if(!o.startsWith("["))return!1;if(!o.endsWith("]"))return!1;let s;try{s=JSON.parse(o)}catch{return!1}return!!Array.isArray(s)&&(e[t]=s,!0)},"parseJsonStringifiedArray");Ot();var Qb=[Gb,Wb,Vb,__name(({parent:e,key:t,value:n,issue:r})=>"invalid_type"===r.code&&"array"===r.expected&&"string"==typeof n&&(e[t]=[n],!0),"wrapBareStringAsArray")];function repairToolInput(e,t){if(null===e)return e;if("object"!=typeof e)return e;const n=deepCloneToolInput(e);let r=!1;for(const e of t.issues)applyRepairsToIssue(n,e)&&(r=!0);return r?n:e}function applyRepairsToIssue(e,t){const n=t.path;if(0===n.length)return!1;const r=walkToParentContainer(e,n);if(void 0===r)return!1;const o=n[n.length-1];if(void 0===o)return!1;const s=r[o];for(const e of Qb)if(e({parent:r,key:o,value:s,issue:t}))return!0;return!1}function walkToParentContainer(e,t){const n=t.slice(0,-1);let r=e;for(const e of n){if(null===r)return;if("object"!=typeof r)return;r=r[e]}if(null!==r&&"object"==typeof r)return r}function parseRepairedToolInput(e){const t=e.schema.safeParse(e.input);if(t.success)return{ok:!0,data:t.data};const n=repairToolInput(e.input,t.error);if(n===e.input)return recordRepairOutcome({toolName:e.toolName,outcome:"unrepairable",validationError:t.error}),{ok:!1,message:formatZodErrorForModel(e.toolName,t.error)};const r=e.schema.safeParse(n);return r.success?(recordRepairOutcome({toolName:e.toolName,outcome:"recovered",validationError:t.error}),{ok:!0,data:r.data}):(recordRepairOutcome({toolName:e.toolName,outcome:"unrepairable",validationError:r.error}),{ok:!1,message:formatZodErrorForModel(e.toolName,r.error)})}__name(repairToolInput,"repairToolInput"),__name(applyRepairsToIssue,"applyRepairsToIssue"),__name(walkToParentContainer,"walkToParentContainer"),__name(parseRepairedToolInput,"parseRepairedToolInput"),Ot();var Kb=/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g,Yb=/^https?:\/\//;function unwrapMarkdownAutoLinks(e){return e.replace(Kb,(e,t,n)=>n.replace(Yb,"")!==t?e:t)}function pathString(){return f.preprocess(e=>"string"!=typeof e?e:unwrapMarkdownAutoLinks(e),f.string())}__name(unwrapMarkdownAutoLinks,"unwrapMarkdownAutoLinks"),__name(pathString,"pathString");var Jb=f.object({command:f.string().min(1,"Command cannot be empty"),args:f.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},f.array(pathString())).optional(),directory:pathString().optional(),timeout:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number()).optional()}),Xb=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,i){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=i}};Ot();var Zb=f.object({absolutePath:pathString().describe("The absolute path to the file to read"),offset:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number()).optional().describe("Optional line number to start reading from (0-based index)"),limit:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number()).optional().describe("Optional number of lines to read")});f.object({content:f.union([f.string(),f.instanceof(Buffer)]),contentType:f.enum(["text","binary"]),fileType:f.string(),size:f.number(),linesRead:f.number().optional(),appliedDefaults:f.object({defaulted:f.enum(["offset","limit"]),offset:f.number(),limit:f.number(),reason:f.string()}).optional()});var eC=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};Ot();var tC=f.object({filePath:pathString().describe("The absolute path to the file to edit"),oldValue:f.string().describe("The text to replace"),newValue:f.string().describe("The new text to insert"),replacementCount:f.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:f.boolean().optional().describe("Whether to replace all occurrences (default: false)")});f.object({path:f.string(),replacementsCount:f.number(),oldContent:f.string(),newContent:f.string()}),f.object({name:f.string(),message:f.string(),code:f.string().optional()}),Ot();var nC=f.object({filePath:pathString().describe("The absolute path where the file should be written"),content:f.string().describe("The content to write to the file")});f.object({success:f.boolean(),message:f.string(),path:f.string().optional()});var rC=class extends Error{static{__name(this,"WriteFileError")}code;constructor(e,t){super(e),this.name="WriteFileError",this.code=t}},oC=f.object({type:f.literal("command"),command:f.string().min(1),timeout:f.number().positive().max(600).optional(),async:f.boolean().optional(),failClosed:f.boolean().optional()}),sC=f.object({matcher:f.string().optional(),hooks:f.array(oC).min(1)}),iC=f.object({hooks:f.record(f.string(),f.array(f.unknown())).optional()}).passthrough(),aC=f.nativeEnum(zb),lC=f.object({session_id:f.string().min(1),transcript_path:f.string().min(1),cwd:f.string().min(1),hook_event_name:aC,permission_mode:f.string().optional()}),cC={[iS.SHELL_COMMAND]:"SHELL",[iS.READ_FILE]:"READ",[iS.EDIT_FILE]:"EDIT",[iS.WRITE_FILE]:"WRITE",[iS.GREP]:"SEARCH",[iS.GLOB]:"GLOB",[iS.READ_DIRECTORY]:"LIST",[iS.READ_MULTIPLE_FILES]:"READ_MULTI",[iS.TODO_WRITE]:"TODOS",[iS.THINKING]:"THINK",[iS.KILL_SHELL]:"KILL_SHELL",[iS.QUESTION]:"QUESTION",[iS.EXPLORE]:"EXPLORE",[aS.WEB_SEARCH]:"WEB_SEARCH",[aS.WEB_FETCH]:"WEB_FETCH",[iS.ENTER_PLAN_MODE]:"ENTER_PLAN_MODE",[iS.EXIT_PLAN_MODE]:"EXIT_PLAN_MODE",[iS.DIAGNOSTICS]:"DIAGNOSTICS",[iS.GET_SELF_KNOWLEDGE]:"GET_SELF_KNOWLEDGE"};Jb.passthrough(),Zb.passthrough(),tC.passthrough(),nC.passthrough(),iS.SHELL_COMMAND,iS.READ_FILE,iS.EDIT_FILE,iS.WRITE_FILE;var uC=f.record(f.string(),f.unknown()),dC=lC.extend({hook_event_name:f.literal("PreToolUse"),tool_use_id:f.string().optional(),tool_name:f.string().min(1),tool_display_name:f.string().min(1),tool_input:uC}),mC=lC.extend({hook_event_name:f.literal("PostToolUse"),tool_use_id:f.string().optional(),tool_name:f.string().min(1),tool_display_name:f.string().min(1),tool_input:uC,tool_response:f.string()});f.discriminatedUnion("hook_event_name",[dC,mC]);var pC=f.object({continue:f.boolean().optional(),suppressOutput:f.boolean().optional(),stopReason:f.string().optional(),systemMessage:f.string().optional()}),gC=pC.extend({hookSpecificOutput:f.object({hookEventName:f.literal("PreToolUse").optional(),additionalContext:f.string().optional(),permissionDecision:f.enum(["allow","deny"]).optional(),permissionDecisionReason:f.string().optional()}).strict().optional()}),hC=pC.extend({decision:f.enum(["block"]).optional(),reason:f.string().optional(),hookSpecificOutput:f.object({hookEventName:f.literal("PostToolUse").optional(),additionalContext:f.string().optional()}).strict().optional()});function getOrCompileRegex(e){const{cache:t,pattern:n}=e,r=t.get(n);if(r)return r;if(n.length>200)return dlog(`[Hook] Matcher regex too long (${n.length} > 200): "${n.slice(0,50)}..."`),null;try{const e=new RegExp(n,"i");return t.set(n,e),e}catch{return dlog(`[Hook] Invalid matcher regex: "${n}"`),null}}function getErrorMessage(e){return e instanceof Error?e.message:String(e)}function resolveBlockReason(e){return e.reason||e.stderr||e.fallback}function logFireAndForget(e){e.catch(e=>dlog(`[Hook] Fire-and-forget failed: ${getErrorMessage(e)}`))}function buildHookLabel(e){const t=e.command.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32)||"hook";return`${e.source}#${e.definitionIndex}.${e.hookIndex} ${t}`}Ot(),Kn(),__name(getOrCompileRegex,"getOrCompileRegex"),Ot(),Kn(),__name(getErrorMessage,"getErrorMessage"),__name(resolveBlockReason,"resolveBlockReason"),__name(logFireAndForget,"logFireAndForget"),__name(buildHookLabel,"buildHookLabel");var fC=/[|;<>`]|&&|\|\||\$\(/,yC=/\.(?:sh|js|ts|mjs|cjs)$/i,wC=/^[A-Za-z0-9_.\-]+$/;function deriveCommandName(e){const t=e.trim();if(!t)return null;if(fC.test(t))return null;const n=t.split(/\s+/,1)[0]??"";if(!n)return null;if(!(n.startsWith("/")||n.startsWith("./")||n.startsWith("~/")||wC.test(n)))return null;const r=n.lastIndexOf("/");return(r>=0?n.slice(r+1):n).replace(yC,"")}function buildHookDisplayLabel(e){return deriveCommandName(e)??e}function deriveScriptPath(e){const t=e.trim();if(!t)return;if(fC.test(t))return;const n=t.split(/\s+/,1)[0]??"";return n.startsWith("/")||n.startsWith("./")||n.startsWith("~/")?n:void 0}function firstNonEmptyLine(e){for(const t of e.split("\n")){const e=t.trim();if(e)return e}}function getProjectLocalPath(t){return e.join(t,".commandcode","settings.local.json")}function getProjectSharedPath(t){return e.join(t,".commandcode","settings.json")}function getUserSettingsPath(){return e.join(w.homedir(),".commandcode","settings.json")}async function loadSettingsFile(e){let t,n;try{t=await v.readFile(e,"utf-8")}catch(t){return"ENOENT"===t.code?null:{warning:`Failed to read hooks settings in ${e}: ${getErrorMessage(t)}`}}try{n=JSON.parse(t)}catch(t){return{warning:`Invalid JSON in ${e}: ${getErrorMessage(t)}`}}const r=iC.safeParse(n);return r.success?{settings:{hooks:r.data.hooks}}:{warning:`Invalid hooks structure in ${e}: ${r.error.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ")}`}}function loadHooksFromSource(e){const{settings:t,validationWarnings:n,normalizeEventName:r}=e;if(!t.hooks)return;const o={settingsPath:e.settingsPath,source:e.source,seenCommands:e.seenCommands,entries:e.entries,matcherCache:e.matcherCache};for(const[e,s]of Object.entries(t.hooks)){const t=r(e);if(!t){const t=`Unknown event "${e}" in ${o.settingsPath}, skipping`;dlog(`[Hook] ${t}`),n.push(t);continue}if(!Array.isArray(s)){const t=`Invalid hooks.${e} in ${o.settingsPath}: expected array, got ${typeof s}`;dlog(`[Hook] ${t}`),n.push(t);continue}loadDefinitionsForEvent({ctx:o,eventName:t,definitions:s,validationWarnings:n})}}function loadDefinitionsForEvent(e){const{ctx:t,eventName:n,definitions:r,validationWarnings:o}=e;for(const[e,s]of r.entries()){const r=sC.safeParse(s);if(!r.success){const e=`Invalid hook in ${t.settingsPath}: ${r.error.message}`;dlog(`[Hook] ${e}`),o.push(e);continue}const i=r.data;if(void 0!==i.matcher&&!getOrCompileRegex({cache:t.matcherCache,pattern:i.matcher})){const e=i.matcher.length>200?`matcher exceeds 200 char cap (got ${i.matcher.length})`:"invalid regex",r=`Invalid matcher in ${t.settingsPath} (event=${n}): ${e}. Hook skipped. Matcher: "${i.matcher.slice(0,80)}"`;dlog(`[Hook] ${r}`),o.push(r);continue}for(const[r,o]of i.hooks.entries())processHookConfig({ctx:t,def:i,eventName:n,definitionIndex:e,hookIndex:r,rawHookConfig:o})}}function processHookConfig(e){const{ctx:t,def:n,eventName:r,definitionIndex:o,hookIndex:s,rawHookConfig:i}=e,a=`${r}:${n.matcher??""}:${i.command}`;t.seenCommands.has(a)?dlog(`[Hook] Hook in ${t.settingsPath} shadowed by higher-priority source (event=${r}, matcher=${n.matcher??"(any)"}, command=${i.command})`):(t.seenCommands.add(a),t.entries.push({config:i,source:t.source,eventName:r,matcher:n.matcher,definitionIndex:o,hookIndex:s}))}function resolveScopePaths(e){const t=[{scope:"user",filePath:getUserSettingsPath()}];return e&&(t.push({scope:"projectShared",filePath:getProjectSharedPath(e)}),t.push({scope:"projectLocal",filePath:getProjectLocalPath(e)})),t}async function readDisabledNames(e){let t,n;try{t=await v.readFile(e,"utf-8")}catch(t){return"ENOENT"===t.code||dlog(`[Skills] Failed to read settings ${e}: ${t.message}`),null}try{n=JSON.parse(t)}catch(t){return dlog(`[Skills] Invalid JSON in ${e}: ${t.message}`),null}const r=Ub.safeParse(n);return r.success?r.data.disabledSkills??null:(dlog(`[Skills] Invalid disabledSkills shape in ${e}`),null)}function resolveProjectRoot(e){return e?.projectRoot?e.projectRoot:findGitRoot()??walkUpToFindDir({dirName:".commandcode"})}async function loadDisabledSkills(e){const t=resolveProjectRoot(e),n=resolveScopePaths(t),r=new Set,o=new Map;for(const{scope:e,filePath:t}of n){const n=await readDisabledNames(t);if(n)for(const t of n)r.add(t),o.has(t)||o.set(t,e)}return{names:r,bySkill:o,noProjectRoot:!t}}__name(deriveCommandName,"deriveCommandName"),__name(buildHookDisplayLabel,"buildHookDisplayLabel"),__name(deriveScriptPath,"deriveScriptPath"),__name(firstNonEmptyLine,"firstNonEmptyLine"),__name(getProjectLocalPath,"getProjectLocalPath"),__name(getProjectSharedPath,"getProjectSharedPath"),__name(getUserSettingsPath,"getUserSettingsPath"),__name(loadSettingsFile,"loadSettingsFile"),__name(loadHooksFromSource,"loadHooksFromSource"),__name(loadDefinitionsForEvent,"loadDefinitionsForEvent"),__name(processHookConfig,"processHookConfig"),Kn(),__name(resolveScopePaths,"resolveScopePaths"),__name(readDisabledNames,"readDisabledNames"),__name(resolveProjectRoot,"resolveProjectRoot"),__name(loadDisabledSkills,"loadDisabledSkills");var SC=Promise.resolve();async function readSettingsObject(e){try{const t=await v.readFile(e,"utf-8"),n=JSON.parse(t);return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}catch(e){if("ENOENT"===e.code)return{};throw e}}async function writeDisabledSkillsTo(t,n){const r=await readSettingsObject(t);0===n.length?delete r.disabledSkills:r.disabledSkills=n,await v.mkdir(e.dirname(t),{recursive:!0}),await v.writeFile(t,JSON.stringify(r,null,2)+"\n")}async function setSkillEnabled(e,t,n){const r=resolveProjectRoot(n),o=n?.scope??"projectLocal",s=r||"user"===o?o:"user";let i;switch(s){case"user":i=getUserSettingsPath();break;case"projectShared":i=getProjectSharedPath(r);break;case"projectLocal":i=getProjectLocalPath(r)}const a=SC.then(async()=>{const n=await readDisabledNames(i)??[],r=new Set(n);t?r.delete(e):r.add(e),await writeDisabledSkillsTo(i,[...r].sort())});return SC=a.catch(()=>{}),await a,s}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(readSettingsObject,"readSettingsObject"),__name(writeDisabledSkillsTo,"writeDisabledSkillsTo"),__name(setSkillEnabled,"setSkillEnabled"),Ot(),Ot(),Ot(),Ot(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),Ao(),Ot(),Ao();var EC=new Set(["DIRECTORY_OUTSIDE_WORKSPACE"]);function isSoftToolErrorCode(e){return void 0!==e&&EC.has(e)}function formatOutsideWorkspaceMessage(e,t){return`${t===(e.replace(/[/\\]+$/,"")||e)?e:`${e} (resolved to ${t})`} is outside workspace (allowed: ${getWorkspaceDirectories().join(", ")})`}async function readFileContent(t){const{absolutePath:n,offset:r,limit:o}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new eC("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);if(!isPathInWorkspace(s))throw new eC(formatOutsideWorkspaceMessage(n,s),"DIRECTORY_OUTSIDE_WORKSPACE");try{await v.access(s,L.constants.F_OK|L.constants.R_OK)}catch{throw new eC(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await v.stat(s)).isFile())throw new eC("Path does not point to a file","NOT_A_FILE");const i=getFileType(s),a=isBinaryFile(i);let l,u=r,d=o;if(void 0===u&&void 0!==d?(u=0,l={defaulted:"offset",offset:0,limit:d,reason:"offset was not provided; defaulted to 0 (read from start of file). To read a different range, retry with both offset and limit."}):void 0!==u&&void 0===d&&(d=2e3,l={defaulted:"limit",offset:u,limit:2e3,reason:"limit was not provided; defaulted to 2000 lines. To read more or fewer lines, retry with both offset and limit."}),void 0!==u&&u<0)throw new eC("Offset must be >= 0","INVALID_OFFSET");if(void 0!==d&&d<=0)throw new eC("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await v.readFile(s);return{fileType:i,content:e,size:e.length,contentType:"binary"}}if(void 0!==u&&void 0!==d){const e=await readTextFileLines(s,u,d);return{fileType:i,contentType:"text",content:e.content,size:Buffer.byteLength(e.content,"utf8"),linesRead:e.linesRead,appliedDefaults:l}}{const e=await v.readFile(s,"utf8");return{content:e,fileType:i,contentType:"text",size:Buffer.byteLength(e,"utf8")}}}catch(e){if(e instanceof eC)throw e;throw new eC(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(isSoftToolErrorCode,"isSoftToolErrorCode"),__name(formatOutsideWorkspaceMessage,"formatOutsideWorkspaceMessage"),__name(readFileContent,"readFileContent");var bC={".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",...bC}[n]||"unknown"}function isBinaryFile(e){return Object.values(bC).includes(e)}async function readTextFileLines(e,t,n){const r=(await v.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),i=r.slice(o,s);return{content:i.join("\n"),linesRead:i.length}}function formatReadSummary({successfulReads:e,totalFiles:t}){return`Read ${e}/${t} ${1===t?"file":"files"}`}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),Ot(),Ot(),__name(formatReadSummary,"formatReadSummary");var CC=/^Read\s+(\d+)\/(\d+)\s+files?(?:,\s+(\d+)\s+lines?)?$/i;function formatOutput(e){const t=[];if("binary"===e.contentType)return t.push(formatReadSummary({successfulReads:1,totalFiles:1})),t.push(`Binary file: ${e.fileType}`),t.join("\n");const n=e.linesRead??(e.content?String(e.content).split("\n").length:0);if(e.appliedDefaults){const r=e.appliedDefaults,o=r.offset+n-1;t.push(`${formatReadSummary({successfulReads:1,totalFiles:1})}, lines ${r.offset}-${o} (${n} of ${r.limit} requested)`),t.push(`Note: ${r.reason}`)}else t.push(`${formatReadSummary({successfulReads:1,totalFiles:1})}, ${n} ${1===n?"line":"lines"}`);return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(formatOutput,"formatOutput");var vC={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 path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"read_file",schema:Zb,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput(await readFileContent(e))}catch(e){return e instanceof eC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading file"}},"execute")};Ot(),Ot(),Ao(),Ot(),Ot();var kC=f.object({backupFileName:f.string().nullable(),version:f.number().int().positive(),backupTime:f.string().datetime()}),TC=f.object({messageId:f.string().uuid(),trackedFileBackups:f.record(f.string(),kC),timestamp:f.string().datetime()});f.object({type:f.literal("file-history-snapshot"),messageId:f.string().uuid(),snapshot:TC,isSnapshotUpdate:f.boolean()}),f.object({maxFileSize:f.number().int().positive().default(10485760),retentionDays:f.number().int().positive().default(30)});var _C=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`${R.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(S.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 k.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 k.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await k.writeFile(r,n);const e=await k.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 k.rename(r,t)}catch(e){try{await k.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await k.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await k.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),i=Math.floor(s/24);return i>0?`${i}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}Ot(),Ot(),wn(),__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"),hs();var xC={maxFileSize:10485760,retentionDays:30},AC=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...xC,...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 k.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 i={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,i),this.trackedState.versions.set(t,n),{success:!0,backup:i,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:cs.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 k.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new _C(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:cs.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await k.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 k.access(t,k.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 k.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await k.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await k.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};Ot(),as(),hs();var PC=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new AC({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,i=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:cs.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(i=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const a=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&a.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&a.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:a}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:i}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}};Ot();var IC=null;function initializeCheckpointService(e){const{sessionId:t}=e;return IC=new PC({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return IC?IC.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:i=1}=t;if(!n)throw createFileEditError("filePath is required","INVALID_PATH");if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const a=e.normalize(n);if(!isPathInWorkspace(a))throw createFileEditError(formatOutsideWorkspaceMessage(n,a),"DIRECTORY_OUTSIDE_WORKSPACE");if(!r)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==o)throw createFileEditError("newValue is required","INVALID_INPUT");if(!s&&i<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await O.access(a,q.F_OK|q.R_OK|q.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${a}`,"FILE_ACCESS_ERROR")}let l;try{const e=await readFileContent({absolutePath:a});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");l=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 u=(l.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===u)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let d,m;if(s)d=u;else if(d=i,d>u)throw createFileEditError(`Expected ${d} replacements, but only found ${u} occurrences`,"INSUFFICIENT_MATCHES");let g=0;if(s||d===u)m=l.split(r).join(o),g=u;else{m=l;for(let e=0;e<d;e++){const e=m.indexOf(r);-1!==e&&(m=m.substring(0,e)+o+m.substring(e+r.length),g++)}}if(0===g)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:a}),await O.writeFile(a,m,"utf-8"),{path:a,replacementsCount:g,oldContent:l,newContent:m}}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"),Ot(),__name(formatOutput2,"formatOutput");var NC={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 path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"edit_file",schema:tC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput2(await editFile(e))}catch(e){return e&&"object"==typeof e&&"code"in e&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while editing file"}},"execute")};Ot(),Ot();var RC=f.object({path:pathString().describe("The absolute path to the directory to read"),exclude:f.array(pathString()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:f.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});f.object({files:f.array(f.string()),directories:f.array(f.string())});var MC=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 MC("Path must be absolute, not relative","INVALID_PATH");const s=e.normalize(n);if(!isPathInWorkspace(s))throw new MC(formatOutsideWorkspaceMessage(n,s),"DIRECTORY_OUTSIDE_WORKSPACE");try{if(!(await v.stat(n)).isDirectory())throw new MC("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof MC)throw e;throw new MC(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await v.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const i=[...r,...s],a=[],l=[];for(const r of t){if(shouldIgnoreEntry(r,i))continue;const t=e.join(n,r);try{const e=await v.stat(t);e.isDirectory()?l.push(r):e.isFile()&&a.push(r)}catch(e){dlog(`[read-directory] skipped ${t}: ${e instanceof Error?e.message:String(e)}`)}}return{files:a.sort(),directories:l.sort()}}catch(e){if(e instanceof MC)throw e;throw new MC(`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 findGitRoot2(t);for(;r&&isWithinGitRoot(r,o);){const t=e.join(r,".gitignore");try{const e=(await v.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch{}const o=e.dirname(r);if(o===r)break;r=o}}catch{}return n}async function isInGitRepository(e){try{return null!==await findGitRoot2(e)}catch{return!1}}async function findGitRoot2(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await v.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(Xe(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")}Ot(),Ao(),Kn(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot2,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),Ot(),__name(formatOutput3,"formatOutput");var LC={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 path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"read_directory",schema:RC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput3(await readDirectory(e))}catch(e){return e instanceof MC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading directory"}},"execute")};async function writeFile3({filePath:e,content:n}){const o=e.startsWith("~/")?t.join(S.homedir(),e.slice(2)):e;if(!i(o))throw new Error(`Invalid file path: '${o}'. Only absolute paths are supported.`);const s=t.normalize(o);if(!isPathInWorkspace(s))throw new rC(formatOutsideWorkspaceMessage(e,s),"DIRECTORY_OUTSIDE_WORKSPACE");try{const e=r(s);return D(e)||await T(e,{recursive:!0}),await backupFileBeforeEdit({filePath:s}),await _(s,n,"utf-8"),{path:s,bytesWritten:Buffer.byteLength(n,"utf-8")}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";throw new Error(`Failed to write file '${s}': ${t}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}Ot(),Ot(),Ao(),__name(writeFile3,"writeFile"),Ot(),__name(formatOutput4,"formatOutput");var $C={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). The path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"write_file",schema:nC,input:e});if(!t.ok)return t.message;try{const e=t.data,n=await writeFile3(e);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return e instanceof rC&&isSoftToolErrorCode(e.code)?e.message:formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")};Ot(),Ot();var DC=f.object({include:f.array(pathString()).describe("Array of glob patterns to include files"),exclude:f.array(pathString()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:f.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:f.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:pathString().optional().describe("Base directory for relative paths. Default: current working directory")}),OC=f.object({filePath:f.string(),content:f.string(),fileType:f.string(),size:f.number()});f.object({content:f.string(),filesRead:f.array(f.string()),errors:f.array(f.object({file:f.string(),error:f.string()})),fileDetails:f.array(OC)});var FC=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};Ot(),Ao();var qC=["**/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:i=process.cwd()}=e;if(!n||0===n.length)throw new FC("At least one include pattern must be provided","NO_PATTERNS");const a=t.resolve(i);if(!isPathInWorkspace(a))throw new FC(formatOutsideWorkspaceMessage(i,a),"DIRECTORY_OUTSIDE_WORKSPACE");const l={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...qC);const i=await findMatchingFiles({include:n,exclude:e,gitIgnore:o,targetDirectory:a});for(const e of i)try{const n=t.resolve(a,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 FC)throw e;throw new FC(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){const t=e.fileDetails.length,n=e.filesRead.length,r=e.errors.length,{fileTypesCounts:o}=e.fileDetails.reduce((e,t)=>(e.fileTypesCounts[t.fileType]=(e.fileTypesCounts[t.fileType]||0)+1,e),{fileTypesCounts:{}});return{totalFiles:t,successfulReads:n,failedReads:r,fileTypesCounts:o,contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];if(n.push(formatReadSummary(t)),e.errors.length>0){n.push("Errors:");for(const t of e.errors)n.push(` - ${t.file}: ${t.error}`)}return n.push("--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),Ot(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var jC={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. The path must resolve inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"read_multiple_files",schema:DC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput5(await readMultipleFiles(e))}catch(e){return e instanceof FC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading multiple files"}},"execute")};Ot(),Ot();var UC=f.object({pattern:f.string().min(1,"Pattern is required"),include:f.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},f.array(pathString())).optional(),directory:pathString().optional()});Ot(),as(),Ot(),as(),jf(),Qr();var BC=rs;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){const e=n,r=e.image??e.source?.data??"";t+=estimateImageTokens("string"==typeof r?r.replace(/^data:[^;]+;base64,/,""):"")}else if("tool-call"===n.type){const e=n;t+=5,e.toolName&&(t+=estimateTextTokens(e.toolName)),e.input&&(t+=1.1*estimateTextTokens(JSON.stringify(e.input)))}else if("tool-result"===n.type){const e=n;t+=3,e.output&&"object"==typeof e.output&&"string"==typeof e.output.value&&(t+=estimateTextTokens(e.output.value))}return Math.ceil(t)}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)>BC}__name(estimateTokens,"estimateTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit");var zC="Results are too large. Let's try a more specific pattern to narrow it down. There's a 25K token limit on tool outputs per request.";function checkToolOutputTokensLimit(e){return exceedsOutputTokenLimit(e)?zC: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 execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=be(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>ts)return i=zC,void o.kill("SIGTERM");s+=t}catch(e){i+=`\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(i.length+t.length>ns)return void(i+="\n[Error output truncated: too large]");i+=t}catch(e){i+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||i?r(new Error(i||`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"),i=[];for(const e of s){const t=parseGrepLine(e);t&&i.push(t)}return i}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),Ot(),__name(formatGrepResults,"formatGrepResults");var HC={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=>{const t=parseRepairedToolInput({toolName:"grep",schema:UC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatGrepResults(await grepSearchInDirectory(e))}catch(e){return e instanceof Error?e.message===zC?e.message:`ERROR: ${e.message}`:"ERROR: Unknown error occurred while searching files"}},"execute")};Ot(),Ot();var WC=f.object({pattern:f.string().min(1,"Pattern is required"),path:pathString().optional()}),GC=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 GC("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new GC(formatOutsideWorkspaceMessage(r,e),"DIRECTORY_OUTSIDE_WORKSPACE");const o=await Ze(n,{cwd:e,ignore:gn,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 k.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 GC)throw e;if(e instanceof Error)throw new GC(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new GC("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")}Ot(),wn(),Ao(),__name(globSearch,"globSearch"),Ot(),__name(formatGlobResults,"formatGlobResults");var VC={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. The path must resolve inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"glob",schema:WC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatGlobResults(await globSearch(e))}catch(e){return e instanceof GC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while finding files"}},"execute")};async function executeShellCommand(t){const{command:n,args:r=[],directory:o,timeout:s=3e4}=t,i=Date.now();if(!n.trim())throw new Xb("Command cannot be empty","EMPTY_COMMAND");const a=o?e.resolve(process.cwd(),o):process.cwd();if(o&&!isPathInWorkspace(a))throw new Xb(formatOutsideWorkspaceMessage(o,a),"DIRECTORY_OUTSIDE_WORKSPACE");try{if(!(await k.stat(a)).isDirectory())throw new Xb(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof Xb)throw e;throw new Xb(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:a,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((t,o)=>{let a="",l="",u=!1,d=!1;const m=r.length>0?tt([n,...r]):n,g=setTimeout(()=>{if(!u){h.kill("SIGTERM");const e=Date.now()-i;o(new Xb(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",a,l,e))}},s),h=be(m,[],e);h.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>ts)return l=zC,d=!0,void h.kill("SIGTERM");a+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,h.kill("SIGTERM")}}),h.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>ns)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"}]`}}),h.on("close",(e,n)=>{u=!0,clearTimeout(g);const r=Date.now()-i;0===e?t({stdout:a.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):o(new Xb(d?zC:`Command failed with exit code ${e}`,d?"OUTPUT_TRUNCATED":"COMMAND_FAILED",e,n,a.trim(),l.trim(),r))}),h.on("error",e=>{u=!0,clearTimeout(g);const t=Date.now()-i;o(new Xb(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),l.trim(),t))})})}catch(e){if(e instanceof Xb)throw e;throw new Xb(`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")}Ot(),Ot(),as(),Ao(),__name(executeShellCommand,"executeShellCommand"),Ot(),__name(formatShellCommandResult,"formatShellCommandResult");var QC={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. Accepts absolute or relative paths; relative paths are resolved against the current working directory. The path must be inside the workspace (the current directory or one of its added directories) and must exist. Examples: "src" runs in src folder, "packages/core" runs in packages/core, "/Users/you/project/packages/core" runs in the specified absolute path. 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=>{const t=parseRepairedToolInput({toolName:"shell_command",schema:Jb,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatShellCommandResult(await executeShellCommand(e))}catch(e){if(e instanceof Xb){if("OUTPUT_TRUNCATED"===e.code)return[e.stdout,zC].filter(Boolean).join("\n");if(isSoftToolErrorCode(e.code))return e.message;if(e.stdout||e.stderr){let t=`ERROR: ${e.message}`;return e.stdout&&(t+=`\nOutput:\n${e.stdout}`),e.stderr&&(t+=`\nError output:\n${e.stderr}`),t}return`ERROR: ${e.message}`}return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while executing command"}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}Ot(),Ot(),__name(think,"think");var KC={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)}Ot(),Ot(),__name(todoWrite,"todoWrite");var YC={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")}Ot(),Ot(),__name(askUserQuestion,"askUserQuestion"),Ot(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var JC={name:"ask_user_question",description:'Ask the user a question with predefined answer choices.\n\nUse it when the request has more than one reasonable reading, when a requirement or preference is missing, or when the user needs to pick between viable approaches.\n\n- A free-text reply ("Type something") is always offered to the user. Never list it yourself.\n- To surface a recommendation, put that option first and append " (Recommended)" to its label.\n- Set multiSelect: true when more than one option can apply to the same 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:'Full sentence ending in "?". Specific enough that the user can answer without rereading the conversation.'},header:{type:"string",description:'Short topic label, 20 characters or fewer so it fits in a chip. Used to disambiguate when multiple questions are asked at once. Examples: "DB choice", "Test runner", "Cache layer".'},options:{type:"array",description:'2 to 4 distinct answer choices. They must be mutually exclusive unless multiSelect is true. Do not include a "Type something" or other free-text choice; the user is always offered one automatically.',items:{type:"object",properties:{label:{type:"string",description:'1 to 5 words, the answer the user picks. Put your recommended choice first and append " (Recommended)" to its label.'},description:{type:"string",description:"One-sentence consequence: what the user gets, gives up, or commits to by picking this answer. Use it to explain trade-offs."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true when more than one option can apply to the same question. Defaults to a single answer."}},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")};Ot(),Ot();var XC=f.object({port:f.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:f.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"}),ZC=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=be(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",i="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{i+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(i.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 i=parseInt(r[r.length-1],10);if(!isNaN(i))return i}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new ZC(`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 ZC("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 ZC(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${Pe.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}Ot(),__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"),Ot(),__name(formatKillshellResult,"formatKillshellResult");var ev={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=XC.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?"ERROR: Permission denied — Process termination was not approved":formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while killing process"}},"execute")};Ot();var tv={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")};Ot();var nv={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")};Ot(),Ot(),Ot(),Ot();var rv=f.preprocess(e=>{if("string"==typeof e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{return[e]}return e},f.array(pathString())).optional(),ov=f.object({filePaths:rv.describe('Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.')});Ot(),Ot(),Kn(),Ot(),Ot();var sv=nt().add([".env",".env.*","*.pem","*.key","id_rsa","id_rsa.*","id_ed25519","id_ed25519.*","id_ecdsa","id_ecdsa.*","credentials","credentials.*","*.crt",".npmrc",".pypirc",".netrc"]),iv=new Map,av=__name(async t=>{const n=e.resolve(t);try{return await v.realpath(n)}catch{return n}},"canonicalize"),lv=__name(async t=>{let n=e.resolve(t);for(;;){try{const t=await v.stat(e.join(n,".git"));if(t.isDirectory()||t.isFile())return n}catch{}const t=e.dirname(n);if(t===n)return null;n=t}},"findWorkingTreeRoot"),cv=__name(t=>{const n=e.basename(t);return!!n&&sv.ignores(n)},"hasSensitiveBasename"),uv=__name(async(e,t)=>{const n=new Map;return 0===t.length?n:new Promise(r=>{const o=[];let s=!1,i=!1;const a=__name(e=>{if(!i){i=!0;for(const r of t)n.set(r,e.has(r));r(n)}},"settle");try{const n=be("git",["check-ignore","--stdin","-z"],{cwd:e,stdio:["pipe","pipe","ignore"]}),r=setTimeout(()=>{s=!0;try{n.kill()}catch{}a(new Set)},2e3);n.stdin.on("error",()=>{}),n.stdout.on("data",e=>{o.push(e)}),n.on("error",()=>{clearTimeout(r),a(new Set)}),n.on("close",e=>{if(clearTimeout(r),s||0!==e&&1!==e)return void a(new Set);const t=Buffer.concat(o).toString("utf8");a(new Set(t.split("\0").filter(Boolean)))});try{n.stdin.write(t.join("\0")+"\0"),n.stdin.end()}catch{}}catch{a(new Set)}})},"checkGitIgnoredBatch"),dv=__name(async e=>{const t=Date.now(),n=iv.get(e);if(n&&n.expiresAt>t)return n;const r=await lv(e)??e,o={results:new Map,workingTreeRoot:r,expiresAt:t+3e4};if(iv.size>=64){const e=iv.keys().next().value;void 0!==e&&iv.delete(e)}return iv.set(e,o),o},"getOrCreateWorkspaceCache"),mv=__name(async(t,n)=>(await Promise.all(t.map(async t=>{if(!t)return null;const r=await av(t),o=e.relative(n,r);if(".."===o||o.startsWith(`..${e.sep}`)||e.isAbsolute(o)||""===o)return null;const s=o.split(e.sep).join("/");return sv.ignores(s)||cv(t)?null:{originalPath:t,canonPath:r}}))).filter(e=>null!==e),"classifyCandidates"),pv=__name(async(e,t)=>{const n=new Set;if(!t||0===e.length)return n;const r=await av(t),o=await mv(e,r);if(0===o.length)return n;const s=await dv(r),i=[];for(const e of o){const t=s.results.get(e.canonPath);void 0!==t?t||n.add(e.originalPath):i.push(e)}if(i.length>0){const e=await uv(s.workingTreeRoot,i.map(e=>e.canonPath));for(const t of i){const r=e.get(t.canonPath)??!1;s.results.set(t.canonPath,r),r||n.add(t.originalPath)}}return n},"getSafePathSet"),gv=__name(async e=>{const t=e.workspace.rootPath;if(!t){const t=!e.activeFile||!cv(e.activeFile.path);return{...e,activeFile:t?e.activeFile:null,selection:t?e.selection:null,openFiles:e.openFiles.filter(e=>!cv(e.path))}}const n=[...e.activeFile?[e.activeFile.path]:[],...e.openFiles.map(e=>e.path)],r=await pv(n,t),o=!e.activeFile||r.has(e.activeFile.path);return{...e,activeFile:o?e.activeFile:null,selection:o?e.selection:null,openFiles:e.openFiles.filter(e=>r.has(e.path))}},"filterIdeContext"),hv=t.join(S.homedir(),".commandcode","ide"),fv=f.object({socketPath:f.string().min(1),workspaceFolders:f.array(f.string()),pid:f.number().int().positive().finite(),ideName:f.string().min(1),timestamp:f.number()}),yv=__name(e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)},"errMsg"),wv=__name(e=>{const n=t.resolve(e);let r=n;try{r=$.realpathSync(n)}catch{}return"win32"===process.platform?r.toLowerCase():r},"normalizePathForComparison"),Sv=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),Ev=__name(e=>{if("win32"===process.platform)return null;try{const t=Ce("ps",["-o","ppid=","-p",String(e)],{encoding:"utf-8",timeout:1e3}),n=parseInt(t.trim(),10);return Number.isNaN(n)||n<=1?null:n}catch{return null}},"getParentPid"),bv=__name((e,t,n=Ev)=>{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"),Cv=__name(()=>{if("vscode"!==process.env.TERM_PROGRAM)return null;if(process.env.CURSOR_TRACE_ID)return"cursor";if(process.env.WINDSURF_SESSION_ID)return"windsurf";const e=(process.env.__CFBundleIdentifier??"").toLowerCase();if(e){if(e.includes("todesktop")||e.includes("cursor"))return"cursor";if(e.includes("windsurf"))return"windsurf";if(e.includes("vscode"))return"code"}const t=[process.env.VSCODE_GIT_ASKPASS_NODE,process.env.VSCODE_GIT_ASKPASS_MAIN,process.env.GIT_ASKPASS];for(const e of t){if(!e)continue;const t=e.toLowerCase();if(t.includes("cursor"))return"cursor";if(t.includes("windsurf"))return"windsurf"}return"code"},"detectIDE"),vv=__name((e,n)=>{try{$.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{$.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),kv=__name((e,n={})=>{const{sessionDir:r=hv,parentPidFn:o=Ev,startPid:s=process.ppid}=n;try{if(!$.existsSync(r))return null;const n=`${e}-`,i=$.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),a=[];for(const e of i)try{const n=t.join(r,e),o=JSON.parse($.readFileSync(n,"utf-8")),s=fv.safeParse(o);if(!s.success)continue;const i=s.data;if(t.dirname(i.socketPath)!==r)continue;if(!Sv(i.pid)){vv(n,r);continue}a.push({session:i,file:e})}catch{continue}if(0===a.length)return null;const l=bv(a,s,o);if(l)return dlog(`[VSCode:IPC] Discovered session via PID ancestry: ${t.basename(l.session.socketPath)} (${l.session.ideName})`),l.session.socketPath;const u=wv(process.cwd());let d=null,m=0;for(const{session:e}of a)for(const n of e.workspaceFolders){const r=wv(n);(u===r||u.startsWith(r+t.sep))&&r.length>m&&(d=e,m=r.length)}return d&&dlog(`[VSCode:IPC] Discovered session via workspace match: ${t.basename(d.socketPath)} (${d.ideName})`),d?.socketPath??null}catch{return null}},"discoverSocketPath"),Tv=__name(()=>{const e=Cv();return e?kv(e):null},"resolveSocketPath"),_v=__name(()=>({type:"request",id:M(),payload:{action:"getContext"}}),"createContextRequest"),xv=__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"),Av=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!xv(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"),Pv=!1,Iv=__name(()=>{Pv||(dlog("[VSCode:IPC] No socket path resolved"),Pv=!0)},"logNoSocketPathOnce"),Nv=__name(()=>{Pv=!1},"resetNoSocketPathLogDedup"),Rv=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??Tv()}get isConnected(){return this.connected}async connect(e=2e3){if(!this.socketPath)return Iv(),!1;const n=this.socketPath;dlog(`[VSCode:IPC] Connecting: ${t.basename(n)} (timeout ${e}ms)`);try{return await new Promise(t=>{try{const r=Le.connect(n);this.socket=r;const o=__name(()=>{r.off("error",s)},"cleanup"),s=__name(e=>{clearTimeout(i),o(),this.connected=!1,dlog(`[VSCode:IPC] Connection error: ${e.message}`),t(!1)},"handleError"),i=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),o(),r.destroy(),t(!1)},e);r.on("connect",()=>{try{if(clearTimeout(i),o(),this.socket!==r)return r.destroy(),void t(!1);this.connected=!0,Nv(),dlog("[VSCode:IPC] Connected successfully"),r.on("close",()=>{this.connected=!1}),r.on("error",()=>{this.connected=!1}),t(!0)}catch(e){dlog(`[VSCode:IPC] Error in connect handler: ${yv(e)}`),r.destroy(),t(!1)}}),r.on("error",s)}catch(e){dlog(`[VSCode:IPC] Connection exception: ${yv(e)}`),t(!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=_v(),r=await new Promise(r=>{const o=__name(()=>{t.off("data",a),t.off("error",l)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),o(),r(null)},e);let i="";const a=__name(e=>{try{i+=e.toString();const t=i.indexOf("\n");if(-1===t)return;clearTimeout(s),o();const a=i.slice(0,t),l=Av(Buffer.from(a),n.id);l||dlog("[VSCode:IPC] Invalid response received"),r(l)}catch(e){clearTimeout(s),o(),dlog(`[VSCode:IPC] Error processing response: ${yv(e)}`),r(null)}},"handleData"),l=__name(e=>{clearTimeout(s),o(),dlog(`[VSCode:IPC] Socket error during request: ${e.message}`),r(null)},"handleError");t.on("data",a),t.on("error",l);try{t.write(JSON.stringify(n)+"\n")}catch(e){clearTimeout(s),o(),dlog(`[VSCode:IPC] Failed to send request: ${yv(e)}`),r(null)}});if(!r)return null;try{return await gv(r)}catch(e){return dlog(`[VSCode:IPC] Filter error, dropping context: ${yv(e)}`),null}}catch{return null}}async getDiagnostics(e={}){const{filePaths:t,timeout:n=5e3}=e,r=this.socket;if(!r||!this.connected)return dlog("[VSCode:IPC] Cannot get diagnostics - not connected"),null;const o={type:"request",id:M(),payload:{action:"getDiagnostics",filePaths:t}};return new Promise(e=>{const t=__name(()=>{r.off("data",a),r.off("error",l)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Diagnostics request timeout"),t(),e(null)},n);let i="";const a=__name(n=>{for(i+=n.toString();;){const n=i.indexOf("\n");if(-1===n)return;const r=i.slice(0,n);if(i=i.slice(n+1),r.trim())try{const n=JSON.parse(r);if(n.id!==o.id){dlog("[VSCode:IPC] Ignoring diagnostics response for different request id");continue}return clearTimeout(s),t(),void("response"===n.type&&n.payload?.diagnostics?e(n.payload.diagnostics):"error"===n.type?(dlog(`[VSCode:IPC] Diagnostics error response: ${n.payload?.message??"(no message)"} [code: ${n.payload?.code??"n/a"}]`),e(null)):(dlog("[VSCode:IPC] Invalid diagnostics response"),e(null)))}catch(e){dlog(`[VSCode:IPC] Failed to parse diagnostics response line: ${yv(e)}`)}}},"handleData"),l=__name(n=>{clearTimeout(s),t(),dlog(`[VSCode:IPC] Socket error during diagnostics request: ${n.message}`),e(null)},"handleError");r.on("data",a),r.on("error",l);try{r.write(JSON.stringify(o)+"\n")}catch(n){clearTimeout(s),t(),dlog(`[VSCode:IPC] Failed to send diagnostics request: ${yv(n)}`),e(null)}})}disconnect(){if(this.socket){dlog("[VSCode:IPC] Disconnecting");try{this.socket.end()}catch{}this.socket=null,this.connected=!1}}static async isAvailable(e=1e3){try{const t=new _VSCodeIPCClient;if(!t.socketPath)return dlog("[VSCode:IPC] Availability check: unavailable (no socket path)"),!1;const n=await t.connect(e);return t.disconnect(),dlog("[VSCode:IPC] Availability check: "+(n?"available":"unavailable")),n}catch{return!1}}};Ot();var Mv=__name(async(e,t)=>{if(!t)return e.filter(e=>!cv(e.file));const n=await pv(e.map(e=>e.file),t);return e.filter(e=>n.has(e.file))},"filterDiagnostics");async function fetchDiagnostics(e){if(!Cv())throw new Error("Not running inside an IDE terminal. The diagnostics tool requires the Command Code VS Code extension.");const n=e?.map(e=>t.resolve(e)),r=new Rv;try{if(!await r.connect())throw new Error("Could not connect to IDE extension. Make sure the Command Code extension is installed and active.");const e=await r.getDiagnostics({filePaths:n,timeout:5e3});if(null===e)throw new Error("Failed to get diagnostics from IDE.");const t=await lv(process.cwd())??process.cwd(),o=await Mv(e,t);return dlog("[diagnostics] Fetched diagnostics",{fileCount:o.length,droppedCount:e.length-o.length,total:o.reduce((e,t)=>e+t.diagnostics.length,0)}),o}finally{r.disconnect()}}Kn(),__name(fetchDiagnostics,"fetchDiagnostics"),Ot();var Lv=__name(e=>String(e??"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\r\n]+/g," ").replace(/```/g,"` ` `"),"sanitize");function formatDiagnostics(e){if(0===e.length)return"No diagnostics found. All files are clean.";const t=[];let n=0,r=0,o=0,s=0;for(const i of e){t.push(`${Lv(i.relativePath)}:`);for(const e of i.diagnostics){const i=`L${e.range.startLine}:${e.range.startCol}`,a=e.code?` ${Lv(e.code)}`:"",l=e.source?` [${Lv(e.source)}]`:"";switch(t.push(` ${i} ${e.severity}${a}: ${Lv(e.message)}${l}`),e.severity){case"error":n++;break;case"warning":r++;break;case"information":o++;break;case"hint":s++}}t.push("")}const i=[];n>0&&i.push(`${n} error${1!==n?"s":""}`),r>0&&i.push(`${r} warning${1!==r?"s":""}`),o>0&&i.push(`${o} info`),s>0&&i.push(`${s} hint${1!==s?"s":""}`);const a=`${e.length} file${1!==e.length?"s":""}`;return t.push(`Summary: ${i.join(", ")} across ${a}`),t.join("\n")}__name(formatDiagnostics,"formatDiagnostics");var $v={name:"diagnostics",description:"Get LSP diagnostics (errors, warnings, hints) from the IDE. Returns type errors, lint warnings, and other language server diagnostics reported by all active language servers (TypeScript, ESLint, Python, etc.). Only available when connected to an IDE with the Command Code extension. Pass specific file paths when you know which files are relevant. Only omit filePaths to scan the entire workspace when the user explicitly asks for all workspace diagnostics.",input_schema:{type:"object",properties:{filePaths:{type:"array",items:{type:"string"},description:'Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.'}},required:[]},execute:__name(async e=>{const t=parseRepairedToolInput({toolName:"diagnostics",schema:ov,input:e});return t.ok?formatDiagnostics(await fetchDiagnostics(t.data.filePaths)):t.message},"execute")};Ot(),Ot(),Ot(),wn();var Dv="Coding agent that continuously learns your taste of writing code.",Ov=34,Fv="Connect IDE to share your open file and selected lines",qv=[{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"},{key:"Alt+P",description:"Quick model switch (Option+P on macOS)"},{key:"Ctrl+G",description:"Open input in external editor ($EDITOR)"},{key:"Press Esc twice",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],jv=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume [name]",description:"Resume a conversation by name (use quotes for multi-word names), or pick from history"},{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:"--auto-accept",description:"Start in auto-accept mode"},{key:"--yolo",description:"Bypass all permission prompts (alias for --dangerously-skip-permissions)"},{key:"--add-dir <directory>",description:"Add directory to workspace context"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"--ide-setup",description:Fv},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],Uv=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rename [name]",description:"Rename the current session"},{key:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/mcp",description:"Manage MCP server connections"},{key:"/model",description:"Switch between Command Code models"},{key:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{key:"/compact",description:"Compact the conversation history"},{key:"/compact-mode",description:"Select a compact mode to compact sessions"},{key:"/context",description:"Show context window usage and breakdown"},{key:"/ide",description:Fv},{key:"/login",description:"Log in to Command Code"},{key:"/logout",description:"Log out of Command Code"},{key:"/courses",description:"Open Command Code courses in your browser"},{key:"/feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"/review [pr]",description:"Review a pull request (optional PR number)"},{key:"/pr-comments",description:"Fetch all PR comments for current branch"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/status",description:"Show comprehensive environment status"},{key:"/usage",description:"Display credits, plan, and usage metrics"},{key:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],Bv=[{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 taste learn <source>",description:"Learn taste from a local repository or GitHub repo"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd skills",description:"Manage skills from GitHub repositories"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Log out of Command Code"}],zv=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Hv=[{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 --resume "auth refactor"',description:"Resume a named session"},{key:'cmd -p "your query"',description:"Run non-interactive query"},{key:"cmd taste learn .",description:"Learn taste from the current repository"},{key:"cmd taste learn owner/repo",description:"Learn taste from a GitHub repository"},{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"}],Wv='Start with a prompt: cmd "fix the login bug"';function formatHelpItems(e){return e.map(e=>`- ${e.key}: ${e.description}`).join("\n")}function getSelfKnowledge(){return`# Command Code — Product Knowledge\n\n## KEYBOARD SHORTCUTS\n${formatHelpItems(qv)}\n\n## SLASH COMMANDS (type these in the chat input)\n${formatHelpItems(Uv)}\n\n## CLI SUBCOMMANDS\n${formatHelpItems(Bv)}\n\n## CLI EXAMPLES\n${formatHelpItems(Hv)}\n\n## CLI OPTIONS (flags when launching cmd)\n${formatHelpItems(jv)}\n\n## TASTE SYSTEM\nTaste is powered by the meta neuro-symbolic AI model taste-1 with continuous reinforcement learning (RL). It combines reasoning with neural intuition to learn your coding preferences.\n\nHow taste works:\n- Learns from you — every accept, reject, and edit becomes a signal\n- Thinks like you — learns patterns and micro-decisions you'd never document\n- Grows with you — continuous learning loop that never goes stale\n\nEnable taste: Use /taste in a session or run npx taste from the command line.\n\nTaste packages (three types):\n- Project: Stored in .commandcode/taste/ — learnings unique to this codebase\n- Global: Stored in ~/.commandcode/taste/ — personal taste across all projects (use -g flag)\n- Remote: Stored at commandcode.ai/username/taste — team sharing, backup, sync across machines\n\nFile structure:\n .commandcode/taste/\n ├── taste.md (main taste file)\n ├── cli/taste.md\n ├── typescript/taste.md\n └── architecture/taste.md\n\nKey commands:\n- npx taste push --all — push entire project taste to remote\n- npx taste pull username/project-name — pull taste from remote\n- npx taste push cli -g — push package to global\n- npx taste pull cli -g — pull package from global\n- npx taste list — list available packages\n- npx taste lint — validate package format\n- npx taste open — open packages in editor\n\nPrivacy: Taste processing runs on your codebase and stores learning data locally only.\n\n## KEY FEATURES\n- Taste System: Automatically learns coding preferences from interactions and applies them consistently\n- Skills: User-defined knowledge modules for specialized tasks (stored in .commandcode/skills/ or .agents/skills/)\n- Agents: Custom agent configurations for different workflows (stored in .commandcode/agents/)\n- Memory: Project-specific instructions via COMMANDCODE.md files\n- MCP: Model Context Protocol server connections for extended tool capabilities\n- Plan Mode: Structured exploration and planning before implementation [Shift+Tab to toggle]\n- Conversation Management: Resume, continue, share, and rewind conversations\n- PR Review: Built-in pull request review capabilities (/review command)\n- Learning Feed: View what taste is learning in real-time [Ctrl+T to toggle]\n- Model Switching: Switch between models with Alt+P (Option+P on macOS)\n\n## FREQUENTLY ASKED QUESTIONS\nQ: What is Command Code?\nA: Command Code is the first coding agent that automatically learns your taste of writing great code.\n\nQ: What is taste-1?\nA: taste-1 is our meta neuro-symbolic AI model with continuous reinforcement learning (RL).\n\nQ: Is Command Code free?\nA: Command Code offers both free and premium plans. Check https://commandcode.ai/pricing for details.\n\nQ: How do I install Command Code?\nA: Run npm i -g command-code, then cmd login, then cmd to start.\n\nQ: What are Agent Skills?\nA: Reusable instructions that teach Command Code how to handle specific tasks like code reviews, testing, or commit messages. Use /skills to browse them.\n\nQ: What are MCP servers?\nA: MCP (Model Context Protocol) servers let Command Code connect to external tools and data sources like GitHub, Notion, databases, and more. Use /mcp to manage them.\n\nQ: What is plan mode?\nA: Plan mode lets you review and approve Command Code's approach before it writes any code. Press Shift+Tab to toggle it.\n\nQ: What is headless mode?\nA: Headless mode lets you run Command Code non-interactively in scripts, CI/CD pipelines, and automation workflows. Use cmd -p "query" to run.\n\nQ: How do I fix "command not found" after installing?\nA: Ensure your global npm bin directory is in your PATH. Run npm config get prefix to find it, then add <prefix>/bin to your PATH.\n\nQ: Why am I getting unauthorized errors?\nA: Run cmd logout followed by cmd login to refresh your session. If the issue persists, check your account at https://commandcode.ai/studio.\n\nQ: How do I check my usage limits?\nA: Visit the billing page in Command Code Studio at https://commandcode.ai/studio.\n\nQ: My MCP server won't connect. What should I do?\nA: Check the server config with cmd mcp get <name> and use /mcp inside a session to see the error. For stdio servers, ensure the command is installed and in your PATH.\n\nQ: Where can I get help?\nA: Join our Discord at https://commandcode.ai/discord, report issues on GitHub, or email support@commandcode.ai.\n\n## TROUBLESHOOTING\n\n### Installation\n- "command not found" after install: Ensure global npm bin directory is in PATH. Run npm config get prefix, add <prefix>/bin to PATH, restart terminal.\n\n### Authentication\n- Login fails or session expired: Run cmd logout then cmd login. If still failing, delete ~/.commandcode/auth.json and retry.\n- API key or provider issues: Verify provider config, check API key validity, check usage limits.\n- Chrome Local Network Access prompt during login: Click "Allow" — this is expected and safe. Command Code runs a temporary local server for OAuth callback.\n\n### MCP Servers\n- Server won't connect: Check config with cmd mcp get <name>, verify command is in PATH, use /mcp in session for error details.\n- Authentication issues: Re-authenticate with cmd mcp auth <server>, or clear and retry with cmd mcp auth --clear <server>.\n\n### Skills\n- Not appearing in /skills menu: Check directory structure (.commandcode/skills/ or .agents/skills/), verify SKILL.md exists with valid frontmatter.\n- Editor not opening: Check $EDITOR is set and the editor is in PATH.\n- Skill not being used: Make description more specific with keywords, ask Command Code explicitly to use the skill.\n\n### Performance\n- Slow responses: Check internet connection, disconnect unneeded MCP servers, keep prompts focused and specific.\n- High token usage: Review usage in Studio, use headless mode for scripted tasks, use plan mode to agree on approach first.\n\n### Support\n- Discord: https://commandcode.ai/discord\n- GitHub: https://github.com/commandcode/command-code\n- Email: support@commandcode.ai\n\n## PRICING & LIMITS\nHow it works:\n- Monthly reset: Request limits reset at the start of each billing cycle.\n- Auto top-up: Buy extra credits at model cost. Credits roll over and never expire.\n- No AI training: Command Code does not train on your code or store your code snippets.\n\nManage your plan:\n- Purchase credits or subscribe: Studio > Billing at https://commandcode.ai/settings/billing\n- Track usage: https://commandcode.ai/usage\n- Manage payment methods: Access billing portal from Studio > Billing\n\nPremium requests: Any request that uses a premium model (like taste-1) during your coding session.\nWhen you hit your limit: Continue with auto top-up enabled. Extra credits are purchased at model cost and roll over.\nSwitch plans: Upgrade or downgrade anytime from Studio > Billing. Changes take effect next billing cycle.\nTeam billing: Billed per seat. Credits are pooled at the team level.\n\nEnterprise: Enhanced security, compliance, and control. Contact support@commandcode.ai for Enterprise edition.\n\n## PRIVACY & LEGAL\n- Command Code does not train on your code or store your code snippets.\n- Taste processing runs on your codebase and stores learning data in your project and on your local machine only.\n- Privacy Policy: https://commandcode.ai/privacy\n- Terms of Service: https://commandcode.ai/terms\n\n## HELPFUL LINKS\n${formatHelpItems(zv)}`}__name(formatHelpItems,"formatHelpItems"),__name(getSelfKnowledge,"getSelfKnowledge");var Gv={name:"get_self_knowledge",description:"Retrieve Command Code product documentation — features, shortcuts, commands, options, taste, FAQs, troubleshooting, pricing, or privacy. Call this whenever the user asks about Command Code capabilities or needs help. Authoritative source — do NOT search the codebase. Call once per conversation. After the first call, the information is already in your context — do not call again.",input_schema:{type:"object",properties:{},required:[]},execute:__name(async()=>getSelfKnowledge(),"execute")};yS(),BS(),US(),Ot(),Ot(),Ot(),wn(),Ot(),Ot();var Vv=["explore","plan","review","general"],Qv=[{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\n5. Stay inside the current workspace. Do not read sibling projects, parent directories, or unrelated paths to draw inspiration — even if structurally similar code exists nearby. The user\'s project is its own context.\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&&Vv.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(S.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=Ke(s),l=i.name||r.replace(".md","");if(isReservedAgentName(l))return null;let u=i.tools||"";return"*"!==u&&'"*"'!==u||(u="*"),{name:l,description:i.description||"",tools:u,systemPrompt:a.trim(),location:n,filePath: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"),Ot(),wn(),ao(),sS(),fS(),Lo(),Rs(),Ot(),Ot();var Kv={"\n":"\\n","\r":"\\r","\t":"\\t"},Yv=['"}','"}}',"}",'": ""}'];function isPlainObject(e){return"object"==typeof e&&null!==e}function escapeControlCharsInJsonStrings(e){const t=[];let n=!1,r=0;for(;r<e.length;){const o=e[r];if(!n){'"'===o&&(n=!0),t.push(o),r++;continue}if("\\"===o){t.push(o,e[r+1]??""),r+=2;continue}if('"'===o){n=!1,t.push(o),r++;continue}const s=o.charCodeAt(0);s>=32?(t.push(o),r++):(t.push(Kv[o]??`\\u${s.toString(16).padStart(4,"0")}`),r++)}return t.join("")}function repairTruncatedJson(e){if(!e.startsWith("{"))return null;for(const t of Yv)try{const n=JSON.parse(e+t);if(isPlainObject(n))return n}catch{}return null}function tryParseDirectly(e){try{const t=JSON.parse(e);if(isPlainObject(t))return t;if("string"==typeof t)return parseToolArgs(t)}catch{}return null}function tryParseAfterEscaping(e){try{const t=JSON.parse(escapeControlCharsInJsonStrings(e));if(isPlainObject(t))return t}catch{}return null}function parseToolArgs(e){return tryParseDirectly(e)??tryParseAfterEscaping(e)??repairTruncatedJson(e)??repairTruncatedJson(escapeControlCharsInJsonStrings(e))}function normalizeToolInput(e){return"string"!=typeof e?e:parseToolArgs(e)??e}__name(isPlainObject,"isPlainObject"),__name(escapeControlCharsInJsonStrings,"escapeControlCharsInJsonStrings"),__name(repairTruncatedJson,"repairTruncatedJson"),__name(tryParseDirectly,"tryParseDirectly"),__name(tryParseAfterEscaping,"tryParseAfterEscaping"),__name(parseToolArgs,"parseToolArgs"),__name(normalizeToolInput,"normalizeToolInput"),Ot(),Kn();var Jv=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${Pe.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${Pe.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${Pe.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${Pe.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}},Xv=new Jv("SSEStreamConsumer");function formatToolResultOutput(e){if(e.output&&"object"==typeof e.output)return e.output;const t=e.result??e.output??"",n="string"==typeof t?t:JSON.stringify(t);return!0===e.isError?{type:"error-text",value:n}:{type:"text",value:n}}async function consumeSSEStream(e,t){const n=e.getReader(),r=new TextDecoder,o=[];let s=null,i="",a=0,l=0,u=0,d=0,m=null,g="";try{for(;;){const{done:e,value:h}=await n.read();if(e)break;g+=r.decode(h,{stream:!0});const f=g.split("\n");g=f.pop()||"";for(const e of f){const n=e.trim();if(!n)continue;let r;try{r=JSON.parse(n)}catch{continue}if("text-delta"!==r.type)if("reasoning-delta"!==r.type)if("reasoning-end"!==r.type)if("tool-call"!==r.type)if("tool-result"!==r.type){if("finish"===r.type){const e=r.totalUsage;e&&(a=e.inputTokens||0,l=e.outputTokens||0,u=e.inputTokenDetails?.cacheReadTokens||0,d=e.inputTokenDetails?.cacheWriteTokens||0),m="tool-calls"===r.finishReason?"tool_calls":"end_turn";continue}if("error"===r.type){const e=r.error,t=e?.message||r.error||"Stream error",n=new Error("string"==typeof t?t:String(t));throw null!=e?.statusCode&&(n.statusCode=e.statusCode),null!=e?.isRetryable&&(n.isRetryable=e.isRetryable),n}}else s=null,o.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:formatToolResultOutput(r),providerExecuted:!0===r.providerExecuted||void 0});else s=null,Xv.debug(`[SSE] tool-call: name=${r.toolName}, id=${r.toolCallId}`),o.push({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:normalizeToolInput(r.input??r.args??{}),providerExecuted:!0===r.providerExecuted||void 0});else i&&(o.push({type:"reasoning",text:i}),i="");else i+=r.text??"";else s||(s={type:"text",text:""},o.push(s)),s.text+=r.text,t?.onText?.(r.text)}}}finally{n.releaseLock()}i&&o.push({type:"reasoning",text:i});const h=o.filter(e=>"tool-call"===e.type).length;return h>0&&Xv.debug(`[SSE] Stream complete: ${o.length} blocks, ${h} tool calls, stop_reason=${m}`),{content:o,usage:{input_tokens:a,output_tokens:l,cache_read_input_tokens:u||void 0,cache_creation_input_tokens:d||void 0},stop_reason:m}}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),i=await readFileContent({absolutePath:t});if("binary"===i.contentType)continue;const a=String(i.content),l=e.relative(process.cwd(),t),u=1e5;if(a.length>u){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${l}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:a});const d=`{${l}: ${a}}`;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(formatToolResultOutput,"formatToolResultOutput"),__name(consumeSSEStream,"consumeSSEStream"),Ot(),wn(),Kn(),sS(),fS(),Ot(),_E(),Ot(),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),wn(),hs(),Kn(),Ot(),Ot(),Ot(),Ot();var Zv="command-message",ek="command-name",tk="command-args";function extractCommandTag({text:e,tagName:t}){const n=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),r=e.match(n);return r?r[1]?.trim()??null:null}function parseCommandTags({text:e}){return{commandMessage:extractCommandTag({text:e,tagName:Zv}),commandName:extractCommandTag({text:e,tagName:ek}),commandArgs:extractCommandTag({text:e,tagName:tk})}}function renderCommandTagMessage({text:e}){const t=parseCommandTags({text:e}),{commandMessage:n,commandName:r,commandArgs:o}=t;if(!n&&!r)return null;if(n){const e=`/${n}`;return o?`${e} ${o}`:e}if(!r)return null;const s=r.startsWith("/")?r:`/${r}`;return o?`${s} ${o}`:s}__name(extractCommandTag,"extractCommandTag"),__name(parseCommandTags,"parseCommandTags"),__name(renderCommandTagMessage,"renderCommandTagMessage"),Ot();var nk=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext");function isHiddenTranscriptMessage({message:e}){return!0===e.meta.isMeta}function extractTextFromMessageContent({content:e}){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e)"text"===n.type&&"string"==typeof n.text&&(t+=n.text);return t}function renderVisibleUserMessageText({content:e}){const t=nk(extractTextFromMessageContent({content:e})).trim();return renderCommandTagMessage({text:t})||t}__name(isHiddenTranscriptMessage,"isHiddenTranscriptMessage"),__name(extractTextFromMessageContent,"extractTextFromMessageContent"),__name(renderVisibleUserMessageText,"renderVisibleUserMessageText"),Gf();var rk=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(S.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Fe(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=Se("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await k.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:cs.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await k.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,version:2,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await k.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 k.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let o=0;const s=[];for(const t of e)try{s.push(JSON.parse(t))}catch(e){o++,console.error("Error parsing session line:",e)}if(s.some(e=>isLegacyFormat(e))){const e=legacyAnthropicToSession(s.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))),o=s.filter(e=>"user"===e.role||"assistant"===e.role);let i=0;for(const n of e){const e=o[Math.min(i,o.length-1)];"tool"!==n.role&&"user"!==n.role||i++,t.push({message:n,meta:{timestamp:e?.timestamp??(new Date).toISOString(),source:"cli",...e?.metadata||{}}})}dlog(`[Session] Migrating v1 session to v2: ${r} (${t.length} messages)`);const a=t.map(e=>JSON.stringify({id:crypto.randomUUID(),timestamp:e.meta.timestamp,sessionId:n,parentId:null,role:e.message.role,content:e.message.content,gitBranch:this.gitBranch,metadata:{...e.meta,version:2}}));await k.writeFile(r,a.join("\n")+"\n").catch(()=>{})}else for(const e of s)"user"!==e.role&&"assistant"!==e.role&&"tool"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}});return{messages:t,corruptedLines:o,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){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message,r=Date.now(),o=crypto.randomUUID();if("tool"!==e.role)if("user"===e.role){const n=renderVisibleUserMessageText({content:e.content});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-call"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=bE(r.toolName,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.toolName,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 k.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 k.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await k.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 k.access(n)}catch{return[]}const e=(await k.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 k.stat(s),o=(await k.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(o.length>0){let s="",i="";const a=JSON.parse(o[0]);a.gitBranch&&(i=a.gitBranch);let l=0;for(const e of o){const t=JSON.parse(e);!0!==t.metadata?.isMeta&&(l++,s||"user"!==t.role||(s=renderVisibleUserMessageText({content:t.content}),!s&&"object"==typeof t.content&&null!==t.content&&"input"in t.content&&"string"==typeof t.content.input&&(s=t.content.input)))}s=nk(s);const u=await _SessionManager.loadSessionMetaForId(e,n),d=u?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",title:d||void 0,messageCount:l,projectPath:n,gitBranch:i||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const n=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await k.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 k.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 k.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await k.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};return await k.writeFile(this.getMetaFilePath(),JSON.stringify(t,null,2)),!0}catch(e){return dlog("Session",`Failed to save session meta: ${e}`),!1}}async saveSessionTitle(e){return await this.saveSessionMeta({title:e})}async loadSessionTitle(){const e=await this.loadSessionMeta();return e?.title||null}async loadUserRenamedTitle(){const e=await this.loadSessionMeta();return e?.userRenamed&&e.title?e.title:null}static async loadProjectMetaFiles(){const e=_SessionManager.getCurrentProjectDirName(),n=t.join(_SessionManager.getProjectsBasePath(),e);try{await k.access(n)}catch{return[]}const r=(await k.readdir(n)).filter(e=>e.endsWith(".meta.json"));return Promise.all(r.map(async e=>{const t=e.slice(0,-10);return{sessionId:t,meta:await _SessionManager.loadSessionMetaForId(t,n)}}))}static async isSessionNameTaken({name:e,excludeSessionId:t}){const n=e.trim().toLowerCase();return!!n&&(await _SessionManager.loadProjectMetaFiles()).some(({sessionId:e,meta:r})=>(!t||e!==t)&&r?.title?.trim().toLowerCase()===n)}static async findSessionByName(e){const t=e.trim().toLowerCase();if(!t)return null;const n=(await _SessionManager.loadProjectMetaFiles()).find(({meta:e})=>e?.title?.trim().toLowerCase()===t);return n?{id:n.sessionId}:null}static async loadSessionMetaForId(e,n){const r=t.join(n,`${e}.meta.json`);try{const e=await k.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 k.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 k.writeFile(r,s)}else await k.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 k.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 k.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 k.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=nk(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}};Lo(),Jr(),ao();var ok=new Map,sk=sn.MINIMAX_M2_5.id;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)}`}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=ok.get(n);if(r)return ok.delete(n),ok.set(n,r),dlog("[ToolDescription] cache hit",{toolName:e,description:r}),r;const o=Date.now();try{const r=createPrompt(t),o=await getConfiguredProvider(),s=await isOAuthEnforced(),i={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:s.toString()},{token:a,oauthProvider:l}=await getOAuthCredentials({provider:o});a&&(i[Ut.OAUTH_TOKEN]=`Bearer ${a}`,l&&(i[Ut.OAUTH_PROVIDER]=l));const u={config:getEnvironmentContext(),memory:"",taste:"",skills:"",mode:"tool-desc",params:{tools:[],messages:[{role:"user",content:r}],model:sk,system:'Precisely describe what a shell 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\nOutput the description only — no preamble, no explanation, no quotes.',max_tokens:500,temperature:1,stream:!0},threadId:crypto.randomUUID()},d=getApiBaseUrl(),m=new jw({baseUrl:d}).post({endpoint:Bt.ALPHA.GENERATE,body:u,headers:i,stream:!0}).then(e=>consumeSSEStream(e)),g=await Promise.race([m,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),1e4))]);if(!g)return dlog("[ToolDescription] empty",{toolName:e,model:sk}),null;const h=g.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("").trim(),f=cleanDescription(h);if(f){if(ok.size>=100){const e=ok.keys().next().value;void 0!==e&&ok.delete(e)}ok.set(n,f),dlog("[ToolDescription] done",{toolName:e,model:sk,description:f,tokensIn:g.usage.input_tokens,tokensOut:g.usage.output_tokens,cached:g.usage.cache_read_input_tokens??0})}else dlog("[ToolDescription] rejected",{toolName:e,raw:h});return f}catch(t){return dlog("[ToolDescription] error",{toolName:e,durationMs:Date.now()-o,error:t instanceof Error?t.message:String(t)}),null}}function sanitize2(e){return String(e).replace(/[\r\n\t\f\v]+/g," ").replace(/\s+/g," ").trim().slice(0,4e3)}function createPrompt(e){return`Command: ${`${sanitize2(e.command||"")} ${sanitize2(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}__name(stableStringify,"stableStringify"),__name(generateCacheKey,"generateCacheKey"),__name(generateToolDescription,"generateToolDescription"),__name(sanitize2,"sanitize"),__name(createPrompt,"createPrompt"),__name(cleanDescription,"cleanDescription"),yS(),Ot(),xo(),BS();var ik,ak=["edit_file","delete_file","shell_command","todo_write","kill_shell"],lk=["exit_plan_mode"],ck=["enter_plan_mode"];function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n||"bypass"===n?t.filter(e=>!lk.includes(e.name)):"plan"===n?t.filter(e=>!ak.includes(e.name)&&!ck.includes(e.name)):t.filter(e=>!lk.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||"bypass"===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 ak.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.`}}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})})}function setBenchmarkOutput(e){ik=e}function createBenchmarkCollector(){return ik?{startTime:Date.now(),turnDetails:[],agents:[],maxTurnsReached:!1}:null}__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode"),Ot(),__name(sleep,"sleep"),_E(),Jr(),yS(),Ot(),__name(setBenchmarkOutput,"setBenchmarkOutput"),__name(createBenchmarkCollector,"createBenchmarkCollector");var uk="\x3c!-- BENCHMARK_AGENT_METRICS:",dk=" --\x3e";function buildAgentMetricsMarker(e){return`\n${uk}${JSON.stringify(e)}${dk}`}function extractAgentMetrics(e){const t=e.indexOf(uk);if(-1===t)return{cleanContent:e,metrics:null};const n=t+29,r=e.indexOf(dk,n);if(-1===r)return{cleanContent:e,metrics:null};try{const o=e.substring(n,r),s=JSON.parse(o);return{cleanContent:e.substring(0,t).trimEnd()+e.substring(r+4),metrics:s}}catch{return{cleanContent:e,metrics:null}}}function createAgentBenchmarkTracker(){return ik?{turns:0,toolCalls:{},toolErrors:0}:null}function trackAgentTurn(e){e&&e.turns++}function trackAgentToolCall(e){const{tracker:t,toolName:n,isError:r}=e;t&&(t.toolCalls[n]=(t.toolCalls[n]??0)+1,r&&t.toolErrors++)}function buildAgentResult(e){const{result:t,tracker:n,agentName:r,startTime:o,tokens:s}=e;return n?t+buildAgentMetricsMarker({name:r,turns:n.turns,toolCalls:n.toolCalls,toolErrors:n.toolErrors,tokens:s,durationMs:Date.now()-o}):t}function writeBenchmarkMetrics(e){if(!ik)return;const t=Date.now()-e.startTime,n=e.turnDetails.length,r={};let o=0,s=0,i=0,a=0;for(const t of e.turnDetails){for(const e of t.toolCalls)o++,r[e.name]=(r[e.name]??0)+1,e.isError&&s++;i+=t.inputTokens,a+=t.outputTokens}const l={wallTimeMs:t,turns:n,turnDetails:e.turnDetails,toolCalls:{total:o,byType:r,errors:s},tokens:{input:i,output:a},maxTurnsReached:e.maxTurnsReached,agents:e.agents};try{L.writeFileSync(ik,JSON.stringify(l,null,2))}catch{}}__name(buildAgentMetricsMarker,"buildAgentMetricsMarker"),__name(extractAgentMetrics,"extractAgentMetrics"),__name(createAgentBenchmarkTracker,"createAgentBenchmarkTracker"),__name(trackAgentTurn,"trackAgentTurn"),__name(trackAgentToolCall,"trackAgentToolCall"),__name(buildAgentResult,"buildAgentResult"),__name(writeBenchmarkMetrics,"writeBenchmarkMetrics");var mk=new Jv("AgentExecutor");function agentToTool(t,n){const{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:i}=n;return{name:t.name,description:t.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object",properties:{content:{type:"string",description:"The text content of the message"}},required:["content"]}}},required:["messages"]},execute:__name(async(n,a)=>{let l=null;const u=Date.now();let d=null;try{const m=a?.permissionMode||"standard",g=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:i}),clientTools:r,serverTools:o,mode:m});let h=Date.now();const f=10,y=[];if(a?.onFeedUpdate){const e=bE(t.name,n);l=mE({name:t.name,input:e}),a.onFeedUpdate(l)}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3);const w=createAgentBenchmarkTracker(),S=await getConfiguredProvider(),E=await isOAuthEnforced(),{token:C,oauthProvider:v}=await getOAuthCredentials({provider:S});validateOAuthToken({token:C,provider:S});const k=getApiBaseUrl(),T=new jw({baseUrl:k});let _=0;const x=[];let A=n?.messages;if("string"==typeof A)try{A=JSON.parse(A)}catch(e){A=[]}if(Array.isArray(A)&&A.length>0)for(const e of A)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&x.push({role:"user",content:t})}const P={stream:!0,messages:x,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:g,model:getConfiguredModel()},I=await isTasteLearningEnabled(),N={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.TASTE_LEARNING]:I.toString(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:E.toString(),...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};C&&(N[Ut.OAUTH_TOKEN]=`Bearer ${C}`,v&&(N[Ut.OAUTH_PROVIDER]=v));const R=getEnvironmentContext(),M=await getMemoryContent([]),L=crypto.randomUUID();let $="",D=!0;const O=__name(()=>{mk.debug("[Agent] Abort signal triggered, stopping immediately"),D=!1,d&&(clearInterval(d),d=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",O);try{for(;D;){if(a?.abortSignal?.aborted)throw mk.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:T,body:{mode:"custom-agent",config:R,memory:M,threadId:L,params:{...P,messages:x}},headers:N,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{_+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&l&&t-h>=f){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:_,elapsedSeconds:e}},a.onFeedUpdate(l),h=t}},"onTextDelta")});if(trackAgentTurn(w),a?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(_=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool-call"===e.type&&!e.providerExecuted);if($=t.content.filter(e=>"tool-call"===e.type&&!!e.providerExecuted).length>0?processServerToolBlocks(t,a):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===n.length){const e=t.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);e.length>0&&x.push({role:"assistant",content:e}),D=!1;break}const r=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);r.length>0&&x.push({role:"assistant",content:r});const o=[],s=new Set;let i=!1;for(const t of n){if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{const r=dS.includes(t.toolName),g="auto-accept"!==m&&"bypass"!==m&&mS.includes(t.toolName)?Promise.race([generateToolDescription(t.toolName,n).catch(()=>null),new Promise(e=>setTimeout(()=>e(null),5e3))]):Promise.resolve(null);if(r&&a?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await g;if(!await a.onPermissionRequest(t.toolName,n,e)){mk.debug(`Permission denied for tool: ${t.toolName}`),i=!0;break}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let 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,mk.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,mk.debug(`Resolved input for ${t.toolName}: ${bE(t.toolName,n)}`)):mk.debug(`No path resolution needed for ${t.toolName}: ${bE(t.toolName,n)}`)}if(a?.onFeedUpdate&&l){const e=bE(t.toolName,n);y.push({name:t.toolName,input:e}),y.length>3&&y.shift();const r=Date.now(),o=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:_,elapsedSeconds:o,recentTools:[...y]}},mk.debug(`Updating agent with recentTools (${y.length} tools): ${JSON.stringify(y)}`),a.onFeedUpdate(l)}const h=await executeTool(t.toolName,n,{abortSignal:a?.abortSignal,permissionMode:m});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const f=checkToolOutputTokensLimit(h);if(o.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:{type:"text",value:f}}),s.add(t.toolCallId),trackAgentToolCall({tracker:w,toolName:t.toolName,isError:!1}),a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:_,elapsedSeconds:t,recentTools:[...y]}},a.onFeedUpdate(l)}mk.debug(`Tool executed successfully: ${t.toolName}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";o.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:{type:"error-text",value:`Error: ${n}`}}),s.add(t.toolCallId),trackAgentToolCall({tracker:w,toolName:t.toolName,isError:!0}),mk.error(`Tool execution failed: ${t.toolName} - ${n}`)}}if(i){const e=x[x.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool-call"===e.type?s.has(e.toolCallId):"text"===e.type);t.length>0?e.content=t:x.pop()}D=!1;break}x.push({role:"tool",content:o})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",O)}if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:$||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:_,elapsedSeconds:t}},a.onFeedUpdate(l)}return buildAgentResult({result:$||"DONE",tracker:w,agentName:t.name,startTime:u,tokens:_})}catch(e){if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const t=Date.now(),n=(t-u)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||a?.abortSignal?.aborted;l={...l,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:u,endTime:t,tokensUsed:l?.metadata?.tokensUsed||0,elapsedSeconds:n}},a.onFeedUpdate(l)}throw e}},"execute")}}function filterToolsForMode(e){const{tools:t,clientTools:n,serverTools:r,mode:o}=e;if("standard"===o||"auto-accept"===o||"bypass"===o)return t;const s=t.filter(e=>n.includes(e)),i=t.filter(e=>r.includes(e));return[...getToolsForMode({allTools:s,mode:o}),...i]}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let i=[];if("*"===e.tools)i=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)i.push(e);else{const e=r.find(e=>e.name===t);e&&i.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)i.push(t);else{const t=r.find(t=>t.name===e);t&&i.push(t)}}}return i}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let i=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:Bt.ALPHA.GENERATE,signal:o,headers:r});return await consumeSSEStream(e,{onText:s})}catch(t){if(i=t,mk.debug(`[callAPIWithRetry] Error on attempt ${e+1}/5: ${t.message||t}, status=${t.status}, code=${t.code}, retryable=${isRetryableError(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);mk.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw i||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof bs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof vs||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","fetch failed","ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","network error","socket hang up","UND_ERR_CONNECT_TIMEOUT"].some(t=>e.message.includes(t))||e?.status>=500&&e?.status<600)}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 bs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof vs||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=>"tool-call"===e.type&&e.providerExecuted).length)return"";let n="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("tool-call"===e.type&&e.providerExecuted&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:o}=uS({serverToolBlock:e,contentBlocks:r}),s=bE(e.toolName,e.input),i={id:`${e.toolName}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.toolName,input:s,output:o?gE(n):n};t.onFeedUpdate(i)}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 pk=new Map,gk=null;function initializeAgentManager(e){gk=e}async function loadAgentTools(){if(!gk)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");pk.clear();for(const e of Qv){const t=agentToTool(e,gk);pk.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,gk);pk.set(t.name,t)}}async function getAgentTools(){return 0===pk.size&&await loadAgentTools(),Array.from(pk.values())}async function getAgentTool(e){return 0===pk.size&&await loadAgentTools(),pk.get(e)}function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,o=e.join(r,".commandcode","taste"),s=e.normalize(e.resolve(r,n)),i=e.normalize(o);return s.startsWith(i)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),o=e.normalize(e.join(w.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 i=e.relative(s,n).split(e.sep);return 1===i.length?{isTaste:!0}:2===i.length?{isTaste:!0,category:i[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),Ot(),wn(),__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"),hs(),Ao();var hk=[vC,NC,LC,$C,jC,HC,VC,QC,KC,YC,JC,ev,tv,nv,$v,Gv],fk=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],yk=new Map(hk.map(e=>[e.name,e])),wk=new Set([...hk.map(e=>e.name),...fk.map(e=>e.name)]);function isAgentTool(e){return!wk.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";setCurrentPermissionMode(r);const 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=yk.get(e);if(s||(s=await getAgentTool(e)),!s){const t=await getAgentTools(),n=[...Array.from(yk.keys()),...t.map(e=>e.name)];throw new Error(`Tool "${e}" not found. Available tools: ${n.join(", ")}`)}if(("write_file"===e||"edit_file"===e)&&!0!==n?.allowTasteWrite){const e=t.filePath,n=isPathInTasteDirectory({filePath:e,projectRoot:process.cwd()});if(e&&n)throw new Error("Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system.".replace("Error: ",""))}const i=trackToolStart({toolName:e});try{let r;return r=(!yk.has(e)||!0===s.acceptsCallbacks)&&n?await s.execute(t,n):await s.execute(t),i.end({status:"success"}),r}catch(t){if(t instanceof Error&&"Interrupted by user"===t.message){const e=sanitizeErrorForTelemetry({error:t,label:"tool_interrupted"});throw i.end({status:"error",error:e}),t}if(t instanceof y){const n=sanitizeErrorForTelemetry({error:t,label:`tool_input_invalid:${e}`});return i.end({status:"error",error:n}),formatZodErrorForModel(e,t)}if(t instanceof Error){const e=sanitizeErrorForTelemetry({error:t,label:"tool_error"});return i.end({status:"error",error:e}),`Error: ${t.message}`}return i.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(e){const t=e?.mode||"standard",n=null!==Cv()?[...hk]:hk.filter(e=>e.name!==iS.DIAGNOSTICS),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 i=[];return"plan"!==t&&getMcpConnectionManager().isInitialized&&(i=getAllMcpToolSchemas()),[...o,...s,...i,...fk]}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 Sk={};hk.forEach(e=>{Sk[e.name]=toPascalCase(e.name)}),fk.forEach(e=>{Sk[e.name]=toPascalCase(e.name)});var Ek={};Object.entries(Sk).forEach(([e,t])=>{Ek[t]=e}),initializeAgentManager({clientTools:hk,serverTools:fk,toolsMap:yk,displayNameToToolName:Ek}),Rs();var bk=null,Ck=!1,vk=new Set([iS.EDIT_FILE,iS.WRITE_FILE,iS.SHELL_COMMAND]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(Ck)return;Ck=!0;const e=__name(e=>{bk?.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(),bk=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{e.model&&setModelOverride(e.model),e.benchmarkOutput&&setBenchmarkOutput(e.benchmarkOutput);const n=await processQuery({query:t,signal:bk.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions,maxTurns:e.maxTurns??kk,verbose:e.verbose??!1});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 Cs&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof vs&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof xs&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Es&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof As&&(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 kk=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced(),{token:r,oauthProvider:o}=await getOAuthCredentials({provider:t});validateOAuthToken({token:r,provider:t});const s=getEnvironmentContext(),i=await getMemoryContent([]),a=await getTasteContent(),l=generateSkillsXML(await loadAllSkillSummaries())||null,u=crypto.randomUUID(),d=await isTasteLearningEnabled(),m={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.TASTE_LEARNING]:d.toString(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:n.toString(),...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};return r&&(m[Ut.OAUTH_TOKEN]=`Bearer ${r}`,o&&(m[Ut.OAUTH_PROVIDER]=o)),{tools:e,config:s,memory:i,taste:a,skills:l,headers:m,sessionId:u}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:getConfiguredModel()},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId};return consumeSSEStream(await e.post({body:s,stream:!0,endpoint:Bt.ALPHA.GENERATE,headers:t.headers,signal:r}))}async function executeToolCall(e,t,n){if(vk.has(e.toolName)&&!n)return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: Tool "${e.toolName}" requires permissions. Use --yolo (or --dangerously-skip-permissions) to enable file writes and shell commands in print mode.`}};try{const n=await executeTool(e.toolName,e.input,{abortSignal:t});return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:n}}}catch(t){if(t instanceof Cs||t instanceof vs||t instanceof xs||t instanceof Es||t instanceof As)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: ${n}`}}}}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall");var Tk=80;function truncate(e){return e.length<=Tk?e:e.slice(0,Tk)+"..."}function formatToolLabel(e){const t=e.input,n=__name(e=>truncate(String(t[e]??"")),"param");switch(e.toolName){case"shell_command":return`Shell: ${n("command")}`;case"read_file":return`Read: ${n("absolutePath")}`;case"edit_file":return`Edit: ${n("filePath")}`;case"write_file":return`Write: ${n("filePath")}`;case"grep":return`Search: ${n("pattern")}`;case"glob":return`Glob: ${n("pattern")}`;case"read_directory":return`List: ${n("path")}`;case"read_multiple_files":return`Read: ${truncate(String(t.include??""))}`;case"think":return"Thinking";case"explore":return"Exploring";case"todo_write":return"Updating todos";case"ask_user_question":return`Question: ${n("question")}`;case"kill_shell":return`Kill: ${n("processId")}`;case"web_search":return`Search: ${n("query")}`;case"web_fetch":return`Fetch: ${n("url")}`;case"get_diagnostics":return"Diagnostics";default:return e.toolName}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1,maxTurns:o,verbose:s}=e,i=getApiBaseUrl(),a=new jw({baseUrl:i}),l=[{role:"user",content:t}],u=await setupConversationContext(),d=createBenchmarkCollector();let m=0,g="";const h={stream:process.stderr,color:"cyan"},f=s?Re(h):null;try{for(;m<o;){if(m++,n.aborted)throw new Error("Cancelled");f?.start();const e=d?Date.now():0,t=await callApi(a,u,l,n),o=d?Date.now()-e:0;f?.stop();const i=t.usage,y=d?{turnNumber:m,apiDurationMs:o,toolCalls:[],toolDurationMs:0,inputTokens:i?.input_tokens??0,outputTokens:i?.output_tokens??0,cacheReadTokens:i?.cache_read_input_tokens??0,cacheCreationTokens:i?.cache_creation_input_tokens??0}:null,w=t.content.filter(e=>"text"===e.type),S=t.content.filter(e=>"tool-call"===e.type),E=w.map(e=>e.text).join("");if(E&&(g+=E),0===S.length){d&&y&&d.turnDetails.push(y);break}const C=[],v=d?Date.now():0;for(const e of S){if(n.aborted)throw new Error("Cancelled");let t=null;if(s){const n=formatToolLabel(e);t=Re({...h,text:n}).start()}const o=await executeToolCall(e,n,r);if(t){const e="error-text"===o.output.type?Pe.cross:Pe.tick;t.stopAndPersist({symbol:e})}const i="string"==typeof o.output?o.output:"value"in o.output?o.output.value:"";if(d&&"string"==typeof i){const{cleanContent:e,metrics:t}=extractAgentMetrics(i);t&&(d.agents.push(t),o.output={type:"text",value:e})}y&&y.toolCalls.push({name:e.toolName,isError:"error-text"===o.output.type}),C.push(o)}d&&y&&(y.toolDurationMs=Date.now()-v,d.turnDetails.push(y));const k=t.content.filter(e=>"tool-result"!==e.type);l.push({role:"assistant",content:k}),l.push({role:"tool",content:C})}m>=o&&(d&&(d.maxTurnsReached=!0),process.stderr.write(`Warning: Reached maximum conversation turns (${o}). The response may be incomplete. Use --max-turns to increase the limit.\n`))}finally{d&&writeBenchmarkMetrics(d)}return g}__name(truncate,"truncate"),__name(formatToolLabel,"formatToolLabel"),__name(processQuery,"processQuery"),Ot(),Ot(),Ot(),Ot(),wn(),fb(),Rs(),sS(),fS();var _k=Object.keys(Yt).sort((e,t)=>t.length-e.length),xk={NOT_AUTHENTICATED:"Not authenticated",SESSION_EXPIRED:"Session expired"},Ak=new Set(Object.values(xk));function isAuthErrorMessage(e){return Ak.has(e)}function formatCredits(e){return`$${e.toFixed(2)}`}function getPlanInfo({planId:e}){if(!e)return null;const t=e.toLowerCase().replace(/_/g,"-"),n=_k.find(e=>t.startsWith(e));if(!n)return null;const r=Yt[n];return r?{name:Jt[n]??n,monthlyCredits:r.total}:null}function getUsagePercent({used:e,total:t}){return t<=0?0:Math.min(e/t*100,100)}function getDaysRemaining(e){const t=new Date(e);return Number.isNaN(t.getTime())?null:Math.max(0,Math.ceil((t.getTime()-Date.now())/864e5))}async function safeFetch({request:e,endpoint:t}){try{return{data:await e.get({endpoint:t}),error:null}}catch(e){return e instanceof Es?{data:null,error:"Network error: unable to reach API"}:e instanceof Cs?{data:null,error:xk.SESSION_EXPIRED}:{data:null,error:`${t}: ${e instanceof Error?e.message:"Unknown error"}`}}}function buildEndpoint({endpoint:e,params:t}){if(!t)return e;const n=new URLSearchParams;for(const[e,r]of Object.entries(t))null!=r&&n.set(e,r);const r=n.toString();return r?`${e}?${r}`:e}async function fetchCredits({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/credits",params:{orgId:t}})})}async function fetchSubscription({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/subscriptions",params:{orgId:t}})})}async function fetchWhoami({request:e}){return safeFetch({request:e,endpoint:"/alpha/whoami"})}async function fetchUsageSummary({request:e,orgId:t,since:n}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/usage/summary",params:{orgId:t,since:n}})})}async function fetchUsageData(){if(!await getAuthKey())return{whoami:null,credits:null,subscription:null,summary:null,modelBreakdown:null,errors:[xk.NOT_AUTHENTICATED]};const e=getApiBaseUrl(),t=new jw({baseUrl:e}),n=await fetchWhoami({request:t}),r=n.data?.org?.id??null,[o,s]=await Promise.all([fetchCredits({request:t,orgId:r}),fetchSubscription({request:t,orgId:r})]),i=s.data?.data?.currentPeriodStart??null,a=await fetchUsageSummary({request:t,orgId:r,since:i}),l=[n.error,o.error,s.error,a.error].filter(e=>null!==e);return{whoami:n.data,credits:o.data,subscription:s.data,summary:a.data,modelBreakdown:a.data?.models??null,errors:l}}__name(isAuthErrorMessage,"isAuthErrorMessage"),__name(formatCredits,"formatCredits"),__name(getPlanInfo,"getPlanInfo"),__name(getUsagePercent,"getUsagePercent"),__name(getDaysRemaining,"getDaysRemaining"),__name(safeFetch,"safeFetch"),__name(buildEndpoint,"buildEndpoint"),__name(fetchCredits,"fetchCredits"),__name(fetchSubscription,"fetchSubscription"),__name(fetchWhoami,"fetchWhoami"),__name(fetchUsageSummary,"fetchUsageSummary"),__name(fetchUsageData,"fetchUsageData"),sS(),fS();var Pk={orgId:null,planId:null,purchasedCredits:0,freeCredits:0,fetchFailed:!0},Ik=null,Nk=null;function getCachedBillingContext(){return Ik}function getBillingContext(){return Ik&&!Ik.fetchFailed?Promise.resolve(Ik):Nk||(Nk=(async()=>{try{const e=new jw({baseUrl:getApiBaseUrl()}),t=await fetchWhoami({request:e}),n=t.data?.org?.id??null,[r,o]=await Promise.all([fetchSubscription({request:e,orgId:n}),fetchCredits({request:e,orgId:n})]);if(!t.data||!r.data||!o.data)return Pk;let s=null;if(r.data.success&&r.data.data){const{planId:e,status:t}=r.data.data;"active"!==t&&"past_due"!==t||(s=e)}const i={orgId:n,planId:s,purchasedCredits:o.data.credits.purchasedCredits??0,freeCredits:o.data.credits.freeCredits??0,fetchFailed:!1};return Ik=i,i}catch{return Pk}finally{Nk=null}})())}function prefetchBillingContext(){getBillingContext().catch(()=>{})}function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}__name(getCachedBillingContext,"getCachedBillingContext"),__name(getBillingContext,"getBillingContext"),__name(prefetchBillingContext,"prefetchBillingContext"),Ot(),Ot(),as(),Ot(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var Rk=["no job control","cannot set terminal process group"],Mk=null;function getShellInfo(){return Mk||(Mk=detectUserShell()),Mk}__name(getShellInfo,"getShellInfo");var Lk=__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 i=__name(e=>{s||(s=!0,t(e))},"doResolve"),a=getShellInfo(),l="bash"===a.type||"zsh"===a.type,u=l?a.path:"/bin/bash",d=be(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="",h=null;n>0&&(h=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({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>ts){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:zC,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>ns)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=>{h&&clearTimeout(h);const n=l?g.split("\n").filter(e=>!Rk.some(t=>e.includes(t))).join("\n"):g;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{h&&clearTimeout(h),i({stdout:m,stderr:g+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),$k=__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");_E();var Dk=__name(()=>{const[e,t]=Y({isExecuting:!1,currentCommand:null});return{executeBash:ee(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Lk(e,{timeout:3e4,cwd:process.cwd()}),o=$k(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]=pE(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]=pE(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=Y(!1),[n,r]=Y(!1),[o,s]=Y(!1),[i,a]=Y(!1),[l,u]=Y(!1),[d,m]=Y(!1),[g,h]=Y(!1),[f,y]=Y(!1),[w,S]=Y(!1),[E,C]=Y(!1),[v,k]=Y(!1),[T,_]=Y(!1),[x,A]=Y(!1),[P,I]=Y(!1),[N,R]=Y(!1),[M,L]=Y(!1),[$,D]=Y(!1),[O,F]=Y(0),[q,j]=Y(!1),[U,B]=Y("off");return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:o,setShowTasteConfig:s,showSkillsConfig:i,setShowSkillsConfig:a,showProviderSelector:l,setShowProviderSelector:u,showModelSelector:d,setShowModelSelector:m,showMemorySelector:g,setShowMemorySelector:h,showMcpManager:f,setShowMcpManager:y,showLearningFeed:w,setShowLearningFeed:S,showSessionSelector:E,setShowSessionSelector:C,showAddDirModal:v,setShowAddDirModal:k,showRewindSelector:T,setShowRewindSelector:_,showLoginOverlay:x,setShowLoginOverlay:A,showCompactModeSelector:P,setShowCompactModeSelector:I,showContextView:N,setShowContextView:R,showStatusView:M,setShowStatusView:L,showUsageOverlay:$,setShowUsageOverlay:D,staticKey:O,setStaticKey:F,showTasteSkipBanner:q,setShowTasteSkipBanner:j,transcriptMode:U,setTranscriptMode:B,expandedToolOutput:"off"!==U}}Ot(),__name(useUiOverlays,"useUiOverlays"),Ot(),_E();var Ok="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...sE("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return Ok?makeInjectedShellEntry("cmd-test-injected-live-entry",process.env.CMD_TEST_INJECT_INPUT??"sleep 60","running"):null}function buildInjectedFeed(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_FEED_ITEMS??"0",10);return!Number.isFinite(e)||e<=0?[]:Array.from({length:e},(e,t)=>makeInjectedShellEntry(`cmd-test-feed-${t}`,`echo item ${t}`,"completed",{output:`item ${t}`}))}function useFeed(){const[e,t]=Y(()=>buildInjectedFeed()),[n,r]=Y(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[o,s]=Y([]),[i,a]=Y(Ok),l=J([]);return X(()=>{l.current=o},[o]),{feed:e,setFeed:t,liveEntries:n,setLiveEntries:r,queuedMessages:o,setQueuedMessages:s,isCmdCodeBusy:i,setIsCmdCodeBusy:a,queuedMessagesRef:l}}function useSession(){const[e,t]=Y(crypto.randomUUID()),[n,r]=Y(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:J(null)}}function useStatus(e){const[t,n]=Y("Ready..."),r=J(!1),[o,s]=Y(""),i=J(null),[a,l]=Y(null),u=J(a),[d,m]=Y(null),[g,h]=Y(!1),[f,y]=Y(""),[w,S]=Y(null),[E,C]=Y(0),[v,k]=Y(null),[T,_]=Y(!1),[x,A]=Y(e??null);X(()=>{u.current=a},[a]),X(()=>{if(x){const e=setTimeout(()=>{A(null)},3e4);return()=>clearTimeout(e)}},[x]);const P=__name(e=>{i.current&&clearTimeout(i.current),s(e),i.current=setTimeout(()=>{s(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:o,setHintMessage:s,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:u,billingLink:d,setBillingLink:m,showShareNotification:g,setShowShareNotification:h,unshareNotificationMessage:f,setUnshareNotificationMessage:y,retryAttempt:w,setRetryAttempt:S,interactionTokens:E,setInteractionTokens:C,contextUsage:v,setContextUsage:k,tasteLearningEnabled:T,setTasteLearningEnabled:_,updateStatus:x,setUpdateStatus:A,showHintMessage:P}}function useAuth(){const[e,t]=Y(null),[n,r]=Y(getConfiguredModel()),[o,s]=Y(!1),[i,a]=Y(null),[l,u]=Y(!1),[d,m]=Y(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:o,setIsOAuthMode:s,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,premiumCreditsExhausted:d,setPremiumCreditsExhausted:m,providerNotificationTimer:J(null),modelNotificationTimer:J(null)}}__name(makeInjectedShellEntry,"makeInjectedShellEntry"),__name(buildInjectedLiveEntry,"buildInjectedLiveEntry"),__name(buildInjectedFeed,"buildInjectedFeed"),__name(useFeed,"useFeed"),Ot(),__name(useSession,"useSession"),Ot(),__name(useStatus,"useStatus"),Ot(),Jr(),__name(useAuth,"useAuth"),Ot(),Ot(),Ot(),wn(),xo();var Fk=new Set(["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprint0","-fprintf","-fls"]);function hasDangerousFindFlag(e){return e.some(e=>Fk.has(e))}function isDangerousFindCall({command:e,args:t}){if("find"!==e&&!e.startsWith("find "))return!1;const n=Array.isArray(t)?t.join(" "):t??"",r=et(`${e} ${n}`),o=[];for(const e of r){if("string"==typeof e){o.push(e);continue}const t=e?.pattern;if("string"!=typeof t)return!0;o.push(t)}return hasDangerousFindFlag(o)}__name(hasDangerousFindFlag,"hasDangerousFindFlag"),__name(isDangerousFindCall,"isDangerousFindCall");var qk=class extends qe{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 k.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,t){if(!this.config.enabled)return{allowed:!0};const n=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)||"plan"===t&&isPlanPath({filePath:e.filePath})?{allowed:!0}:this.config.sessionPermissions.has(n)?{allowed:this.config.sessionPermissions.get(n)||!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)?{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.trim()}:${e.args?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand({command:e,args:t}){return["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))?!isDangerousFindCall({command:e,args: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 k.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await k.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 k.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 k.mkdir(n,{recursive:!0});try{const t=await k.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 k.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},jk=__name((e={})=>{const[t,n]=Y(null),[r,o]=Y(null),[s,i]=Y(!1);return X(()=>{const t=e.projectRoot||process.cwd(),r=new qk(t);return r.on("permission-request",(t,n)=>{o(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:ee(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:ee(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:ee(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),i(!1)}},[t]),clearSessionPermissions:ee(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:ee(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:ee((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:ee(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="boolean"==typeof t?t?"auto-accept":"standard":t,o="auto-accept"===r||"bypass"===r,s=["create","edit","delete","execute","shellCommands"];for(const e of s)n.setAutoApprove(e,o)}function usePermissionMode({initialPermissionMode:e,dangerouslySkipPermissions:t=!1,setPendingPermission:n,setStatus:r,contextEngineRef:o}){const[s,i]=Y(()=>e||(t?"bypass":"standard")),a=J(s);X(()=>{a.current=s},[s]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:g}=jk({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{n({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),o.current&&r("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{n({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),o.current&&r("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?r("Permission granted"):r("Permission denied")},"onPermissionResponse")});return X(()=>{u&&applyAutoAcceptMode({enabled:s,service:u})},[s,u]),{permissionMode:s,setPermissionMode:i,permissionModeRef:a,permissionsService:u,respondToPrompt:d,clearSessionPermissions:m,dangerouslySkipPermissions:t}}function usePendingOps(){const[e,t]=Y(null),[n,r]=Y(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=Y(!1),[n,r]=Y(!1),[o,s]=Y(!0),[i,a]=Y(!1),[l,u]=Y(!1),[d,m]=Y(null),[g,h]=Y(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:o,setCheckingProject:s,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:u,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:m,autoLearnTaste:g,setAutoLearnTaste:h,tasteOnboardingCheckedRef:J(!1)}}function useExit(){const[e,t]=Y(!1),[n,r]=Y(null),o=J(null),s=J(0),i=J(null),a=ee(()=>{o.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:o,lastExitKeyTimeRef:s,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}async function resolveEditStartLine({filePath:e,oldContent:t}){const n=await O.readFile(e,"utf-8"),r=n.indexOf(t);if(-1!==r)return n.substring(0,r).split("\n").length}function isDirectoryEmpty(){try{return 0===B(process.cwd()).length}catch{return!1}}Ot(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Ot(),__name(usePendingOps,"usePendingOps"),Ot(),__name(useOnboarding,"useOnboarding"),Ot(),__name(useExit,"useExit"),Ot(),Ot(),Ot(),Ot(),__name(resolveEditStartLine,"resolveEditStartLine"),__name(isDirectoryEmpty,"isDirectoryEmpty"),Ot();var Uk=/(?<=[\s(\[{])\/([a-z0-9-]+)(?=[\s,.:;!?)\]}]|$)/g,Bk=/(?<=[\s(\[{])\/[a-z0-9-]+(?=[\s,.:;!?)\]}]|$)/;function hasInlineSkillToken(e){return Bk.test(e)}function tagSkillContent(e,t){return`<${ek}>${e}</${ek}>\n\n${t}`}function buildSlashCommandMessage(e){const{commandName:t,skillName:n,rawArguments:r}=e,o=[`<${Zv}>${n}</${Zv}>`,`<${ek}>${t}</${ek}>`];return 0===r.trim().length?o.join("\n"):[...o,`<${tk}>${r}</${tk}>`].join("\n")}function applySkillArguments({rawArguments:e,skillContent:t,positionalArgs:n}){let r=t.replace(/\$ARGUMENTS\[(\d+)\]|\$\{(\d+)\}/g,(e,t,r)=>{const o=t??r;if(!o)return"";const s=Number.parseInt(o,10);return Number.isNaN(s)?"":n[s]??""});return r=r.replace(/\$ARGUMENTS/g,e),0===e.trim().length||r!==t?r.trim():`${t.trimEnd()}\n\nARGUMENTS: ${e}`}function buildSlashCommandSkillContextMessage(e){const{rawArguments:t,skillContent:n,skillDirectory:r,positionalArgs:o}=e,s=`Base directory for this skill: ${r}`,i=applySkillArguments({rawArguments:t,skillContent:n,positionalArgs:o});return 0===i.length?s:`${s}\n\n${i}`}async function processSkillReferences(e){const n=await loadAllSkillSummaries(),{names:r}=await loadDisabledSkills(),o=new Map(deduplicateSkills(n).filter(e=>!r.has(e.name)).map(e=>[e.name,e]));if(0===o.size)return[];const s=[...e.matchAll(Uk)];if(0===s.length)return[];const i=[],a=new Set;for(const e of s){const n=e[1];if(!n)continue;if(a.has(n))continue;const r=o.get(n);if(r)try{const e=await loadSkill({filePath:r.filePath});i.push({skillName:n,content:e.content.trim(),skillDirectory:t.dirname(r.filePath)}),a.add(n)}catch{}}return i}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}__name(hasInlineSkillToken,"hasInlineSkillToken"),__name(tagSkillContent,"tagSkillContent"),__name(buildSlashCommandMessage,"buildSlashCommandMessage"),__name(applySkillArguments,"applySkillArguments"),__name(buildSlashCommandSkillContextMessage,"buildSlashCommandSkillContextMessage"),__name(processSkillReferences,"processSkillReferences"),Rs(),_E(),yS(),Ot(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),Ot(),WE(),Kn(),Jr();var zk=null;async function hasFirstMessageBeenTracked(){try{return!0===(await loadUserConfig()).firstMessageSent}catch{return!1}}async function markFirstMessageTracked(){try{await updateUserConfig({firstMessageSent:!0})}catch(e){dlog("[detect-first-message] failed to mark as tracked",{error:e})}}async function detectAndTrackFirstMessage(){if(!await hasFirstMessageBeenTracked())return zk||(zk=(async()=>{try{await trackLifecycleEvent({eventType:"cli_first_message"}),await markFirstMessageTracked(),dlog("[detect-first-message] tracked first message")}catch(e){dlog("[detect-first-message] failed to track",{error:e})}finally{zk=null}})())}function computePayloadHealth(e){let t=0,n=0,r=0,o=0,s=0,i=0;const a=new Set,l=new Set,u=new Set;for(const d of e)if("user"!==d.role){if("assistant"===d.role){if(n++,!Array.isArray(d.content))continue;let e=!1;for(const t of d.content)"tool-call"!==t.type||t.providerExecuted||(e=!0,s++,a.add(t.toolCallId));e&&o++;continue}if("tool"===d.role){if(r++,!Array.isArray(d.content))continue;for(const e of d.content)"tool-result"===e.type&&(i++,u.add(e.toolCallId),a.has(e.toolCallId)&&l.add(e.toolCallId))}}else t++;const d=a.size-l.size;let m=0;for(const e of u)a.has(e)||m++;const g=0===e.length?"none":e[e.length-1].role;return{messageCount:e.length,userMessageCount:t,assistantMessageCount:n,toolMessageCount:r,assistantWithToolUseCount:o,toolUseCount:s,toolResultCount:i,orphanToolUseCount:d,orphanToolResultCount:m,lastMessageRole:g}}function firstLine(e){const t=e.trim(),n=t.indexOf("\n"),r=-1===n?t:t.slice(0,n);return r.length>200?r.slice(0,200)+"…":r}function payloadHealthAttributes(e){return{[Mt.PAYLOAD_MESSAGE_COUNT]:e.messageCount,[Mt.PAYLOAD_USER_MESSAGE_COUNT]:e.userMessageCount,[Mt.PAYLOAD_ASSISTANT_MESSAGE_COUNT]:e.assistantMessageCount,[Mt.PAYLOAD_TOOL_MESSAGE_COUNT]:e.toolMessageCount,[Mt.PAYLOAD_ASSISTANT_WITH_TOOL_USE_COUNT]:e.assistantWithToolUseCount,[Mt.PAYLOAD_TOOL_USE_COUNT]:e.toolUseCount,[Mt.PAYLOAD_TOOL_RESULT_COUNT]:e.toolResultCount,[Mt.PAYLOAD_ORPHAN_TOOL_USE_COUNT]:e.orphanToolUseCount,[Mt.PAYLOAD_ORPHAN_TOOL_RESULT_COUNT]:e.orphanToolResultCount,[Mt.PAYLOAD_LAST_MESSAGE_ROLE]:e.lastMessageRole}}function attemptAttributes(e){const t={[Mt.API_ATTEMPT_NUMBER]:e.attempt,[Mt.API_ATTEMPT_DELAY_MS_BEFORE]:e.delayMsBefore,[Mt.API_ATTEMPT_STATUS]:e.status};return e.errorType&&(t[Mt.API_ATTEMPT_ERROR_TYPE]=e.errorType),e.errorMessage&&(t[Mt.API_ATTEMPT_ERROR_MESSAGE]=firstLine(e.errorMessage)),"number"==typeof e.httpStatus&&(t[Mt.API_ATTEMPT_HTTP_STATUS]=e.httpStatus),"boolean"==typeof e.isRetryable&&(t[Mt.API_ATTEMPT_IS_RETRYABLE]=e.isRetryable),t}function startIterationSpan(e){const t=getSessionId(),n=getActiveIterationSpanContext(),r={[Mt.ITERATION_NUMBER]:e.iteration,[Rt.REQUEST_MODEL]:e.model,[Rt.STEP_NAME]:`iteration_${e.iteration}`};e.capability&&(r[Rt.CAPABILITY_NAME]=e.capability),t&&(r["session.id"]=t,r[Rt.CONVERSATION_ID]=t),"number"==typeof e.initialMessageCount&&(r[Mt.ITERATION_INITIAL_MESSAGE_COUNT]=e.initialMessageCount);const o=ke.getTracer(_t),s=ke.deleteSpan(Te.active()),i=n?[{context:n,attributes:{"cmd.iteration.link_kind":"previous_iteration"}}]:void 0,a=o.startSpan("context:iteration",{attributes:r,kind:_e.INTERNAL,links:i,root:!0},s),l=a.spanContext();setActiveIterationSpanContext(l);let u=!1;return{span:a,spanContext:l,recordPayloadHealth(e){u||a.addEvent("context.payload_health",payloadHealthAttributes(e))},recordAttempt(e){u||a.addEvent("context.api_attempt",attemptAttributes(e))},setAttribute(e,t){u||a.setAttribute(e,t)},end({outcome:e,error:t}){if(u)return;u=!0,a.setAttribute(Mt.ITERATION_OUTCOME,e),t&&(a.setAttribute(Mt.ITERATION_TERMINAL_ERROR_TYPE,t.name),a.setAttribute(Mt.ITERATION_TERMINAL_ERROR_MESSAGE,firstLine(t.message)),a.recordException(t));const n="non_retryable_error"===e||"max_retries_exceeded"===e||"error"===e;a.setStatus({code:n?xe.ERROR:xe.OK,message:t?firstLine(t.message):void 0}),a.end(),setActiveIterationSpanContext(l)}}}function toToolDisplayName(e){return cC[e.toolName]||toRegexSafeAlias(e.toolName)}function toRegexSafeAlias(e){const t=e.replace(/[^A-Za-z0-9_]/g,"_").toUpperCase().replace(/^_+|_+$/g,"");return t?/^[A-Z]/.test(t)?t:`T_${t}`:"TOOL"}function getHookMatcherTarget(e){return toToolDisplayName({toolName:e.toolName})}__name(hasFirstMessageBeenTracked,"hasFirstMessageBeenTracked"),__name(markFirstMessageTracked,"markFirstMessageTracked"),__name(detectAndTrackFirstMessage,"detectAndTrackFirstMessage"),hs(),Ot(),__name(computePayloadHealth,"computePayloadHealth"),Ot(),fn(),Oo(),__name(firstLine,"firstLine"),__name(payloadHealthAttributes,"payloadHealthAttributes"),__name(attemptAttributes,"attemptAttributes"),__name(startIterationSpan,"startIterationSpan"),fS(),sS(),Of(),wn(),Lo(),Ot(),Ot(),Ot(),Ot(),Kn(),Ot(),yS(),__name(toToolDisplayName,"toToolDisplayName"),__name(toRegexSafeAlias,"toRegexSafeAlias"),__name(getHookMatcherTarget,"getHookMatcherTarget");var Hk=new Set([iS.WRITE_FILE,iS.EDIT_FILE,iS.READ_FILE,iS.READ_MULTIPLE_FILES,iS.READ_DIRECTORY,iS.DIAGNOSTICS]);function camelToSnake(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function toHookWireInput(e,t){if(!Hk.has(e))return t;const n={};for(const[e,r]of Object.entries(t))n[camelToSnake(e)]=r;return n}function normalizeEventName(e){return Object.values(zb).includes(e)?e:null}function createHookRegistry(){const e=[],t=new Map,n=[];return{initialize:__name(async r=>{const{projectRoot:o}=r,s=[{path:getProjectLocalPath(o),source:"project-local"},{path:getProjectSharedPath(o),source:"project-shared"},{path:getUserSettingsPath(),source:"user"}],i=new Set;for(const{path:r,source:o}of s){const s=await loadSettingsFile(r);s&&(s.warning?(dlog(`[Hook] ${s.warning}`),n.push(s.warning)):s.settings&&loadHooksFromSource({settingsPath:r,source:o,settings:s.settings,seenCommands:i,entries:e,matcherCache:t,validationWarnings:n,normalizeEventName:normalizeEventName}))}e.length>0&&dlog(`[Hook] Loaded ${e.length} hook(s)`)},"initialize"),normalizeEventName:normalizeEventName,getHooksForEvent:__name(n=>{const{eventName:r,toolName:o}=n;return e.filter(e=>{if(e.eventName!==r)return!1;if(e.matcher){if(!o)return!1;const n=getOrCompileRegex({cache:t,pattern:e.matcher});if(!n)return!1;if(!n.test(getHookMatcherTarget({toolName:o})))return!1}return!0})},"getHooksForEvent"),getAllHooks:__name(()=>[...e],"getAllHooks"),getHookCount:__name(()=>e.length,"getHookCount"),getValidationWarnings:__name(()=>[...n],"getValidationWarnings")}}function getTrustFilePath(){return e.join(w.homedir(),".commandcode","trusted-hooks.json")}function computeFingerprint(e){return N.createHash("sha256").update(e.command).digest("hex").slice(0,16)}function createTrustManager(){let t={},n=!1;return{load:__name(async()=>{if(!n){try{const e=await v.readFile(getTrustFilePath(),"utf-8");t=JSON.parse(e)}catch{t={}}n=!0}},"load"),checkTrust:__name(e=>{const{hookConfig:n,source:r,projectRoot:o}=e;if("user"===r)return"trusted";const s=computeFingerprint(n);return(t[o]||[]).find(e=>e.fingerprint===s)?"trusted":"new"},"checkTrust"),trust:__name(e=>{const{hookConfig:n,projectRoot:r}=e,o=computeFingerprint(n);t[r]||(t[r]=[]);const s=t[r];s.some(e=>e.fingerprint===o)||s.push({fingerprint:o,trustedAt:(new Date).toISOString()})},"trust"),save:__name(async()=>{const n=getTrustFilePath(),r=e.dirname(n);await v.mkdir(r,{recursive:!0}),await v.writeFile(n,JSON.stringify(t,null,2))},"save"),getTrustedHooks:__name(e=>t[e]||[],"getTrustedHooks")}}function collectTrustWarnings(e){const{registry:t,trustManager:n,projectRoot:r}=e,o=[];let s=0;for(const e of t.getAllHooks()){const t=n.checkTrust({hookConfig:e.config,source:e.source,projectRoot:r});"trusted"!==t&&("new"===t&&s++,n.trust({hookConfig:e.config,projectRoot:r}))}s>0&&dlog(`[Hook] ${s} new hook(s) trusted on first execution`);for(const e of t.getValidationWarnings())o.push(e);return o}function auditLogPath(t){const n=t.sessionId?`hooks-audit-${t.sessionId}.jsonl`:"hooks-audit.jsonl";return e.join(t.sessionDir,n)}function createAuditLogger(t){const n=auditLogPath(t);let r=null;const o=__name(()=>(r||(r=v.mkdir(e.dirname(n),{recursive:!0}).then(()=>{})),r),"ensureDir");let s=Promise.resolve();return{log:__name(e=>{const t=s.then(async()=>{try{await o();const t=JSON.stringify(e)+"\n";await v.appendFile(n,t)}catch(e){dlog(`[Hook] Audit log write failed: ${getErrorMessage(e)}`)}});return s=t,t},"log")}}__name(camelToSnake,"camelToSnake"),__name(toHookWireInput,"toHookWireInput"),__name(normalizeEventName,"normalizeEventName"),__name(createHookRegistry,"createHookRegistry"),Ot(),wn(),__name(getTrustFilePath,"getTrustFilePath"),__name(computeFingerprint,"computeFingerprint"),__name(createTrustManager,"createTrustManager"),Ot(),Kn(),__name(collectTrustWarnings,"collectTrustWarnings"),Ot(),Kn(),__name(auditLogPath,"auditLogPath"),__name(createAuditLogger,"createAuditLogger"),Ot(),Ot(),Ot();var Wk=[/API_KEY/i,/SECRET/i,/TOKEN/i,/PASSWORD/i,/ANTHROPIC_/i,/COMMANDCODE_API/i,/OAUTH/i,/CREDENTIAL/i,/PRIVATE_KEY/i,/(^|_)AUTH(_|$)/i,/(^|_)AUTHORIZATION(_|$)/i,/(^|_)BEARER(_|$)/i,/AWS_ACCESS_KEY/i,/AWS_SECRET/i,/AWS_SESSION_TOKEN/i];function sanitizeEnvironment(e){const{env:t,input:n}=e,r={};for(const[e,n]of Object.entries(t))void 0!==n&&(Wk.some(t=>t.test(e))||(r[e]=n));return r.COMMANDCODE_PROJECT_DIR=n.cwd,r.COMMANDCODE_SESSION_ID=n.session_id,r.COMMANDCODE_CWD=n.cwd,r.COMMANDCODE_HOOK_EVENT=n.hook_event_name,r}__name(sanitizeEnvironment,"sanitizeEnvironment"),Ot(),Kn(),Ot(),Ot();var Gk={cancel:{hint:'Use "continue": false to stop the session, or hookSpecificOutput.permissionDecision: "deny" (PreToolUse) to block the tool.'},blocked:{hint:'Use hookSpecificOutput.permissionDecision: "deny" (PreToolUse) to block.'},shouldContinue:{hint:'Use "continue": false with "stopReason" to halt the session.'},decision:{hint:'Use hookSpecificOutput.permissionDecision: "allow"|"deny" (PreToolUse). Top-level decision is PostToolUse-only.',suppressFor:["PostToolUse"]},reason:{hint:'Use hookSpecificOutput.permissionDecisionReason (PreToolUse) or "systemMessage" for user messaging. Top-level reason is PostToolUse-only.',suppressFor:["PostToolUse"]},message:{hint:'Use "systemMessage" for user messaging, or hookSpecificOutput.additionalContext for context injection.'},error:{hint:"Use hookSpecificOutput.permissionDecisionReason (PreToolUse) or exit with code 2 and write to stderr."},errorMessage:{hint:"Use hookSpecificOutput.permissionDecisionReason (PreToolUse) or exit with code 2 and write to stderr."},contextModification:{hint:"Use hookSpecificOutput.additionalContext instead."}},Vk=new Set(["continue","suppressOutput","stopReason","systemMessage","hookSpecificOutput"]),Qk=new Set(["decision","reason"]);function getValidFieldsForEvent(e){return"PostToolUse"===e?new Set([...Vk,...Qk]):Vk}function validateHookOutput(e){const{stdout:t,hookName:n,eventName:r}=e,o=[],s=getValidFieldsForEvent(r),i=[...s].join(", "),a=t.trim();if(!a)return{status:"empty",warnings:o};let l;try{l=JSON.parse(a),"string"==typeof l&&(l=JSON.parse(l))}catch{const e="non-JSON stdout";return o.push(`Hook "${n}" wrote non-JSON to stdout. Output was ignored. Expected JSON object with optional fields: ${i}.`),{status:"parse-error",reason:e,warnings:o}}if("object"!=typeof l||null===l||Array.isArray(l)){const e=Array.isArray(l)?"an array":typeof l;return o.push(`Hook "${n}" returned ${e}. Expected JSON object.`),{status:"parse-error",reason:`expected object, got ${e}`,warnings:o}}const u=l;for(const[e,t]of Object.entries(Gk))e in u&&(t.suppressFor?.includes(r)||o.push(`Hook "${n}": unexpected field "${e}". ${t.hint}`));for(const e of Object.keys(u))s.has(e)||e in Gk||o.push(`Hook "${n}": unknown field "${e}". Valid fields: ${i}`);const d=("PreToolUse"===r?gC:hC).safeParse(u);if(!d.success){const e=d.error.issues.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ");return o.push(`Hook "${n}": validation error: ${e}`),{status:"schema-error",reason:e,warnings:o}}const m=d.data;return m.hookSpecificOutput?.hookEventName&&m.hookSpecificOutput.hookEventName!==r&&o.push(`Hook "${n}": hookSpecificOutput.hookEventName "${m.hookSpecificOutput.hookEventName}" does not match "${r}".`),{status:"valid",output:m,warnings:o}}function resolveProcessExit(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,processOutput:s}=e,{exitCode:i,stdout:a,stderr:l,duration:u,toolName:d,toolUseId:m}=s,g=validateHookOutput({stdout:a,hookName:n,eventName:o});for(const e of g.warnings)dlog(`[Hook] ${e}`);const h="valid"===g.status?g.output:void 0,f={hookName:n,displayLabel:r,eventName:o,exitCode:i,duration:u,stdout:a,stderr:l,scriptPath:deriveScriptPath(t.command),stderrFirstLine:firstNonEmptyLine(l),toolName:d,toolUseId:m};if(2===i){const e=h?.hookSpecificOutput?.permissionDecisionReason??h?.reason;return{...f,success:!0,output:h,blocked:!0,blockReason:resolveBlockReason({reason:e,stderr:l.trim(),fallback:`Hook "${r}" exited with code 2`})}}if(t.failClosed&&0!==i)return{...f,success:!1,output:h,blocked:!0,blockReason:`Security hook "${r}" failed (exit code ${i}). Action blocked (failClosed). Error: ${l.trim()||"unknown"}`};if(t.failClosed&&0===i&&a.trim().length>0&&("parse-error"===g.status||"schema-error"===g.status))return{...f,success:!1,output:h,blocked:!0,blockReason:`Security hook "${r}" returned invalid output (failClosed). ${g.reason??"invalid output"}`};if(0!==i)return{...f,success:!1,output:h,blocked:!1};const y=h?deriveBlockFromOutput({eventName:o,output:h,displayLabel:r}):{blocked:!1,blockReason:void 0};return{...f,success:!0,output:h,blocked:y.blocked,blockReason:y.blockReason}}function deriveBlockFromOutput(e){if("PreToolUse"===e.eventName){const t=e.output.hookSpecificOutput;return"deny"===t?.permissionDecision?{blocked:!0,blockReason:t.permissionDecisionReason??`Blocked by hook "${e.displayLabel}"`}:{blocked:!1}}return"PostToolUse"===e.eventName&&"block"===e.output.decision?{blocked:!0,blockReason:e.output.reason??`PostToolUse hook "${e.displayLabel}" requested retry`}:{blocked:!1}}function failClosedBlockReason(e){return`Hook "${e.displayLabel}" failed (failClosed): ${e.cause}`}function buildSpawnThrowResult(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,error:s,toolName:i,toolUseId:a,startTime:l}=e,u=s instanceof Error?s:new Error(String(s)),d=Boolean(t.failClosed);return{hookName:n,displayLabel:r,eventName:o,success:!1,error:u,blocked:d,blockReason:d?failClosedBlockReason({displayLabel:r,cause:`Failed to spawn: ${u.message}`}):void 0,duration:Date.now()-l,scriptPath:deriveScriptPath(t.command),toolName:i,toolUseId:a}}function buildChildErrorResult(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,error:s,stderr:i,toolName:a,toolUseId:l,startTime:u}=e,d=Boolean(t.failClosed);return{hookName:n,displayLabel:r,eventName:o,success:!1,error:s,blocked:d,blockReason:d?failClosedBlockReason({displayLabel:r,cause:`Failed to start: ${s.message}`}):void 0,duration:Date.now()-u,stderr:i,scriptPath:deriveScriptPath(t.command),stderrFirstLine:firstNonEmptyLine(i),toolName:a,toolUseId:l}}function buildTimeoutResult(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,timeoutMs:s,stdout:i,stderr:a,toolName:l,toolUseId:u,startTime:d}=e,m=Boolean(t.failClosed);return{hookName:n,displayLabel:r,eventName:o,success:!1,error:new Error(`Hook "${r}" timed out after ${s}ms`),blocked:m,blockReason:m?failClosedBlockReason({displayLabel:r,cause:`Timed out after ${s}ms`}):void 0,duration:Date.now()-d,stdout:i,stderr:a,scriptPath:deriveScriptPath(t.command),stderrFirstLine:firstNonEmptyLine(a),toolName:l,toolUseId:u}}function getShellConfig(){return"win32"===process.platform?{executable:"cmd.exe",args:["/c"]}:{executable:"/bin/bash",args:["--norc","--noprofile","-c"]}}function collectStream(e){e.stream?.on("data",t=>{e.buffer.value.length>=Bb||(e.buffer.value+=t.toString(),e.buffer.value.length>Bb&&(e.buffer.value=e.buffer.value.slice(0,Bb)))})}function extractToolMeta(e){let t,n;return"tool_name"in e&&"string"==typeof e.tool_name&&(t=e.tool_name),"tool_use_id"in e&&"string"==typeof e.tool_use_id&&(n=e.tool_use_id),{toolName:t,toolUseId:n}}function scheduleKillEscalation(e){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}async function executeCommandHook(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,input:s}=e,i=t.timeout?Math.round(1e3*t.timeout):3e4,a=Date.now(),{toolName:l,toolUseId:u}=extractToolMeta(s),d=sanitizeEnvironment({env:process.env,input:s}),m=getShellConfig(),g={config:t,hookLabel:n,displayLabel:r,eventName:o,toolName:l,toolUseId:u,startTime:a};return new Promise(e=>{const h={value:""},f={value:""};let y=!1,w=null;const S=__name(t=>{y||(y=!0,w&&clearTimeout(w),e(t))},"finish");let E;try{E=be(m.executable,[...m.args,t.command],{env:d,cwd:s.cwd,stdio:["pipe","pipe","pipe"]})}catch(e){return void S(buildSpawnThrowResult({...g,error:e}))}E.stdin?.on("error",()=>{});try{E.stdin?.write(JSON.stringify(s)),E.stdin?.end()}catch{}collectStream({stream:E.stdout,buffer:h}),collectStream({stream:E.stderr,buffer:f}),E.on("close",e=>{S(resolveProcessExit({config:t,hookLabel:n,displayLabel:r,eventName:o,processOutput:{exitCode:e??1,stdout:h.value,stderr:f.value,duration:Date.now()-a,toolName:l,toolUseId:u}}))}),E.on("error",e=>{S(buildChildErrorResult({...g,error:e,stderr:f.value}))}),w=setTimeout(()=>{scheduleKillEscalation(E),S(buildTimeoutResult({...g,timeoutMs:i,stdout:h.value,stderr:f.value}))},i)})}function labelFor(e){return buildHookLabel({source:e.source,eventName:e.eventName,definitionIndex:e.definitionIndex,hookIndex:e.hookIndex,command:e.config.command})}function displayLabelFor(e){return buildHookDisplayLabel(e.config.command)}function buildAuditEntry(e){const{eventName:t,result:n}=e,r=!0===n.output?.suppressOutput;return{timestamp:(new Date).toISOString(),eventName:t,hookName:n.hookName,hookType:"command",exitCode:n.exitCode,duration:n.duration,blocked:n.blocked,output:r?void 0:n.output,error:n.error?.message,...n.toolName?{toolName:n.toolName}:{},...n.toolUseId?{toolUseId:n.toolUseId}:{}}}async function executeSingle(e){const{entry:t,eventName:n,input:r}=e,o=labelFor(t),s=displayLabelFor(t);try{return await executeCommandHook({config:t.config,hookLabel:o,displayLabel:s,eventName:n,input:r})}catch(e){const r=Boolean(t.config.failClosed);return{hookName:o,displayLabel:s,eventName:n,success:!1,error:e instanceof Error?e:new Error(getErrorMessage(e)),blocked:r,blockReason:r?`Hook "${s}" failed (failClosed): ${getErrorMessage(e)}`:void 0,duration:0}}}function fireAsync(e){const{entry:t,eventName:n,input:r,auditLogger:o}=e,s=labelFor(t),i=displayLabelFor(t);logFireAndForget(executeCommandHook({config:t.config,hookLabel:s,displayLabel:i,eventName:n,input:r}).then(e=>{logFireAndForget(o.log(buildAuditEntry({eventName:n,result:e})))},e=>{const t={hookName:s,displayLabel:i,eventName:n,success:!1,error:e instanceof Error?e:new Error(getErrorMessage(e)),blocked:!1,duration:0};logFireAndForget(o.log(buildAuditEntry({eventName:n,result:t})))}))}async function executeSequential(e){const{entries:t,eventName:n,input:r,auditLogger:o}=e,s=[];for(const e of t){if(e.config.async){fireAsync({entry:e,eventName:n,input:r,auditLogger:o});continue}const t=await executeSingle({entry:e,eventName:n,input:r});if(s.push(t),t.blocked)break}return s}async function executeParallel(e){const{entries:t,eventName:n,input:r,auditLogger:o}=e,s=t.filter(e=>!e.config.async),i=t.filter(e=>e.config.async);for(const e of i)fireAsync({entry:e,eventName:n,input:r,auditLogger:o});return(await Promise.allSettled(s.map(e=>executeSingle({entry:e,eventName:n,input:r})))).map((e,t)=>"fulfilled"===e.status?e.value:{hookName:labelFor(s[t]),displayLabel:displayLabelFor(s[t]),eventName:n,success:!1,error:e.reason instanceof Error?e.reason:new Error(getErrorMessage(e.reason)),blocked:!1,duration:0})}function aggregateResults(e){const{results:t,eventName:n}=e,r=Hb.has(n);let o,s,i=!1,a=!1;const l=[],u=[];let d=0;for(const e of t){if(d+=e.duration,r&&e.blocked&&!i&&(i=!0,o=e.blockReason??`Blocked by hook "${e.displayLabel}"`),!e.success)continue;const t=e.output;t&&(t.hookSpecificOutput?.additionalContext&&l.push(t.hookSpecificOutput.additionalContext),t.systemMessage&&u.push(t.systemMessage),!1!==t.continue||a||(a=!0,s=t.stopReason))}return{blocked:i,blockReason:o,stop:a,stopReason:s,additionalContext:l.length>0?truncateHookContext({additionalContext:l.join("\n")}):void 0,systemMessages:u,results:t,totalDuration:d}}function truncateHookContext(e){return e.additionalContext.length<=4e3?e.additionalContext:e.additionalContext.slice(0,4e3)+"\n[Hook context truncated to 4000 characters]"}__name(getValidFieldsForEvent,"getValidFieldsForEvent"),__name(validateHookOutput,"validateHookOutput"),__name(resolveProcessExit,"resolveProcessExit"),__name(deriveBlockFromOutput,"deriveBlockFromOutput"),Ot(),__name(failClosedBlockReason,"failClosedBlockReason"),__name(buildSpawnThrowResult,"buildSpawnThrowResult"),__name(buildChildErrorResult,"buildChildErrorResult"),__name(buildTimeoutResult,"buildTimeoutResult"),__name(getShellConfig,"getShellConfig"),__name(collectStream,"collectStream"),__name(extractToolMeta,"extractToolMeta"),__name(scheduleKillEscalation,"scheduleKillEscalation"),__name(executeCommandHook,"executeCommandHook"),__name(labelFor,"labelFor"),__name(displayLabelFor,"displayLabelFor"),__name(buildAuditEntry,"buildAuditEntry"),__name(executeSingle,"executeSingle"),__name(fireAsync,"fireAsync"),__name(executeSequential,"executeSequential"),__name(executeParallel,"executeParallel"),Ot(),__name(aggregateResults,"aggregateResults"),__name(truncateHookContext,"truncateHookContext"),Kn(),Ot(),Kn(),Ot();var Kk=new class extends qe{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;_authResolve=null;_authReject=null;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:i,promptCount:a,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:i,promptCount:a,learningCount:l,categories:u,storage:d};this.events.unshift(m),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",m)}emitStepStart(e){this.addEvent({type:"step_start",...e})}emitProgress(e){this.addEvent({type:"progress",...e})}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}waitForAuth(){return new Promise((e,t)=>{this._authResolve=e,this._authReject=t})}resolveAuth(){this._authResolve?.(),this._authResolve=null,this._authReject=null}rejectAuth(e){this._authReject?.(new Error(e??"Login cancelled")),this._authResolve=null,this._authReject=null}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this._authReject?.(new Error("Reset during auth")),this._authResolve=null,this._authReject=null,this.emit("reset")}};function getGlobalProjectSettingsDir(t=process.cwd()){const n=Fe(t);return e.join(S.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 v.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 v.mkdir(o,{recursive:!0}),await v.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),Kk.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 v.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}function createHookSystem(e){const t=createHookRegistry(),n=createTrustManager(),r=createAuditLogger({sessionDir:getGlobalProjectSettingsDir(e.projectRoot),sessionId:e.sessionId});let o=!1,s=null,i=[];const a=__name(async()=>{if(!o)return s||(s=__name(async()=>{await t.initialize({projectRoot:e.projectRoot}),await n.load(),i=collectTrustWarnings({registry:t,trustManager:n,projectRoot:e.projectRoot});try{await n.save()}catch(e){dlog(`[Hook] Trust save failed during init: ${getErrorMessage(e)}`)}o=!0;const r=t.getHookCount();r>0&&dlog(`[Hook] Initialized with ${r} hook(s)`)},"doInit")().catch(e=>{throw s=null,e}),void await s)},"initialize"),l=__name(async n=>{const o={blocked:!1,stop:!1,systemMessages:[],results:[],totalDuration:0};if("plan"===e.runMode||"plan"===n.input.permission_mode)return o;try{await a()}catch(e){return dlog(`[Hook] Hook initialization failed: ${getErrorMessage(e)}`),o}const s=t.normalizeEventName(n.eventName);if(!s)return dlog(`[Hook] Unknown event name: ${n.eventName}`),o;const i=t.getHooksForEvent({eventName:s,toolName:n.toolName});if(0===i.length)return o;const l=Hb.has(s),u={entries:i,eventName:s,input:n.input,auditLogger:r},d=l?await executeSequential(u):await executeParallel(u);for(const e of d)logFireAndForget(r.log(buildAuditEntry({eventName:s,result:e})));return aggregateResults({results:d,eventName:s})},"fireEvent");return{initialize:a,fireEvent:l,drainTrustWarnings:__name(()=>{const e=[...i];return i=[],e},"drainTrustWarnings"),getRegistry:__name(()=>t,"getRegistry"),shutdown:__name(async()=>{try{await n.save()}catch(e){dlog(`[Hook] Trust save failed during shutdown: ${getErrorMessage(e)}`)}},"shutdown")}}function getProjectsBasePath(){return t.join(S.homedir(),".commandcode","projects")}function getProjectDirName(e){return Fe(e.cwd)}function getTranscriptPath(e){return t.join(getProjectsBasePath(),getProjectDirName({cwd:e.cwd}),`${e.sessionId}.jsonl`)}function baseInput(e){return{session_id:e.sessionId,transcript_path:getTranscriptPath({cwd:e.cwd,sessionId:e.sessionId}),cwd:e.cwd,hook_event_name:e.eventName,permission_mode:e.permissionMode}}function buildPreToolUseInput(e){return{...baseInput({...e,eventName:"PreToolUse"}),tool_use_id:e.toolUseId,tool_name:e.toolName,tool_display_name:toToolDisplayName({toolName:e.toolName}),tool_input:toHookWireInput(e.toolName,e.toolInput)}}function buildPostToolUseInput(e){return{...baseInput({...e,eventName:"PostToolUse"}),tool_use_id:e.toolUseId,tool_name:e.toolName,tool_display_name:toToolDisplayName({toolName:e.toolName}),tool_input:toHookWireInput(e.toolName,e.toolInput),tool_response:e.toolResponse}}function formatHookSaysLine(e,t){return`${e}: ${t}`}function formatHookBlock(e,t,n){return`${e}:${t} blocked: ${n}`}function formatHookError(e,t,n,r){const o=`${e}:${t} hook error:`;return n?`${o} [${n}]: ${r}`:`${o} ${r}`}function formatHookStop(e,t,n){return`${e}:${t} hook stopped continuation: ${n??"session halt requested"}`}function formatHookDenyMessage(e){return`${e}\n\n(Blocked by hook policy. Do not retry this tool — choose another approach or ask the user.)`}async function firePreToolUseHook(e){const{hookSystem:t,baseParams:n,toolBlock:r}=e,o=SE(r.toolName),s=await t.fireEvent({eventName:"PreToolUse",input:buildPreToolUseInput({...n,toolUseId:r.toolCallId,toolName:r.toolName,toolInput:r.input}),toolName:r.toolName}),i=buildHookLines("PreToolUse",s);if(s.blocked){const e=s.blockReason||"PreToolUse hook denied execution",t=buildBlockOrErrorOutcome({event:"PreToolUse",toolDisplayName:o,aggregate:s,fallbackReason:e});return{blocked:!0,denyReason:formatHookDenyMessage(e),stopSession:s.stop,sessionStopReason:s.stopReason,hookLines:i,hookOutcome:t}}return{blocked:!1,additionalContext:s.additionalContext,stopSession:s.stop,sessionStopReason:s.stopReason,hookLines:i,hookOutcome:s.stop?{kind:"stop",text:formatHookStop("PreToolUse",o,s.stopReason)}:void 0}}async function firePostToolUseHook(e){const{hookSystem:t,baseParams:n,toolBlock:r,toolResponse:o}=e,s=SE(r.toolName);try{const e=await t.fireEvent({eventName:"PostToolUse",input:buildPostToolUseInput({...n,toolUseId:r.toolCallId,toolName:r.toolName,toolInput:r.input,toolResponse:o}),toolName:r.toolName}),i=buildHookLines("PostToolUse",e),a=resolvePostHookOutcome({toolDisplayName:s,aggregate:e});return{additionalContext:e.additionalContext,stopSession:e.stop,sessionStopReason:e.stopReason,hookLines:i,hookOutcome:a}}catch(e){return dlog(`[Hook] PostToolUse dispatch failed: ${getErrorMessage(e)}`),{hookLines:[]}}}function wrapHookContextChunk(e){const t=e.context.replaceAll("</hook_context>","</hook_context>");return`<hook_context source="${e.source}" tool="${e.toolName}">${t}</hook_context>`}function buildHookLines(e,t){const n=[];for(const r of t.results)n.push(...linesForResult(e,r));return n}function linesForResult(e,t){const n=t.output?.systemMessage;if(n){const t=n.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(t.length>0){const n=[formatHookSaysLine(e,t[0])];for(let e=1;e<t.length;e++)n.push(t[e]);return n}}const r=t.output?.hookSpecificOutput?.additionalContext;return r?[formatHookSaysLine(e,`${t.displayLabel} added context`)]:[]}function buildBlockOrErrorOutcome(e){const{event:t,toolDisplayName:n,aggregate:r,fallbackReason:o}=e,s=r.results.find(e=>e.blocked);return 2===s?.exitCode?{kind:"hook-error",text:formatHookError(t,n,s.scriptPath,s.stderrFirstLine??s.blockReason??o)}:{kind:"block",text:formatHookBlock(t,n,o)}}function resolvePostHookOutcome(e){const{toolDisplayName:t,aggregate:n}=e,r=n.results.find(e=>e.blocked);if(r){const e=r.blockReason??"PostToolUse hook requested retry";return 2===r.exitCode?{kind:"hook-error",text:formatHookError("PostToolUse",t,r.scriptPath,r.stderrFirstLine??e)}:{kind:"block",text:formatHookBlock("PostToolUse",t,e)}}if(n.stop)return{kind:"stop",text:formatHookStop("PostToolUse",t,n.stopReason)}}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])),i=[],a=[],l=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?i.push(e):e.confidence>t?a.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&l.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:i,upgraded:a,downgraded:l}}wn(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),__name(createHookSystem,"createHookSystem"),Ot(),Ot(),wn(),__name(getProjectsBasePath,"getProjectsBasePath"),__name(getProjectDirName,"getProjectDirName"),__name(getTranscriptPath,"getTranscriptPath"),__name(baseInput,"baseInput"),__name(buildPreToolUseInput,"buildPreToolUseInput"),__name(buildPostToolUseInput,"buildPostToolUseInput"),Ot(),__name(formatHookSaysLine,"formatHookSaysLine"),__name(formatHookBlock,"formatHookBlock"),__name(formatHookError,"formatHookError"),__name(formatHookStop,"formatHookStop"),_E(),Kn(),__name(formatHookDenyMessage,"formatHookDenyMessage"),__name(firePreToolUseHook,"firePreToolUseHook"),__name(firePostToolUseHook,"firePostToolUseHook"),__name(wrapHookContextChunk,"wrapHookContextChunk"),__name(buildHookLines,"buildHookLines"),__name(linesForResult,"linesForResult"),__name(buildBlockOrErrorOutcome,"buildBlockOrErrorOutcome"),__name(resolvePostHookOutcome,"resolvePostHookOutcome"),Jr(),ao(),Ot(),wn(),Kn(),Ot(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),Jr(),ao(),hs();var Yk=new Jv("LearningAgent"),Jk=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:cs.LEARNING_AGENT,heading:"Learning pass failed"}}),Kk.addEvent({type:"error",message:n||"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)];Kk.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,i=Math.max(20,s),a=Math.max(0,t.length-i),l=t.slice(a);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.toolName).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:"tool",content:n}),u++}u>=this.maxTurns&&Yk.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Kk.addEvent({type:"no_learnings",message:"no changes to taste"}),Kk.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool-call"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.toolName,input:e.input});const t=this.adjustPathsForTaste({toolName:e.toolName,input:e.input});let o="",s="";if("write_file"===e.toolName||"edit_file"===e.toolName){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await L.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.toolName||"edit_file"===e.toolName){const e=t.filePath;e&&this.validateFinalTastePath(e)}const i=await executeTool(e.toolName,t,{allowTasteWrite:!0});let a="";if(("write_file"===e.toolName||"edit_file"===e.toolName)&&s)try{a=await L.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.toolName||"edit_file"===e.toolName){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:a});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{Kk.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Kk.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Kk.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:i}})}catch(t){n.push({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value: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 i=e.normalize(s);if(i.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${s}`);const a=e.resolve(e.join(this.tasteDir,i));if(!this.isPathInsideTasteDir(a))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 i="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)){const n=e.resolve(t);if(!this.isPathInsideTasteDir(n))throw new Error(`Security: Absolute path outside taste directory: ${t}`);if(i&&!this.isValidTasteFilePath(n))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=n}else{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.resolve(r),!this.isPathInsideTasteDir(r))throw new Error(`Security: Resolved path escapes taste directory: ${t} -> ${r}`);if(i&&!this.isValidTasteFilePath(r))throw new Error(`Invalid adjusted path: ${r}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}o[s]=r}return o}isPathInsideTasteDir(t){const n=e.resolve(this.tasteDir),r=e.resolve(t);if(r===n)return!0;const o=e.relative(n,r);return""!==o&&!o.startsWith("..")&&!e.isAbsolute(o)}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isPathInsideTasteDir(e))throw new Error(`Security: Resolved path escapes taste directory: ${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(!L.existsSync(this.tasteDir)){L.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");L.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!L.existsSync(t))return!1;const n=L.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");L.mkdirSync(r,{recursive:!0}),Kk.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const i=`# ${t.name}\n${t.learnings.join("\n")}\n`;L.writeFileSync(s,i,"utf-8");const a=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,a)}return L.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 L.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=L.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const i=o[t],a=t===o.length-1,l=a?"└── ":"├── ";if(i.isDirectory()){s+=`${r}${l}${i.name}/\n`;const t=r+(a?" ":"│ ");s+=await this.buildTree({dir:e.join(n,i.name),prefix:t})}else if("taste.md"===i.name){const t=(L.readFileSync(e.join(n,i.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${l}${i.name} (${t} learnings)\n`}else s+=`${r}${l}${i.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(),{token:o,oauthProvider:s}=await getOAuthCredentials({provider:n});validateOAuthToken({token:o,provider:n}),dlog(`[LearningAgent] callLearningAPI provider=${n} oauthProvider=${s} hasToken=${!!o}`);const i={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:r.toString(),[Ut.SESSION_ID]:`${this.sessionId}-learning`,...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};o&&(i[Ut.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Ut.OAUTH_PROVIDER]=s));const a=await this.getTasteTools(),l=getConfiguredModel();dlog(`[LearningAgent] calling ${Bt.ALPHA.TASTE.LEARN} (model: ${l})`);const u={conversation:t,tools:a,model:l,threadId:this.sessionId};let d=0,m=null;for(;d<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:Bt.ALPHA.TASTE.LEARN,body:u,headers:i,signal:this.abortSignal});if(!e)throw new Error("No response received");const t=e;return dlog(`[LearningAgent] API response received: ${t.content.length} blocks`),{role:"assistant",content:t.content}}catch(e){if(m=e instanceof Error?e:new Error(String(e)),d++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status||e?.statusCode;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${m.message}`),trackError({error:sanitizeErrorForTelemetry({error:m,label:"learning_api_client_error"}),context:{component:cs.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),m;if(d>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:m,label:"learning_api_max_retries"}),context:{component:cs.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":d}}),m;const n=1e3*Math.pow(2,d);dlog(`[LearningAgent] retrying API call (${d}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw m||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return L.existsSync(r)}};Ot(),wn(),Lo(),Jr(),ao(),Kn();var Xk="deepseek/deepseek-v4-pro",Zk=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,n=Date.now();dlog("[CompactAgent] compacting",{messages:t.length,model:Xk});try{const e=await this.callCompactAPI({messages:t});return dlog("[CompactAgent] done",{model:Xk,durationMs:Date.now()-n,chars:e.summary.length,tokensIn:e.tokensUsed.input,tokensOut:e.tokensUsed.output,cached:e.tokensUsed.cached??0}),e}catch(e){throw dlog("[CompactAgent] error",{model:Xk,durationMs:Date.now()-n,error:e instanceof Error?e.message:String(e)}),e}}async callCompactAPI(e){const{messages:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced(),{token:o,oauthProvider:s}=await getOAuthCredentials({provider:n});validateOAuthToken({token:o,provider:n});const i={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(i[Ut.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Ut.OAUTH_PROVIDER]=s));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"),l={config:getEnvironmentContext(),memory:"",taste:"",skills:"",mode:"compact",params:{tools:[],system:"You compress a Command Code conversation into a handoff brief so a fresh assistant can pick up the work without rereading the original transcript.\n\nThe summary is the next assistant's only memory. Be precise. Prefer concrete artifacts (paths, function names, exact strings) over paraphrase. When code is mid-edit, include the snippet verbatim — losing it loses the work.\n\nCover these areas, in this order:\n\n**Goal**\nWhat the user is trying to accomplish across the whole conversation, with extra weight on the most recent ask. Include any constraints or success criteria the user has stated.\n\n**User turns**\nWalk through every user message that is not a tool result, in order. For each, capture the gist in one line — instructions, questions, corrections, reactions, \"no, not that\". Paraphrase is fine, but do not merge two turns into one and do not skip turns that look like noise; tone shifts and abandoned threads are signal. Quote verbatim when wording matters (e.g. precise rules the user laid down).\n\n**In-flight work**\nThe single task that was active immediately before this summary, in enough detail that the next assistant can resume without rediscovering anything. Name the file(s), the function(s), and the specific change being attempted.\n\n**Pending tasks**\nAnything the user has explicitly asked for that is not yet started or not yet finished, beyond the in-flight task. One bullet per item, in the order the user raised them. Omit work the user has since dropped or superseded. If nothing is queued, say \"None\".\n\n**Files touched**\nEvery file read or modified during the conversation. For each: path, what changed (or what was learned by reading it), and a code snippet where it helps the next assistant pick up — always for unfinished edits, and for finished edits when the snippet captures non-obvious context. Skip files that turned out to be irrelevant.\n\n**Decisions and constraints**\nDesign choices, library or pattern selections, and trade-offs that have already been settled. Include the reasoning so the next assistant doesn't relitigate them. Also capture user preferences picked up along the way (style rules, things to avoid, things to repeat).\n\n**Errors and feedback**\nFailures hit during the conversation, what fixed each one, and any course-correction the user gave. If the user told you to do something differently, capture that instruction in their words.\n\n**Resume point**\nThe exact next action to take. Only fill this in if the in-flight work has a clear continuation aligned with the user's latest ask — do not invent follow-ups, do not resurrect older threads the user has already moved on from. If the task was concluded, say so and stop. When you do fill it in, paste the user's most recent instruction word-for-word in quotes so the next assistant anchors on the actual ask instead of your paraphrase.\n\nWrite the summary directly. No preamble, no scratchpad, no wrapping tags.",messages:[{role:"user",content:`Please summarize the following conversation.\n\n${a}`}],model:Xk,max_tokens:16e3,stream:!0},threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:Bt.ALPHA.GENERATE,body:l,headers:i,stream:!0});if(!e)throw new Error("No response stream received");const t=await consumeSSEStream(e);return{summary:t.content.filter(e=>"text"===e.type).map(e=>e.text||"").join(""),tokensUsed:{input:t.usage.input_tokens,output:t.usage.output_tokens,cached:t.usage.cache_read_input_tokens??0}}}catch(e){d=e instanceof Error?e:new Error(String(e)),u++;const t=e?.status;if(t&&t>=400&&t<500)throw d;if(u>this.maxApiRetries)throw dlog("[CompactAgent] retries exhausted",{attempts:this.maxApiRetries,error:d.message}),d;dlog("[CompactAgent] retry",{attempt:u,max:this.maxApiRetries,error:d.message})}throw d||new Error("Compact API call failed")}};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={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:t.toString(),...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}},{token:r,oauthProvider:o}=await getOAuthCredentials({provider:e});return r&&(n[Ut.OAUTH_TOKEN]=`Bearer ${r}`,o&&(n[Ut.OAUTH_PROVIDER]=o)),n}function hasUserAndAssistantMessage(e){let t=!1,n=!1;for(const r of e)if(!isHiddenTranscriptMessage({message:r})&&("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}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let r="",o="";for(const e of t)if(!isHiddenTranscriptMessage({message:e})&&(r||"user"!==e.message.role||(r=extractMessageText(e.message.content).slice(0,os)),o||"assistant"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,os)),r&&o))break;if(!r||!o)return;const s=`Session description:\n<description>User: ${r}\n\n---\n\nAssistant: ${o}</description>\n\nGenerate the session title now.`,i=sn.MINIMAX_M2_5.id,a=await buildAuthHeaders(),l={config:getEnvironmentContext(),memory:"",taste:"",skills:"",mode:"title-gen",params:{tools:[],messages:[{role:"user",content:s}],model:i,system:"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. Don't reason.\n\nExample titles:\nAdd retry logic to API\nSimplify error handling flow\nClean up unused components",max_tokens:500,temperature:1,stream:!0},threadId:n.getSessionId()},u=getApiBaseUrl(),d=new jw({baseUrl:u});try{const e=await d.post({endpoint:Bt.ALPHA.GENERATE,body:l,headers:a,stream:!0}),t=await consumeSSEStream(e),r=t.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("").trim();if(!r)return void dlog("[TitleGen] empty",{model:i});await n.saveSessionTitle(r),dlog("[TitleGen] done",{model:i,title:r,tokensIn:t.usage.input_tokens,tokensOut:t.usage.output_tokens,cached:t.usage.cache_read_input_tokens??0})}catch(e){dlog("[TitleGen] error",{model:i,error:e instanceof Error?e.message:String(e)})}}async function callServerAPI(e){const t=await getConfiguredProvider(),n=await isOAuthEnforced(),{token:r,oauthProvider:o}=await getOAuthCredentials({provider:t});validateOAuthToken({token:r,provider:t});const s=await isTasteLearningEnabled(),i={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.TASTE_LEARNING]:s.toString(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:n.toString(),[Ut.SESSION_ID]:e.sessionId,...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};r&&(i[Ut.OAUTH_TOKEN]=`Bearer ${r}`,o&&(i[Ut.OAUTH_PROVIDER]=o));const a=e.permissionMode??"standard",l="bypass"===a?"auto-accept":a,u={config:e.config,memory:e.memory,taste:e.taste??null,skills:e.skills??null,permissionMode:l,params:{model:e.model,messages:e.messages,tools:e.tools,system:e.system,max_tokens:e.maxOutputTokens??64e3,stream:!0,...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{}}};dlog(`[AISDKBridge] POST ${Bt.ALPHA.GENERATE} model=${e.model} msgs=${e.messages.length} tools=${e.tools.length}`);const d=getApiBaseUrl(),m=new jw({baseUrl:d}),g=ke.getTracer(_t),h=getSessionId(),f=getSessionContext(),y=g.startSpan(`chat ${e.model}`,{attributes:{[Rt.PROVIDER_NAME]:t??"unknown",[Rt.OPERATION_NAME]:"chat",[Rt.REQUEST_MODEL]:e.model,[Rt.RESPONSE_MODEL]:e.model,...h?{[Rt.CONVERSATION_ID]:h}:{},...void 0!==e.iteration?{[Rt.STEP_NAME]:`iteration_${e.iteration}`}:{},[Rt.CAPABILITY_NAME]:e.capability??"chat","cmd.tool_count":e.tools.length,"cmd.telemetry.content_capture":isContentCaptureEnabled()}},f),w=ke.setSpan(f,y);try{const t=await Te.with(w,()=>m.post({body:u,stream:!0,endpoint:Bt.ALPHA.GENERATE,signal:e.signal,headers:i,onHeaders:e.onSystemPromptBreakdown?t=>{const n=t.get(Ut.SYSTEM_PROMPT_BREAKDOWN);if(n)try{const t=JSON.parse(n);e.onSystemPromptBreakdown(t)}catch{}}:void 0})),n=await consumeSSEStream(t,{onText:e.onTextDelta});return n.usage&&(y.setAttribute(Rt.USAGE_INPUT_TOKENS,n.usage.input_tokens),y.setAttribute(Rt.USAGE_OUTPUT_TOKENS,n.usage.output_tokens),n.usage.cache_read_input_tokens&&y.setAttribute(Rt.USAGE_CACHED_INPUT_TOKENS,n.usage.cache_read_input_tokens)),y.setStatus({code:xe.OK}),y.end(),n}catch(e){throw e instanceof Error&&y.recordException(e),y.setStatus({code:xe.ERROR,message:e instanceof Error?e.message:String(e)}),y.end(),e}}Kn(),Ot(),sS(),Lo(),Jr(),ao(),Kn(),wn(),fS(),as(),__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle"),as(),Ot(),sS(),fS(),wn(),Jr(),ao(),Kn(),Oo(),fn(),__name(callServerAPI,"callServerAPI");var eT=new Jv("ContextEngine"),tT=200;function applyHookContextToMessage(e){const t=e.meta.hookContexts;if(!t||0===Object.keys(t).length)return e.message;const n=e.message;if("tool"!==n.role)return n;const r=n.content.map(e=>{const n=t[e.toolCallId];if(!n)return e;const r=[];if(n.preToolUse&&r.push(wrapHookContextChunk({context:n.preToolUse,source:"PreToolUse",toolName:e.toolName})),n.postToolUse&&r.push(wrapHookContextChunk({context:n.postToolUse,source:"PostToolUse",toolName:e.toolName})),0===r.length)return e;if("text"!==e.output.type)return e;const o="string"==typeof e.output.value?e.output.value:"";return{...e,output:{...e.output,value:`${o}\n\n${r.join("\n\n")}`}}});return{...n,content:r}}__name(applyHookContextToMessage,"applyHookContextToMessage");var nT=class{static{__name(this,"ContextEngine")}request;messages=[];callbacks;sessionManager;abortController=null;requestInterrupted=!1;contextTokensUsed=0;systemPromptBreakdown=null;currentInteractionTokens=0;compactionCount=0;modelChangeInFlight=!1;syncQueue=Promise.resolve();lastFileContexts=[];titleGenerationInFlight=!1;healedOrphanIds=new Set;learningAgent;compactAgent;checkpointManager;hookSystem=null;constructor(e,t,n){const r=getApiBaseUrl();this.request=new jw({baseUrl:r}),this.callbacks=e,this.sessionManager=new rk(t),this.learningAgent=new Jk({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new Zk({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore(),n?.hookSystem&&(this.hookSystem=n.hookSystem)}getHookBaseParams(){return{sessionId:this.sessionManager.getSessionId(),cwd:process.cwd(),permissionMode:this.callbacks.getPermissionMode?.()||"standard"}}async firePreToolUseHook(e){return this.hookSystem?firePreToolUseHook({hookSystem:this.hookSystem,baseParams:this.getHookBaseParams(),toolBlock:e}):null}async firePostToolUseHook(e,t){return this.hookSystem?firePostToolUseHook({hookSystem:this.hookSystem,baseParams:this.getHookBaseParams(),toolBlock:e,toolResponse:t.toolResponse}):null}refreshRequest(){const e=getApiBaseUrl();this.request=new jw({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()})}async interrupt(e=!1){if(this.requestInterrupted=!0,this.abortController){this.abortController.abort(),this.abortController=null,eT.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-call"===e.type);if(n.length>0){const e=n.map(e=>({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:"Interrupted by user"}}));this.addMessageAndSync(this.createMessageWithMeta({role:"tool",content:e})),eT.debug(`Added tool-result parts for ${e.length} interrupted tool calls`)}e&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[{type:"text",text:"Interrupted by user"}]},{isAutomated:!0}))}if(e){const e=nE("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>eT.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n,r,o,s){let i=e,a=[];if(null===parseCommandTags({text:e}).commandMessage&&hasInlineSkillToken(i))try{a=await processSkillReferences(i)}catch(e){eT.error(`Skill reference processing failed: ${e}`)}let l=[];try{const t=await processFileReferences(e);if(i=t.processedContent,l=t.fileReferences,l.length>0){const e=l.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(i=`${n}\n\n${i}`);const u=nE(r??e);t&&t.length>0&&(u.metadata={...u.metadata,images:t}),l&&l.length>0&&(u.metadata={...u.metadata,fileReferences:l}),s&&(u.metadata={...u.metadata,ideHint:s}),this.callbacks.onFeedUpdate(u);const d=[];t&&t.length>0&&t.forEach(e=>{d.push({type:"image",image:`data:${e.mediaType};base64,${e.data}`})}),i.trim()&&d.push({type:"text",text:i});const m={role:"user",content:d},g=crypto.randomUUID(),h={messageId:g};this.getAutomatedMessageMeta({input:e,displayMessage:r,isAutomated:o?.isAutomated}).isAutomated&&(h.isAutomated=!0);const f=this.createMessageWithMeta(m,h);detectAndTrackFirstMessage().catch(()=>{}),this.addMessageAndSync(f),this.injectHiddenSkillMessages({hiddenMessages:o?.hiddenMessages}),a.length>0&&this.injectHiddenSkillMessages({hiddenMessages:a.map(e=>{const t=`Base directory for this skill: ${e.skillDirectory}\n\nThe content of SKILL.md is:\n${e.content}`;return{role:"user",content:tagSkillContent(e.skillName,t)}})}),this.checkpointManager.createSnapshot({messageId:g}).catch(e=>eT.error(`Failed to create checkpoint snapshot: ${e}`));const{ideHint:y,...w}=u.metadata??{},S={...u,metadata:w};this.sessionManager.saveMessages(this.messages,S).catch(e=>eT.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const E=await this.processMessages();return this.triggerTitleGeneration(),E}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.messages.filter(e=>!e.meta.isAutomated&&!this.messageContainsToolResult(e.message)).map(e=>e.message),t=this.sanitizeMessagesForAPI(e);await this.learningAgent.checkAndProcess({messages:t})}catch(e){eT.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager}).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;const t=new AbortController;this.abortController=t,this.learningAgent.setAbortSignal(t.signal);let n=!1,r=0;try{for(;;){r++;const t=startIterationSpan({iteration:r,model:getConfiguredModel(),initialMessageCount:this.messages.length});let o,s="continued";try{this.checkIfInterrupted(),n||(this.initializeInteractionTokens(),n=!0);const o=await this.callAPIWithRetry({iterationSpan:t,iterationNumber:r});this.checkIfInterrupted(),this.updateContextUsage(o),await this.checkAndCompactIfNeeded();const i=o.content.filter(e=>"tool-call"===e.type&&!e.providerExecuted),a=o.content.filter(e=>"tool-call"===e.type&&e.providerExecuted);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===i.length){const t=o.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===a.length){const t=oE(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>eT.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>eT.error(`Failed to save messages: ${e}`)),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0){let t=!1;for(const n of e){const e=nE(n.displayMessage??n.input);this.callbacks.onFeedUpdate(e);const r=this.getAutomatedMessageMeta(n);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:n.input},r)),t=!0}this.sessionManager.saveMessages(this.messages).catch(e=>eT.error(`Failed to save messages: ${e}`)),t&&this.triggerLearningAgent();continue}}s="completed";break}const l=o.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);if(l.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:l})),e.trim()){const t=oE(e);this.callbacks.onFeedUpdate(t)}const u=await this.executeToolBlocks({toolBlocks:i}),{toolResults:d,executedToolIds:m,permissionDenied:g,hookContextsByToolCallId:h,sessionStop:f}=u;if(g){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-call"===e.type?m.has(e.toolCallId):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}s="completed";break}let y=!1,w=!1;if(d.length>0){const e=Object.keys(h).length>0;this.addMessageAndSync(this.createMessageWithMeta({role:"tool",content:d},e?{hookContexts:h}:{})),y=!0}if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){const e=nE(t.displayMessage??t.input);this.callbacks.onFeedUpdate(e);const n=this.getAutomatedMessageMeta(t);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t.input},n)),y=!0,w=!0}}if(y&&this.sessionManager.saveMessages(this.messages).catch(e=>eT.error(`Failed to save messages: ${e}`)),w&&this.triggerLearningAgent(),f){s="completed";break}}catch(e){throw this.isNonRetryableError(e)&&eT.debug("Request interrupted or insufficient credits"),o=e instanceof Error?e:new Error(String(e)),s=this.classifyIterationOutcome(e),e}finally{t.end({outcome:s,error:o})}}}finally{this.abortController===t&&(this.abortController=null)}return 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){eT.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return eT.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){const e=this.messages.map(e=>applyHookContextToMessage(e));return this.sanitizeMessagesForAPI(e)}sanitizeMessagesForAPI(e){const t=[];for(const n of e){if("tool"===n.role){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-call"===t.type&&r.add(t.toolCallId);const o=n.content.filter(e=>"tool-result"!==e.type||r.has(e.toolCallId));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 this.healOrphanToolUses(t)}healOrphanToolUses(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(t.push(r),"assistant"!==r.role)continue;if(!Array.isArray(r.content))continue;const o=[];for(const e of r.content)"tool-call"===e.type&&o.push({id:e.toolCallId,name:e.toolName});if(0===o.length)continue;const s=e[n+1],i="tool"===s?.role&&Array.isArray(s.content),a=new Set;if(i)for(const e of s.content)"tool-result"===e.type&&a.add(e.toolCallId);const l=o.filter(e=>!a.has(e.id));if(0===l.length)continue;const u=l.map(e=>({type:"tool-result",toolCallId:e.id,toolName:e.name,output:{type:"error-text",value:`Tool ${e.name} did not complete`}})),d=l.filter(e=>!this.healedOrphanIds.has(e.id));for(const e of d)this.healedOrphanIds.add(e.id);d.length>0&&endSpan({span:createSpan({name:"sanitize:healed_orphan_tool_use",attributes:{"cmd.sanitize.unmatched_count":d.length,"cmd.sanitize.tool_names":d.map(e=>e.name).join(","),"cmd.sanitize.next_message_role":s?.role??"none"}}),status:"success"}),dlog(`[sanitizeMessages] healed ${l.length} orphan tool_use(s) (${d.length} new): ${l.map(e=>`${e.name}#${e.id}`).join(", ")}`),i?(t.push({...s,content:[...s.content,...u]}),n++):t.push({role:"tool",content:u})}return t}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getHookSystem(){return this.hookSystem}getContextTokensUsed(){return this.contextTokensUsed}getContextLimit(){return getContextLimit(getConfiguredModel())}async onModelChanged(e){const t=this.getContextLimit(),n=this.contextTokensUsed;if(this.modelChangeInFlight)return this.callbacks.onContextUsageUpdate?.({current:n,limit:t}),{overflowed:!1,tokensUsed:n,newLimit:t,tokensSaved:0};this.modelChangeInFlight=!0;try{if(this.callbacks.onContextUsageUpdate?.({current:n,limit:t}),void 0!==e&&t>=e)return{overflowed:!1,tokensUsed:n,newLimit:t,tokensSaved:0};if(n<=Math.floor(t*hn.TIER_3_THRESHOLD))return{overflowed:!1,tokensUsed:n,newLimit:t,tokensSaved:0};const r=this.contextTokensUsed;try{await this.summarizeAndCompact()}catch(e){eT.debug(`Failed to auto-compact after model switch: ${String(e)}`)}const o=Math.max(0,r-this.contextTokensUsed);return o>0&&this.compactionCount++,this.callbacks.onContextUsageUpdate?.({current:this.contextTokensUsed,limit:t}),{overflowed:!0,tokensUsed:n,newLimit:t,tokensSaved:o}}finally{this.modelChangeInFlight=!1}}getSystemPromptBreakdown(){return this.systemPromptBreakdown}getCompactionCount(){return this.compactionCount}isRequestInProgress(){return null!==this.abortController}async manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};eT.debug(`Manual compact: ${this.messages.length} messages`);const e=this.contextTokensUsed;await this.summarizeAndCompact();const t=Math.max(0,e-this.contextTokensUsed);return this.compactionCount++,{tokensSaved:t,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],i=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===i){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"===i){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool-call"===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"!==i&&"assistant"!==i&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,n-o);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:this.getContextLimit()}),{messagesRemoved:t-s.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}injectHiddenSkillMessages(e){const{hiddenMessages:t}=e;if(t&&0!==t.length)for(const e of t)this.addMessageAndSync(this.createMessageWithMeta(e,{isMeta:!0,messageId:crypto.randomUUID()}))}isAutomatedSlashCommandPrompt(e){const{input:t,displayMessage:n}=e;return!!n&&!!n.trim().startsWith("/")&&n.trim()!==t.trim()}getAutomatedMessageMeta(e){return e.isAutomated||this.isAutomatedSlashCommandPrompt(e)?{isAutomated:!0}:{}}messageContainsToolResult(e){if("user"!==e.role)return!1;const t=e.content;return!!Array.isArray(t)&&t.some(e=>{if("object"!=typeof e||null===e||!("type"in e))return!1;const t=e.type;return"tool_result"===t||"tool-result"===t})}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){if(!t.meta.isMeta)try{const n=Nf.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Bt.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 prepareServerCall(){const e=this.callbacks.getPermissionMode?.()||"standard",t=await getToolSchemas({mode:e}),n=await getConfiguredProvider();n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n);const r=getConfiguredModel(),o=modelSupportsReasoningEffort(r)?getReasoningEffort(r):void 0,s=this.getRawMessages(),i=getEnvironmentContext(),a=await getMemoryContent(this.lastFileContexts),l=await getTasteContent(),u=await loadAllSkillSummaries(),{names:d}=await loadDisabledSkills(),m=generateSkillsXML(0===d.size?u:{global:u.global.filter(e=>!d.has(e.name)),project:u.project.filter(e=>!d.has(e.name))});return eT.debug(`prepareServerCall (${r}, ${s.length} msgs, ${t.length} tools)`),{model:r,messages:s,tools:t,config:i,memory:a||null,taste:l||null,skills:m||null,permissionMode:e,reasoningEffort:o}}async callAPIWithRetry(e){const{iterationSpan:t,iterationNumber:n}=e;let r=null,o=0;const{model:s,messages:i,tools:a,config:l,memory:u,taste:d,skills:m,permissionMode:g,reasoningEffort:h}=await this.prepareServerCall();t?.recordPayloadHealth(computePayloadHealth(i));for(let e=0;e<10;e++)try{const r=await callServerAPI({model:s,messages:i,tools:a,config:l,memory:u,taste:d,skills:m,permissionMode:g,maxOutputTokens:64e3,sessionId:this.sessionManager.getSessionId(),iteration:n,reasoningEffort:h,signal:this.abortController?.signal,onTextDelta:__name(e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)},"onTextDelta"),onSystemPromptBreakdown:__name(e=>{this.systemPromptBreakdown=e},"onSystemPromptBreakdown"),onError:__name(e=>{eT.debug(`API stream error: ${e.message}`)},"onError")});return this.callbacks.onRetryUpdate?.(null),t?.recordAttempt({attempt:e+1,delayMsBefore:o,status:"ok"}),r}catch(n){r=n instanceof Error?n:new Error(String(n)),dlog(`[ContextEngine] API error (attempt ${e+1}/10): statusCode=${n?.statusCode} status=${n?.status} message=${n?.message} responseBody=${n?.responseBody?.substring?.(0,300)}`);const s=n?.statusCode??n?.status,i=!this.isNonRetryableError(n),a=this.classifyApiErrorLabel(n);if(t?.recordAttempt({attempt:e+1,delayMsBefore:o,status:"error",errorType:a,errorMessage:r.message,httpStatus:"number"==typeof s?s:void 0,isRetryable:i}),this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(n))throw trackError({error:sanitizeErrorForTelemetry({error:n instanceof Error?n:new Error(String(n)),label:"non_retryable_api_error"}),context:{component:cs.CONTEXT_ENGINE,heading:"Non-retryable AI SDK error",code:n?.status||n?.statusCode}}),this.formatAPIError(n);if(9===e)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:r,label:"api_max_retries_exceeded"}),context:{heading:"AI SDK max retries exceeded",component:cs.CONTEXT_ENGINE,"cmd.retry.attempts":10}}),this.formatAPIError(n);const l=Math.min(e,10),u=100*Math.pow(2,l),d=Math.max(u,1e3),m=Math.min(d,1e4);o=m,e>=2&&this.callbacks.onRetryUpdate?.(e+1),await sleep({delay:m,signal:this.abortController?.signal})}throw r||new Error("Failed to get response after retries")}classifyIterationOutcome(e){const t=e instanceof Error?e.message:"string"==typeof e?e:"",n=t.toLowerCase();return"Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")?"interrupted":this.isNonRetryableError(e)?"non_retryable_error":"max_retries_exceeded"}classifyApiErrorLabel(e){const t=e?.statusCode??e?.status,n=(e instanceof Error?e.message:"string"==typeof e?e:"").toLowerCase();return n.includes("connection error")?"connection_error":n.includes("tool result is missing")||n.includes("missing tool results")?"missing_tool_results":n.includes("rate limit")||429===t?"rate_limit":n.includes("overloaded")||529===t?"overloaded":401===t||403===t?"auth_error":"number"==typeof t&&t>=500?"server_error":"number"==typeof t&&t>=400?"client_error":e instanceof Error?e.name:"unknown_error"}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=t?.includes("PREMIUM_CREDITS_EXHAUSTED:"),i=t?.includes("MODEL_NOT_IN_PLAN:"),a="UPSTREAM_PROVIDER_UNAVAILABLE"===e?.code,l="CMD_ZDR_NO_PROVIDERS"===e?.code||"cmd_zdr_no_providers"===e?.type||"CMD_ZDR_NO_PROVIDERS"===e?.error?.code||"cmd_zdr_no_providers"===e?.error?.type,u=!1===e?.isRetryable;u&&dlog(`[ContextEngine] AI SDK isRetryable=false: status=${e?.statusCode??e?.status} message=${e?.message}`);const d=e?.status||e?.statusCode,m=e instanceof Cs||401===d||e instanceof vs||403===d,g=e?.type||e?.error?.type,h="rate_limit_error"===g||429===d||n.includes("rate limit"),f="overloaded_error"===g||529===d||n.includes("overloaded");return r||o||s||i||a||l||u||m||h||f}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.responseBody){const n=parseEmbeddedErrorJSON(e.responseBody);if(n)return{...n,status:n.status||t};try{const n=JSON.parse(e.responseBody);if(n?.error?.message)return{status:t,type:n.error.type||null,message:n.error.message}}catch{}}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,s=getSupportId(),i="unknown"!==s?`\nRequest ID: ${s}`:"",a='\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord';dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",o);const l=o?.toLowerCase().includes("insufficient credits");if(l)return new Error(`Insufficient credits\n\nUpgrade your plan or add credits: https://commandcode.ai/settings/billing${i}`);const u=o?.includes("PREMIUM_CREDITS_EXHAUSTED:");if(u)return new Error("Premium credits exhausted");const d=o?.includes("MODEL_NOT_IN_PLAN:");if(d)return new Error(`Model not in plan: ${o?.replace("MODEL_NOT_IN_PLAN:","").trim()}`);if("CMD_ZDR_NO_PROVIDERS"===e?.code||"cmd_zdr_no_providers"===e?.type||"CMD_ZDR_NO_PROVIDERS"===e?.error?.code||"cmd_zdr_no_providers"===e?.error?.type)return new Error(o||"This model has no zero-data-retention upstream. Disable CMD_ZDR or pick a different model.");const m=o?.toLowerCase().includes("oauth authentication required");if(m)return e;if(e instanceof Cs||401===(e?.status||e?.statusCode))return new Error(`Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.${a}${i}`);let g="";if(o)if(o.includes("Invalid 'Authorization' header"))g=`Error: Authentication failed. Run "cmd login" to sign in again.${a}${i}`;else{let e=o;for(;e.startsWith("Error: ");)e=e.substring(7);(e.includes("Unexpected event order")||e.includes("part")&&e.includes("not found")||e.includes("AI_")||e.includes("Invalid prompt"))&&(e="Something went wrong. Please try again or contact support if the issue persists.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>tT&&(t=t.substring(0,tT)+"..."),g=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const s=o.toLowerCase(),l="overloaded_error"===r||s.includes("overloaded"),u="rate_limit_error"===r||s.includes("rate limit");g+=l?"\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.':a,g+=i}else{const t=e?.toString?.()||"Unknown error occurred";g=t.length>tT?t.substring(0,tT)+"...":t,g+=a+i}return new Error(g)}async executeToolBlocks(e){const t=new Set;let n=!1;const r={};let o;const s=[],i=[];for(const r of e.toolBlocks){this.checkIfInterrupted();const e=crypto.randomUUID(),o=dS.includes(r.toolName),a=this.callbacks.getPermissionMode?.(),l="auto-accept"!==a&&"bypass"!==a&&mS.includes(r.toolName)?this.getToolDescription(r):Promise.resolve(null);let u=null;try{o&&this.callbacks.onPermissionRequest&&(u=await l);const t=await this.checkToolPermission(r,u);if(t.needsPermission&&!t.allowed){this.handlePermissionDenied(r,e),n=!0;break}}catch(n){const o=n instanceof Error?n.message:"Permission check failed";this.showToolError(r,o,e,u),i.push({toolBlock:r,toolResult:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:{type:"error-text",value:`Error: ${o}`}}}),t.add(r.toolCallId);continue}null===u&&(u=await l),s.push({toolBlock:r,entryId:e,description:u})}const a=[];for(const{toolBlock:e,toolResult:n}of i)a.push(n),t.add(e.toolCallId);if(s.length>0){const e=await Promise.allSettled(s.map(async({toolBlock:e,entryId:t,description:n})=>{this.checkIfInterrupted();const r="edit_file"===e.toolName?await resolveEditStartLine({filePath:e.input.filePath,oldContent:e.input.oldValue}).catch(()=>{}):void 0,o=!isAgentTool(e.toolName)&&e.toolName!==iS.GET_SELF_KNOWLEDGE,s=await this.firePreToolUseHook(e);if(s?.blocked)return o&&s.hookOutcome&&this.showToolBlockedByHook(e,t,n,{preHookLines:s.hookLines,hookOutcome:s.hookOutcome}),{toolBlock:e,toolResult:{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:s.denyReason}},hookContext:void 0,sessionStop:s.stopSession?{reason:s.sessionStopReason}:void 0};o&&this.showToolRunning(e,t,n,{preHookLines:s?.hookLines});const i=await this.executeSingleTool(e),a=await this.firePostToolUseHook(e,{toolResponse:i}),l=a?.additionalContext,u={};s?.additionalContext?.trim()&&(u.preToolUse=s.additionalContext.trim()),l?.trim()&&(u.postToolUse=l.trim());const d=Object.keys(u).length>0;o&&this.showToolSuccess(e,i,t,n,r,{preHookLines:s?.hookLines,postHookLines:a?.hookLines,hookOutcome:a?.hookOutcome??s?.hookOutcome});const m=s?.stopSession||a?.stopSession?{reason:s?.sessionStopReason??a?.sessionStopReason}:void 0;return{toolBlock:e,toolResult:{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:i}},hookContext:d?u:void 0,sessionStop:m}}));for(let n=0;n<e.length;n++){const i=e[n],{toolBlock:l,entryId:u,description:d}=s[n];if("fulfilled"===i.status)a.push(i.value.toolResult),i.value.hookContext&&(r[l.toolCallId]=i.value.hookContext),i.value.sessionStop&&!o&&(o=i.value.sessionStop),t.add(l.toolCallId);else{const e=i.reason instanceof Error?i.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(l.toolName)?t.add(l.toolCallId):(a.push({type:"tool-result",toolCallId:l.toolCallId,toolName:l.toolName,output:{type:"error-text",value:`Error: ${e}`}}),t.add(l.toolCallId),l.toolName!==iS.GET_SELF_KNOWLEDGE&&this.showToolError(l,e,u,d))}}}return{toolResults:a,executedToolIds:t,permissionDenied:n,hookContextsByToolCallId:r,sessionStop:o}}async getToolDescription(e){try{return await Promise.race([generateToolDescription(e.toolName,e.input),new Promise(e=>setTimeout(()=>e(null),5e3))])}catch(t){return eT.debug(`Failed to generate description for ${e.toolName}: ${t instanceof Error?t.message:"Unknown error"}`),this.callbacks.onToolDescriptionError&&this.callbacks.onToolDescriptionError(e.toolName,t),null}}async checkToolPermission(e,t){return dS.includes(e.toolName)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.toolName,e.input,t)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=this.callbacks.getPermissionMode?.()||"standard",n=await executeTool(e.toolName,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),o=estimateTokens(r);return this.currentInteractionTokens+=o,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=bE(e.toolName,e.input),r={..."edit_file"===e.toolName?e.input:{},permissionDenied:!0},o={...sE(e.toolName,n,r),id:t},s=pE(o,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(s)}buildToolMetadata({toolBlock:e,editStartLine:t}){if("edit_file"===e.toolName)return{...e.input,...void 0!==t?{startLine:t}:{}};if("write_file"===e.toolName){const t=e.input,n="string"==typeof t.content?t.content:"",r=n.split("\n"),o=r.length>Go?r.slice(0,Go).join("\n"):n;return{...t,content:o,totalLines:r.length}}}showToolRunning(e,t,n,r){const o=bE(e.toolName,e.input),s={...sE(e.toolName,o,{status:"running"}),id:t,...n?{description:n}:{}};r?.preHookLines?.length&&setPreHookLines(s,r.preHookLines),this.callbacks.onFeedUpdate(s)}showToolSuccess(e,t,n,r,o,s){let i=this.buildToolMetadata({toolBlock:e,editStartLine:o});if("read_file"===e.toolName){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(i={...i||{},isTasteFile:!0,tasteCategory:e.category})}}const a={...e.input,...i?.isTasteFile?{isTasteFile:i.isTasteFile}:{},...i?.tasteCategory?{tasteCategory:i.tasteCategory}:{}},l=bE(e.toolName,a),u={...sE(e.toolName,l,i),id:n,...r?{description:r}:{}},d=pE(u,t);s?.preHookLines?.length&&setPreHookLines(d,s.preHookLines),s?.postHookLines?.length&&setPostHookLines(d,s.postHookLines),s?.hookOutcome&&setHookOutcome(d,s.hookOutcome),this.callbacks.onFeedUpdate(d)}showToolBlockedByHook(e,t,n,r){const o=bE(e.toolName,e.input),s={...sE(e.toolName,o,{status:"hook-blocked"}),id:t,...n?{description:n}:{}};r.preHookLines?.length&&setPreHookLines(s,r.preHookLines),setHookOutcome(s,r.hookOutcome),this.callbacks.onFeedUpdate(s)}showToolError(e,t,n,r){const o=bE(e.toolName,e.input),s="edit_file"===e.toolName?{...e.input,permissionDenied:!0}:void 0,i={...sE(e.toolName,o,s),id:n,...r?{description:r}:{}},a=pE(i,gE(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"tool-call"===e.type&&e.providerExecuted).length)return"";let t="";const n=e.content;for(const e of n)if("text"===e.type)t+=e.text;else if("tool-call"===e.type&&e.providerExecuted){if(t.trim()){const e=oE(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:o}=uS({serverToolBlock:e,contentBlocks:n}),s=bE(e.toolName,e.input),i=sE(e.toolName,s),a=pE(i,o?gE(r):r);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=oE(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:this.getContextLimit()})}async checkAndCompactIfNeeded(){const e=this.getContextLimit(),t=Math.floor(e*hn.TIER_1_THRESHOLD),n=Math.floor(e*hn.TIER_2_THRESHOLD),r=Math.floor(e*hn.TIER_3_THRESHOLD),o=getCompactMode();try{if(this.contextTokensUsed>r){eT.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 3 threshold (${r}), 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("fast"!==o)return;if(this.contextTokensUsed>n){eT.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${n}), removing all except last ${hn.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(hn.TIER_2_KEEP_COUNT);return eT.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void this.emitAutoCompactInfo(e.tokensSaved)}if(this.contextTokensUsed>t){const e=this.countToolCalls(),n=hn.TIER_1_KEEP_COUNT;if(e>n){eT.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${t}), keeping last ${n} tool calls`);const e=await this.removeToolCallsExceptLast(n);eT.debug(`Tier 1 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),this.emitAutoCompactInfo(e.tokensSaved)}}}catch(e){eT.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){this.compactionCount++,e>0&&this.callbacks.onFeedUpdate(rE(`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-call"===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-call"===t[n].type&&r.push({id:t[n].toolCallId,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)),i=[];for(const e of this.messages){const t=e.message.role,r=e.message.content;if("tool"===t&&Array.isArray(r)){const t=r.filter(e=>"tool-result"!==e.type||!s.has(e.toolCallId)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool-call"!==e.type||!s.has(e.toolCallId)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}i.push(e)}this.messages=i,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,t-n);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:this.getContextLimit()}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return eT.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(hn.TIER_2_KEEP_COUNT);eT.debug(`Summarizing ${e.length} older messages, keeping ${t.length} recent messages`);const n=e.filter(e=>!isHiddenTranscriptMessage({message:e})).map(e=>e.message),r=await this.compactAgent.compactMessages({messages:n});eT.debug(`Summarization complete: ${r.summary.length} chars, tokensIn=${r.tokensUsed.input} tokensOut=${r.tokensUsed.output} cached=${r.tokensUsed.cached}`);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,i=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[o,...t],await this.sessionManager.saveMessages(this.messages);const a=estimateTokens(o.message),l=Math.max(0,s-i+a);this.contextTokensUsed=l,this.callbacks.onContextUsageUpdate?.({current:l,limit:this.getContextLimit()}),eT.debug(`Tier 3 summarization complete: reduced from ${s} to ~${l} tokens`)}catch(e){eT.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(hn.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=hn.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 i=o.message.content;Array.isArray(i)&&i.some(e=>"tool-result"===e.type)}n=Math.min(n,this.messages.length-3),n=Math.max(0,n);let r=0;this.messages[0]?.meta?.isSummary&&(r=1);for(let e=r;e<n;e++){const t=this.messages[e].message.content;if(Array.isArray(t)&&t.some(e=>"image"===e.type)){n=e;break}}for(;n>r&&"user"===this.messages[n].message.role;)n--;return{messagesToSummarize:this.messages.slice(r,n),messagesToKeep:this.messages.slice(n),keepStartIndex:n}}getCheckpointManager(){return this.checkpointManager}listCheckpoints(){return this.checkpointManager.listCheckpoints()}hasCheckpoints(){return this.checkpointManager.hasCheckpoints()}async restoreToCheckpoint(e){const{messageId:t,mode:n}=e;this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()});const r=this.sessionManager.getMessageIndexById({messageId:t,messages:this.messages});let 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:this.getContextLimit()})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots(),this.checkpointManager.runCleanup().catch(()=>{})}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}};Ot(),_E(),ro();var rT=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1),oT=["Invalid JSON","Failed to read","Invalid hooks structure"];function isFileLevelWarning(e){return oT.some(t=>e.startsWith(t))}__name(isFileLevelWarning,"isFileLevelWarning");var sT={unknown_event:{singular:"unknown event",plural:"unknown events"},invalid_matcher:{singular:"invalid matcher",plural:"invalid matchers"},invalid_hook:{singular:"invalid hook",plural:"invalid hooks"}},iT=["unknown_event","invalid_matcher","invalid_hook"],aT={singular:"hook config issue",plural:"hook config issues"};function categorizeHookLevelWarning(e){return e.startsWith("Unknown event")?"unknown_event":e.startsWith("Invalid matcher")?"invalid_matcher":"invalid_hook"}function pluralize(e,t){return`${e} ${1===e?t.singular:t.plural}`}function summarizeHookLevelWarnings(e){if(0===e.length)return null;const t={unknown_event:0,invalid_matcher:0,invalid_hook:0};for(const n of e)t[categorizeHookLevelWarning(n)]+=1;const n=iT.filter(e=>t[e]>0).map(e=>pluralize(t[e],sT[e])).join(", ");return`${pluralize(e.length,aT)}: ${n}.`}function buildHookStartupEntries(e){const t=[],n=[];for(const r of e)isFileLevelWarning(r)?t.push(r):n.push(r);const r=t.map(e=>({message:e,isHookWarning:!0})),o=summarizeHookLevelWarnings(n);if(o&&r.push({message:o,isHookWarning:!1}),0===r.length)return[];const s=r[r.length-1];return s.message=`${s.message} ${rT}`,r.map(e=>e.isHookWarning?rE(e.message,{isHookWarning:!0}):rE(e.message))}function createHookSystemStartupState(e){const t=createHookSystem(e),n=t.initialize().then(()=>buildHookStartupEntries(t.drainTrustWarnings())).catch(e=>[rE(`Hook system failed to initialize: ${getErrorMessage(e)}`,{isHookWarning:!0})]);return{hookSystem:t,startupEntriesPromise:n}}function bootstrapContextEngineWithHooks(e){const t=createHookSystemStartupState({projectRoot:e.projectRoot,sessionId:e.sessionId,runMode:e.runMode,permissionMode:e.permissionMode});return{contextEngine:new nT(e.callbacks,e.sessionId,{hookSystem:t.hookSystem}),startupEntriesPromise:t.startupEntriesPromise}}function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:t,description:`Terminate process on ${t}`}}function buildShellPermissionRequest(e,t){const n=e.args,r=Array.isArray(n)?n.join(" "):"string"==typeof n?n:"";return{command:"string"==typeof e.command?e.command:"",args:"string"==typeof n?n:Array.isArray(n)?n.join(" "):void 0,workingDirectory:"string"==typeof e.directory?e.directory:void 0,description:t??`Execute shell command: ${String(e.command??"")} ${r}`}}function getFileAction(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function buildFilePermissionRequest(e,t){const n="edit_file"===e?t.oldValue:void 0,r="edit_file"===e?t.newValue:void 0;return{action:getFileAction(e),filePath:String(t.filePath??t.file_path??t.path??t.absolutePath??"unknown"),description:"string"==typeof t.description?t.description:`${e} operation`,oldContent:"string"==typeof n?n:void 0,newContent:"string"==typeof r?r:void 0}}function useContextEngine({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:r,setFeed:o,setLiveEntries:s,setQueuedMessages:i,queuedMessagesRef:a,setStatus:l,pinnedStatusRef:u,setRetryAttempt:d,setInteractionTokens:m,setContextUsage:g,setCurrentProvider:h,shareInfoRef:f,permissionsService:y,permissionModeRef:w,setPendingQuestion:S,contextEngineRef:E}){const C=ee(t=>({onFeedUpdate:__name(e=>{const t=e.metadata?.status;"running"!==t?(s(t=>0===t.length?t:t.filter(t=>t.id!==e.id)),o(t=>[...t,e])):s(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]})},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...a.current];return a.current=[],i([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{m(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{g(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{h(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!y)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await y.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await y.requestShellPermission(e)).allowed}const o=buildFilePermissionRequest(e,r);return(await y.requestPermission(o,w.current)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{S({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=f.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>w.current,"getPermissionMode")}),[w,y,u,a,e,g,h,o,s,S,i,d,l,m,f]);return X(()=>{if(E.current||!r||n||t)return;let s=!1;const{contextEngine:i,startupEntriesPromise:a}=bootstrapContextEngineWithHooks({projectRoot:process.cwd(),sessionId:e,runMode:"interactive",permissionMode:w.current,callbacks:C()});a.then(e=>{s||0===e.length||o(t=>[...t,...e])}),E.current=i;const l=__name(async()=>{await(E.current?.getHookSystem()?.shutdown())},"onBeforeExit");return process.on("beforeExit",l),()=>{s=!0,process.removeListener("beforeExit",l)}},[e,n,t,r,C,E,w,o]),{createContextEngineCallbacks:C}}__name(categorizeHookLevelWarning,"categorizeHookLevelWarning"),__name(pluralize,"pluralize"),__name(summarizeHookLevelWarnings,"summarizeHookLevelWarnings"),__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(createHookSystemStartupState,"createHookSystemStartupState"),__name(bootstrapContextEngineWithHooks,"bootstrapContextEngineWithHooks"),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Ot(),Ot(),Ot(),Kn();var lT=5242880,cT=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(w.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await v.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>5e4?e.slice(0,5e4)+"...":e;this.buffer[this.buffer.length-1]!==t&&(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 v.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await v.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 v.stat(this.filePath);if(e.size<=lT)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await v.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=Math.floor(2621440),r=[];let o=0;for(let e=t.length-1;e>=0;e--){const s=Buffer.byteLength(t[e],"utf-8")+1;if(o+s>n)break;o+=s,r.unshift(t[e])}await v.writeFile(this.filePath,r.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${r.length} of ${t.length} entries (${o} bytes)`)}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 cT}__name(createHistoryManager,"createHistoryManager"),US(),Ot(),wn();var uT=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await v.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await v.access(r);const e=await v.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await v.writeFile(r,t,"utf-8")}catch{await v.writeFile(r,Db+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await v.access(n),!0}catch{return!1}}};async function copyOrFallback(e,t){if(!isClipboardAvailable())return t(`Share URL: ${e} (clipboard unavailable, copy manually)`),!1;try{const t=await import("@crosscopy/clipboard");return await t.default.setText(e),!0}catch{return t(`Share URL: ${e} (clipboard unavailable, copy manually)`),!1}}async function loadShareInfo({contextEngineRef:e,setShareInfo:t}){const n=e.current?.getSessionManager();if(n){const e=await n.loadShareInfo();e&&t({url:e.url,secret:e.secret})}}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:o,contextEngineRef:s}){if(e){if(t)return void(await copyOrFallback(t.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},3e3)));try{r("Creating share link...");const t=s.current?.getMessages()||[],i=Nf.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new jw({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:Bt.ALPHA.SHARE.CREATE,body:{sessionId:e,messages:i}});n({url:l.url,secret:l.secret});const u=s.current?.getSessionManager();u&&await u.saveShareInfo({url:l.url,secret:l.secret}),await copyOrFallback(l.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},5e3))}catch(e){r(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else r("No active session to share")}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:o,contextEngineRef:s}){if(e){if(!t)return o("NOT SHARED: Session is not currently shared"),void setTimeout(()=>o(""),5e3);try{r("Removing share link...");const i=new jw({baseUrl:getApiBaseUrl()});await i.delete({endpoint:Bt.ALPHA.SHARE.DELETE,body:{sessionId:e,secret:t.secret}});const a=s.current?.getSessionManager();a&&await a.deleteShareInfo(),o("UNSHARED: Sharing has stopped"),r(""),n(null),setTimeout(()=>{o("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;r(t),setTimeout(()=>r(""),5e3)}}else r("No active session to unshare")}function getContextEngineCallbacks(e){const{createContextEngineCallbacks:t,sessionId:n}=e;return t(n)}async function handleSelectSession({selectedSessionId:e,sessionLoadIdRef:t,contextEngineRef:n,setFeed:r,setLiveEntries:o,setSessionId:s,setShowSessionSelector:i,setSessionLoaded:a,permissionModeRef:l,setStaticKey:u,setShareInfo:d,createContextEngineCallbacks:m}){const g=crypto.randomUUID();t.current=g;try{await(n.current?.getHookSystem()?.shutdown()),r([]),o([]),n.current=null,s(e),i(!1),a(!0);const h=getContextEngineCallbacks({createContextEngineCallbacks:m,sessionId:e}),{contextEngine:f,startupEntriesPromise:y}=bootstrapContextEngineWithHooks({projectRoot:process.cwd(),sessionId:e,runMode:"interactive",permissionMode:l.current,callbacks:h});n.current=f;const[{feedEntries:w,corruptedLines:S,totalLines:E},C]=await Promise.all([f.loadSession(e),y]);if(t.current!==g)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const v=[...C];if(0===w.length&&E>0&&v.push(lE(`Session could not be loaded. ${E} lines could not be parsed.`)),0===w.length&&0===E&&v.push(rE("Session loaded but contains no messages.")),w.length>0&&(S>0&&v.push(rE(`Warning: ${S} message(s) could not be loaded.`)),v.push(...w)),t.current!==g)return;r(v),yb(),u(e=>e+1)}catch(e){if(t.current!==g)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([lE(`Failed to load session: ${n}. Starting fresh session.`)]),i(!1),a(!1),s(crypto.randomUUID())}}async function handleNewSession({contextEngineRef:e,setFeed:t,setLiveEntries:n,setSessionId:r,setShowSessionSelector:o,setSessionLoaded:s,setPermissionMode:i}){t([]),n([]),e.current=null,i("standard"),r(crypto.randomUUID()),o(!1),s(!1)}function physicalLineCount(e,t){const n=t>0?t:80,r=e.split("\n");let o=0;for(const e of r){const t=st(e);o+=0===t?1:Math.ceil(t/n)}return o}function createPhysicalLogUpdate(e,t){let n="";const r=__name(r=>{const o=`${r}\n`;if(o===n)return;const s=t.getCols(),i=n.length>0?ot.eraseLines(physicalLineCount(n,s)):"";e.write(i+o),n=o},"render");return r.clear=()=>{if(n.length>0){const r=t.getCols();e.write(ot.eraseLines(physicalLineCount(n,r)))}n=""},r.sync=e=>{n=`${e}\n`},r.done=()=>{n=""},r}Jr(),ao(),Ot(),_E(),Sb(),Ot(),wn(),Of(),sS(),fS(),qr(),__name(copyOrFallback,"copyOrFallback"),__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),Ot(),__name(getContextEngineCallbacks,"getContextEngineCallbacks"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),vb(),Ot(),wb(),Ot(),wb(),Ot(),__name(physicalLineCount,"physicalLineCount"),__name(createPhysicalLogUpdate,"createPhysicalLogUpdate");var dT=null,mT=null,pT=null,gT=!1;async function resolveInkInstance(e){try{const n=rt(import.meta.url).resolve("ink"),r=t.join(t.dirname(n),"instances.js"),o=await import(m(r).href);return o.default?.get(e)}catch{return}}function warnPatchSkipped(e){gb.custom("INK_LOG_PATCH_SKIPPED",{reason:e}),gT||(gT=!0)}function registerInkControl(e){if(dT=e.clear,mT=e.stdout,!(pT=e.instance??null))return void warnPatchSkipped("no-instance");const t=pT.options?.stdout;if(!t)return void warnPatchSkipped("no-options.stdout");if("function"!=typeof pT.log||"function"!=typeof pT.throttledLog)return void warnPatchSkipped("log-shape-unexpected");const n=createPhysicalLogUpdate(t,{getCols:__name(()=>t.columns??80,"getCols")});pT.log=n,pT.throttledLog=n,gb.custom("INK_LOG_PATCHED",{})}function hardResetForResize(){if(mT)try{mT.write(ot.clearTerminal),dT?.(),pT&&(pT.lastOutput="",pT.fullStaticOutput=""),gb.custom("HARD_RESET",{clear:null!==dT,internals:null!==pT})}catch(e){gb.custom("HARD_RESET_ERROR",{message:e?.message??String(e)})}else gb.custom("HARD_RESET_SKIPPED",{reason:"no-stdout"})}function createResizeHandler(e){let t=e.getColumns();return()=>{const n=e.getColumns();e.isLearningFeedActive()?gb.resize({from:t,to:n,handler:"use-startup",skipped:!0}):n!==t?(gb.resize({from:t,to:n,handler:"use-startup"}),t=n,hardResetForResize(),e.bumpStaticKey()):gb.custom("RESIZE_NOOP",{width:n})}}async function submitInitialPrompt({initialPrompt:e,onCommand:t,submitAsUserMessage:n}){const r=e.trim();r.startsWith("/")&&t&&"handled"===(await t(r)).status||await n()}function useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:o,stdout:s,feedState:i,sessionState:a,statusState:l,authState:u,onboarding:d,uiOverlays:m,permissionState:g,contextEngineRef:h,isSubmittingRef:f,initialPromptSubmittedRef:y,historyManagerRef:w,executeBash:S,createContextEngineCallbacks:E,setInput:C,onCommand:v}){const k=ee(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningEnabled(e),e&&await uT.initializeProject()}catch{}},[l.setTasteLearningEnabled]),T=ee(async()=>{const e=await getConfiguredProvider();u.setCurrentProvider(e);const t=await isOAuthEnforced();u.setIsOAuthMode(t)},[u.setCurrentProvider,u.setIsOAuthMode]),_=ee(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),x=ee(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:a.sessionLoadIdRef,contextEngineRef:h,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,setSessionId:a.setSessionId,setShowSessionSelector:m.setShowSessionSelector,setSessionLoaded:a.setSessionLoaded,permissionModeRef:g.permissionModeRef,setStaticKey:m.setStaticKey,setShareInfo:l.setShareInfo,createContextEngineCallbacks:E})},[a,i,m,g,l,h,E]),A=ee(async()=>{if(n){const e=await rk.listSessions();return void(e.length>0&&x(e[0].id))}t?x(t):e&&m.setShowSessionSelector(!0)},[n,t,e,x,m]);X(()=>{(async()=>{await rk.isProjectInitialized()?(d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await A()):r?(await rk.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await A()):isDirectoryEmpty()?(await rk.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_()):(d.setShowTrustPrompt(!0),d.setCheckingProject(!1))})()},[e,n,r]),X(()=>{if(!d.projectTrusted)return;const e=createHistoryManager();return w.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted]);const P=J(m.showLearningFeed);P.current=m.showLearningFeed,X(()=>{if(!s)return;const e=createResizeHandler({getColumns:__name(()=>s.columns??0,"getColumns"),isLearningFeedActive:__name(()=>P.current,"isLearningFeedActive"),bumpStaticKey:__name(()=>m.setStaticKey(e=>e+1),"bumpStaticKey")});return s.prependListener("resize",e),()=>{s.off("resize",e)}},[s]),X(()=>{o&&d.projectTrusted&&!d.checkingProject&&h.current&&!m.showSessionSelector&&!y.current&&(y.current=!0,submitInitialPrompt({initialPrompt:o,onCommand:v,submitAsUserMessage:__name(()=>handleSubmit({role:"user",input:o,feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:u.currentModel,premiumCreditsExhausted:u.premiumCreditsExhausted,setPremiumCreditsExhausted:u.setPremiumCreditsExhausted,setCurrentModel:u.setCurrentModel,contextEngineRef:h,isSubmittingRef:f,setInput:C,setStaticKey:m.setStaticKey,executeBash:S}),"submitAsUserMessage")}))},[o,d.projectTrusted,d.checkingProject,m.showSessionSelector,v]);const I=J(null);I.current={feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:u.currentModel,premiumCreditsExhausted:u.premiumCreditsExhausted,setPremiumCreditsExhausted:u.setPremiumCreditsExhausted,setCurrentModel:u.setCurrentModel,contextEngineRef:h,isSubmittingRef:f,setInput:C,setStaticKey:m.setStaticKey,executeBash:S,role:"",input:""};const N=ee(async({role:e,input:t,images:n,ideContext:r,ideHint:o,displayMessage:s,isAutomated:i})=>(m.setShowTasteSkipBanner(!1),handleSubmit({...I.current,role:e,input:t,images:n,ideContext:r,ideHint:o,displayMessage:s,isAutomated:i})),[]);return{loadTasteStatus:k,loadCurrentProvider:T,initializeMcpInBackground:_,onSubmit:N}}__name(resolveInkInstance,"resolveInkInstance"),__name(warnPatchSkipped,"warnPatchSkipped"),__name(registerInkControl,"registerInkControl"),__name(hardResetForResize,"hardResetForResize"),__name(createResizeHandler,"createResizeHandler"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ot(),Wn(),_E(),Hn(),Ot(),wn(),Kn(),Ot();var hT={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return hT[e]||e}function getProjectDirName2(e){return e.replace(/\//g,"-")}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName2,"getProjectDirName"),Ot(),Kn();var fT=e.join(w.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=H(e,{encoding:"utf8"}),n=it.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 v.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await v.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await v.stat(o)).isDirectory())continue;const i=await v.readdir(o);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(o,t);if(!(await v.stat(i)).isDirectory())continue;const a=await v.readdir(i);for(const o of a){if(!/^\d{2}$/.test(o))continue;const a=e.join(i,o);if(!(await v.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const l=(await v.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(a,t));r.push(...l)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const i=e.slice(s,s+n),a=await Promise.all(i.map(t));for(const e of a)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 i=await findAllSessionFiles(fT,n);if(0===i.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${i.length} session files to scan`),n?.({phase:"reading",totalFiles:i.length,processedFiles:0,matchedSessions:0});let a=0;const l=await processFilesInBatches(i,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await v.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)=>{a=s.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:a})});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:i.length,processedFiles:i.length,matchedSessions:u.length}),u.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await v.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}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),Ot(),Kn();var yT=e.join(w.homedir(),".cursor","projects");function getCursorProjectDirNames(e){const t=e.replace(/[/\\:]/g,"-"),n=t.replace(/^-+/,"");return[...new Set([n,t])].filter(Boolean)}async function findAgentTranscriptsDir(t){try{await v.access(yT)}catch{return dlog("[Cursor] projects directory not found"),null}const n=getCursorProjectDirNames(t);dlog(`[Cursor] looking for project dirs: ${n.join(", ")}`);try{const t=await v.readdir(yT);for(const r of n){if(!t.includes(r))continue;const n=e.join(yT,r,"agent-transcripts");try{if((await v.stat(n)).isDirectory())return dlog(`[Cursor] found agent-transcripts at: ${n}`),n}catch{}}}catch(e){dlog("[Cursor] error scanning projects",e)}return null}async function findCursorSessions(t,n=0){const r=t||process.cwd(),o=[];dlog(`[Cursor] scanning for project: ${r}`);const s=await findAgentTranscriptsDir(r);if(!s)return dlog("[Cursor] no agent-transcripts found"),[];try{const t=await v.readdir(s);for(const n of t){const t=e.join(s,n);try{if(!(await v.stat(t)).isDirectory())continue;const r=e.join(t,`${n}.jsonl`);try{const e=await v.stat(r);o.push({id:n,filePath:r,createdAt:e.birthtime,lastModified:e.mtime,messageCount:0,agent:"cursor"})}catch{}}catch{}}}catch(e){dlog("[Cursor] error reading agent-transcripts",e)}const i=o.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime()),a=n>0?i.slice(0,n):i;return dlog(`[Cursor] matched ${a.length} sessions for project`),a}async function findCursorSessionIds(e){return(await findCursorSessions(e)).map(e=>e.id)}async function extractCursorPrompts(e){const t=[];try{const n=(await v.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"!==n.role)continue;const r=n.message?.content;if(!Array.isArray(r))continue;for(const e of r)if("text"===e.type&&"string"==typeof e.text){const n=e.text.trim().replace(/^<user_query>\n?/,"").replace(/\n?<\/user_query>$/,"").trim();n&&t.push(n)}}catch{continue}t.length>0&&dlog(`[Cursor] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Cursor] 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;if(e?.newTasteLearningsBannerDismissedForever)return dlog("[Onboarding] dismissed forever for this project, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[]};const t=e?.learnedSessions||{},n=e?.skippedSessions||{},r={};for(const e of new Set([...Object.keys(t),...Object.keys(n)]))r[e]=[...t[e]||[],...n[e]||[]];const o=await findNewSessions(r),s=o["claude-code"]?.length||0,i=s+(o.codex?.length||0)+(o.cursor?.length||0);return i>0?(dlog(`[Onboarding] found ${i} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:i,hasTasteContent:!0,agentSessions:buildAgentSessionsList(o)}):(isOnboardingDone(e)?dlog(`[Onboarding] ${e?.skipped?"user skipped":"already completed"}, no new sessions`):dlog("[Onboarding] no sessions to learn from, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:isOnboardingDone(e),agentSessions:[]})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[]}}}async function getSessionFilesFromDir(e){try{return(await v.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||[],s=t.cursor||[];try{const t=e.join(w.homedir(),".claude","projects");await v.access(t);const o=getProjectDirName2(process.cwd()),s=(await v.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await v.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")}try{const e=await findCursorSessionIds();e.length>0&&(n.cursor=e.filter(e=>!s.includes(e)));dlog(`[Sessions] cursor: ${n.cursor?.length||0} new, ${s.length} learned`)}catch{dlog("[Sessions] cursor sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];if(n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.skippedSessions?.[e]){const r=new Set(t);n.tasteOnboarding.skippedSessions[e]=n.tasteOnboarding.skippedSessions[e].filter(e=>!r.has(e)),0===n.tasteOnboarding.skippedSessions[e].length&&delete n.tasteOnboarding.skippedSessions[e]}n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0;try{const t=e.tasteOnboarding.learnedSessions||{},n=await findNewSessions(t);e.tasteOnboarding.skippedSessions||(e.tasteOnboarding.skippedSessions={});for(const[t,r]of Object.entries(n))if(r.length>0){const n=e.tasteOnboarding.skippedSessions[t]||[];e.tasteOnboarding.skippedSessions[t]=Array.from(new Set([...n,...r]))}}catch{dlog("[Onboarding] failed to record skipped sessions, skip flag still set")}await saveProjectSettings(e)}async function dismissOnboardingForeverForProject(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.newTasteLearningsBannerDismissedForever=!0,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 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")}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:o,onboarding:s,uiOverlays:i,skipOnboarding:a,contextEngineRef:l,sessionTitleHolder:u}){X(()=>{if(!n.shouldExit)return;r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current);const t=l.current?.getSessionManager();u&&t&&(u.loadTitle=()=>t.loadUserRenamedTitle());try{e()}catch{process.exit(0)}},[n.shouldExit,e]),X(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current)},[]),X(()=>{(async()=>{if("anthropic"===o.currentProvider&&o.isOAuthMode)try{await On.getValidAccessToken()||r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}catch{r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[o.currentProvider,o.isOAuthMode]),X(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(wE())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),X(()=>{a||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,a]),X(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=cE();s.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!s.showTasteOnboarding&&s.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==s.tasteOnboardingEntryId)),s.setTasteOnboardingEntryId(null))},[s.showTasteOnboarding,s.tasteOnboardingEntryId])}__name(getCursorProjectDirNames,"getCursorProjectDirNames"),__name(findAgentTranscriptsDir,"findAgentTranscriptsDir"),__name(findCursorSessions,"findCursorSessions"),__name(findCursorSessionIds,"findCursorSessionIds"),__name(extractCursorPrompts,"extractCursorPrompts"),__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(dismissOnboardingForeverForProject,"dismissOnboardingForeverForProject"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),__name(useLifecycle,"useLifecycle"),Ot(),_E(),Ot(),Bn(),ao(),Sb(),wn(),Ot();var wT="└",ST="│",ET=" ",bT=`${ET}TASTE${ET}`;function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:o,showMcpManager:s,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showUsageOverlay:u,showAddDirModal:d,authComponentInfo:m,setShowLearningFeed:g,setShowModelSelector:h,setStaticKey:f,showTasteSkipBanner:y,setShowTasteSkipBanner:w,transcriptMode:S,setTranscriptMode:E,isCmdCodeBusy:C,liveEntries:v,queuedMessagesRef:k,setInput:T,setQueuedMessages:_,setFeed:x,setLiveEntries:A,setIsCmdCodeBusy:P,setRetryAttempt:I,setStatus:N,pendingExitKey:R,setPendingExitKey:M,pendingExitKeyRef:L,lastExitKeyTimeRef:$,exitConfirmationTimeoutRef:D,resetPendingExitKey:O,pendingPermission:F,setPendingPermission:q,pendingQuestion:j,setPendingQuestion:U,setShouldExit:B,contextEngineRef:z,handleToggleAutoAccept:H,handleDoubleEscapeEmpty:W,respondToPrompt:G,createErrorEntry:V}){const Q=__name(()=>{if(!z.current)return;z.current.interrupt(!0);const e=v.length>0;if(P(!1),I(null),A([]),N("Interrupted by user"),!e){const e=V("Interrupted by user");x(t=>[...t,e])}if(k.current.length>0){const e=k.current.map(e=>e.displayMessage??e.input).join("\n");T(t=>t?e+"\n"+t:e),_([]),k.current=[]}},"handleInterrupt");se((v,k)=>{if(k.shift&&k.tab||"[Z"===v)H();else if(y&&k.escape)w(!1);else if(e||t||n||r||o||s||m||i||a||l||u||d)R&&O();else{if(""===v||k.ctrl&&"c"===v){if(C&&z.current)return void Q();const e=Date.now(),t=e-$.current;return $.current=e,"ctrl-c"===L.current&&t<2e3?(D.current&&(clearTimeout(D.current),D.current=null),void B(!0)):(T(()=>""),L.current="ctrl-c",M("ctrl-c"),D.current&&clearTimeout(D.current),void(D.current=setTimeout(()=>{L.current=null,M(null),D.current=null},2e3)))}if(k.ctrl&&"t"===v)return yb(),g(!i),void f(e=>e+1);if(getIsExpandToolShortcut(k,v))return yb(),E("off"===S?"limited":"off"),void f(e=>e+1);if(k.ctrl&&"e"===v&&"off"!==S)return yb(),E("limited"===S?"full":"limited"),void f(e=>e+1);if(k.meta&&"p"===v||isAltP(v))h(!0);else if(k.escape){if(j)return j.reject(new Error("Question cancelled by user")),U(null),void N("Question cancelled");if(F)return G({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),F.resolve(!1),q(null),void N("Permission denied");C&&z.current&&Q()}}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:o,pendingOps:s,permissionState:i,statusState:a,authState:l,contextEngineRef:u,loadTasteStatus:d,loadCurrentProvider:m,setInput:g}){const h=ee(()=>{i.setPermissionMode(e=>{const t=i.dangerouslySkipPermissions;let n="standard";if("standard"===e?n="auto-accept":"auto-accept"===e?n="plan":"plan"===e&&t&&(n="bypass"),("auto-accept"===n||"bypass"===n)&&s.pendingPermission){const e={label:"Yes",value:"yes",description:"Allow this action",scope:void 0};i.respondToPrompt(e),s.pendingPermission.resolve(!0),s.setPendingPermission(null)}return"plan"===n&&s.pendingPermission&&(s.pendingPermission.resolve(!1),s.setPendingPermission(null)),n})},[i.setPermissionMode,i.respondToPrompt,i.dangerouslySkipPermissions,s.pendingPermission,s.setPendingPermission]),f=ee(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=u.current?.hasCheckpoints()??!1;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector]),y=ee(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),w=ee(async()=>{try{if(await rk.initializeProject(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void o.setShouldExit(!0);n.setProjectTrusted(!0),d(),m()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),o.setShouldExit(!0)}},[e,n,o,d,m]),S=ee(()=>{o.setShouldExit(!0)},[o.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showLearningFeed:r.showLearningFeed,showRewindSelector:r.showRewindSelector,showLoginOverlay:r.showLoginOverlay,showUsageOverlay:r.showUsageOverlay,showAddDirModal:r.showAddDirModal,authComponentInfo:l.authComponentInfo,setShowLearningFeed:r.setShowLearningFeed,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,showTasteSkipBanner:r.showTasteSkipBanner,setShowTasteSkipBanner:r.setShowTasteSkipBanner,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveEntries:t.liveEntries,queuedMessagesRef:t.queuedMessagesRef,setInput:g,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:o.pendingExitKey,setPendingExitKey:o.setPendingExitKey,pendingExitKeyRef:o.pendingExitKeyRef,lastExitKeyTimeRef:o.lastExitKeyTimeRef,exitConfirmationTimeoutRef:o.exitConfirmationTimeoutRef,resetPendingExitKey:o.resetPendingExitKey,pendingPermission:s.pendingPermission,setPendingPermission:s.setPendingPermission,pendingQuestion:s.pendingQuestion,setPendingQuestion:s.setPendingQuestion,setShouldExit:o.setShouldExit,contextEngineRef:u,handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,respondToPrompt:i.respondToPrompt,createErrorEntry:lE}),{handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,handleTasteOnboardingComplete:y,handleTrust:w,handleNoTrust:S}}function lastResponseHasComments(e){const t=e[e.length-1];if(!t||"assistant"!==t.message.role)return!1;const{content:n}=t.message;if("string"==typeof n)return n.includes("## Review Comments")||n.includes("## PR Comments");const r=n.filter(e=>"text"===e.type).map(e=>e.text).join("");return r.includes("## Review Comments")||r.includes("## PR Comments")}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 i=t[e];'"'!==i&&"'"!==i||o?i===s&&o?(o=!1,s=""):" "!==i||o?r+=i:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=i)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const 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(S.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if($.existsSync(n))try{const s=$.readdirSync(n,{withFileTypes:!0});for(const i of s){const s=t.join(n,i.name);if(i.isDirectory())loadCommandsFromDirectory(s,r,o?`${o}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".md")){const n=t.basename(i.name,".md"),a=$.readFileSync(s,"utf-8").trim();e.push({name:n,source:r,content:a,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}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ot(),Ot(),wn(),Ot(),__name(lastResponseHasComments,"lastResponseHasComments"),_E(),Sb(),Ot(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),Ot(),wn(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),Ot(),Ot(),Ot(),wn(),Kn(),lo(),Co(),Ot(),wn();var CT=t.join(S.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(CT);$.existsSync(e)||$.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!$.existsSync(CT))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=$.readFileSync(CT,"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(),$.writeFileSync(CT,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"),WE(),lo();var vT=lt(Ee),kT=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!process.env.COMMANDCODE_SKIP_UPDATES||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=Se("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1"}});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return kT.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(ct.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&ct.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&ct.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 vT(`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;const n=await checkForUpdateAvailable(),r=n?.latestVersion??t.targetVersion;if(!ct.gt(r,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${r}`);const o=Re(`Updating ${e} → ${r}`).start(),s=await executeUpdate(r);if(clearPendingUpdate(),!s)return o.fail("Update failed"),void console.log("Run `cmd update` to try again.");o.succeed(`Updated to v${r}`),trackLifecycleEvent({eventType:"cli_updated",metadata:{fromVersion:e,toVersion:r}}).catch(()=>{})}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 Se("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 TT=new Set(["OPEN","MERGED","CLOSED"]),_T=null;function getCachedPRInfo(e){if(_T&&_T.branch===e){if(!(Date.now()-_T.timestamp>3e5))return _T.result;_T=null}}function setPRCache(e,t){_T={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((o,s)=>{ve(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&&TT.has(t.state)?{number:t.number,title:t.title||"",url:t.url,state:t.state}:null}catch{return null}}function getCachedPR(e){return e?getCachedPRInfo(e)??null:null}__name(getCachedPRInfo,"getCachedPRInfo"),__name(setPRCache,"setPRCache"),__name(execFileAsync,"execFileAsync"),__name(parsePRResponse,"parsePRResponse"),__name(getCachedPR,"getCachedPR");var xT=__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 null}},"detectPR");function decompress(e,t,n){if(0===e)return n;if(8===e)return ut(n);throw new Error(`Unsupported compression method ${e} for ${t}`)}function readZipEntries(e){const t=Math.max(0,e.length-65557);let n=-1;for(let r=e.length-22;r>=t;r--)if(101010256===e.readUInt32LE(r)){n=r;break}if(n<0)throw new Error("Not a ZIP archive (no EOCD)");const r=e.readUInt32LE(n+12),o=e.readUInt32LE(n+16),s=o+r,i=[];let a=o;for(;a<s&&33639248===e.readUInt32LE(a);){const t=e.readUInt16LE(a+10),n=e.readUInt32LE(a+20),r=e.readUInt16LE(a+28),o=e.readUInt16LE(a+30),s=e.readUInt16LE(a+32),l=e.readUInt32LE(a+42),u=e.toString("utf8",a+46,a+46+r);if(a+=46+r+o+s,u.endsWith("/"))continue;const d=l+30+e.readUInt16LE(l+26)+e.readUInt16LE(l+28),m=e.subarray(d,d+n);i.push({name:u,data:decompress(t,u,m)})}return i}function parseVsixOnce(e){const t=readZipEntries($.readFileSync(e));return{entries:t,meta:readVsixPackageJson(t)}}function readVsixPackageJson(e){const t=e.find(e=>"extension/package.json"===e.name);if(!t)throw new Error("VSIX missing extension/package.json");const n=JSON.parse(t.data.toString("utf8")),r="string"==typeof n.publisher?n.publisher:"",o="string"==typeof n.name?n.name:"",s="string"==typeof n.version?n.version:"";if(!r||!o||!s)throw new Error("VSIX package.json missing publisher/name/version");return{publisher:r,name:o,version:s}}function extractExtensionInto(e,n){const r=t.resolve(n);for(const o of e){if(!o.name.startsWith("extension/"))continue;const e=o.name.slice(10);if(!e)continue;const s=t.resolve(n,e);if(s!==r&&!s.startsWith(r+t.sep))throw new Error(`Refusing to extract entry outside destDir: ${o.name}`);$.mkdirSync(t.dirname(s),{recursive:!0}),$.writeFileSync(s,o.data)}}Ot(),Kn(),Jr(),Ot(),Kn(),Ot(),__name(decompress,"decompress"),__name(readZipEntries,"readZipEntries"),__name(parseVsixOnce,"parseVsixOnce"),__name(readVsixPackageJson,"readVsixPackageJson"),__name(extractExtensionInto,"extractExtensionInto");var AT={code:"Visual Studio Code",cursor:"Cursor",windsurf:"Windsurf"},PT={code:".vscode",cursor:".cursor",windsurf:".windsurf"},IT=["cursor","code","windsurf"];function getVsixPath(){try{const e=t.dirname(d(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return $.existsSync(n)?n:null}catch{return null}}function getIDEExtensionsDir(e){return t.join(S.homedir(),PT[e],"extensions")}__name(getVsixPath,"getVsixPath"),__name(getIDEExtensionsDir,"getIDEExtensionsDir");var NT={code:"Visual Studio Code.app",cursor:"Cursor.app",windsurf:"Windsurf.app"};function getMacAppBundle(e){if("darwin"!==process.platform)return null;const n=[t.join("/Applications",NT[e]),t.join(S.homedir(),"Applications",NT[e])];for(const e of n)try{if($.existsSync(e))return e}catch{}return null}function getInstalledIDEs(){return IT.filter(e=>{if("darwin"===process.platform)return null!==getMacAppBundle(e);try{return $.existsSync(t.join(S.homedir(),PT[e]))}catch{return!1}})}function formatInstallError(e,t){const n=AT[t],r=e??{},o="string"==typeof r.code?r.code:"",s="string"==typeof r.message?r.message:String(e);return"EACCES"===o||"EPERM"===o?`${n}: permission denied writing to ${getIDEExtensionsDir(t)}. Check directory ownership/permissions.`:"ENOSPC"===o?`${n}: not enough disk space to extract the extension.`:"EROFS"===o?`${n}: ${getIDEExtensionsDir(t)} is on a read-only filesystem.`:"EBUSY"===o?`${n}: extensions directory is locked by another process. Close ${n} and retry.`:"ENOENT"===o?`${n}: required path not found (${s}).`:s.includes("Not a ZIP archive")||s.includes("Unsupported compression")?`${n}: bundled VSIX appears corrupt (${s}). Reinstall Command Code.`:`${n}: ${s}`}function verifyOnDisk(e,n){try{const r=getIDEExtensionsDir(e),o=`${n.publisher}.${n.name}-${n.version}`,s=t.join(r,o,"package.json");if(!$.existsSync(s))return!1;JSON.parse($.readFileSync(s,"utf-8"));const i=t.join(r,"extensions.json");if(!$.existsSync(i))return!1;const a=JSON.parse($.readFileSync(i,"utf-8"));if(!Array.isArray(a))return!1;const l=`${n.publisher}.${n.name}`;return a.some(e=>{const t=e;return"string"==typeof t?.identifier?.id&&t.identifier.id===l&&t.version===n.version})}catch{return!1}}function buildManifestEntry(e,n,r){const o=t.join(e,n),s=m(o).href,i=o.split(t.sep).join("/");return{identifier:{id:`${r.publisher}.${r.name}`},version:r.version,location:{$mid:1,fsPath:o,external:s,path:i.startsWith("/")?i:"/"+i,scheme:"file"},relativeLocation:n,metadata:{installedTimestamp:Date.now(),source:"vsix"}}}function upsertManifestEntry(e,n){const r=t.join(e,"extensions.json");let o=[];try{if($.existsSync(r)){const e=$.readFileSync(r,"utf-8"),t=JSON.parse(e);Array.isArray(t)&&(o=t)}}catch(e){dlog(`[IDE] extensions.json unreadable, rewriting: ${e instanceof Error?e.message:String(e)}`)}o=o.filter(e=>e?.identifier?.id!==n.identifier.id),o.push(n);const s=`${r}.tmp.${process.pid}`;$.writeFileSync(s,JSON.stringify(o,null,"\t")),$.renameSync(s,r)}function directInstallExtension(e,n,r){try{const{entries:o,meta:s}=r??parseVsixOnce(n);if(verifyOnDisk(e,s))return dlog(`[IDE] direct-install ${e}: fast-path skip (${s.publisher}.${s.name}@${s.version})`),{ide:e,status:"already_installed"};const i=getIDEExtensionsDir(e);$.mkdirSync(i,{recursive:!0});const a=`${s.publisher}.${s.name}-${s.version}`,l=t.join(i,a),u=$.existsSync(t.join(l,"package.json"));if(!u){const e=t.join(i,`.commandcode-install-${process.pid}-${Date.now()}`);$.rmSync(e,{recursive:!0,force:!0}),$.mkdirSync(e,{recursive:!0});try{extractExtensionInto(o,e),$.rmSync(l,{recursive:!0,force:!0}),$.renameSync(e,l)}catch(t){throw $.rmSync(e,{recursive:!0,force:!0}),t}}if(upsertManifestEntry(i,buildManifestEntry(i,a,s)),!verifyOnDisk(e,s)){const t="post-install verification failed (extension folder or manifest entry missing)";return dlog(`[IDE] direct-install ${e} verification failed`),{ide:e,status:"failed",error:`${AT[e]}: ${t}`}}return dlog(`[IDE] direct-install ${e}: ${u?"already_installed":"installed"} (${s.publisher}.${s.name}@${s.version})`),{ide:e,status:u?"already_installed":"installed"}}catch(t){const n=formatInstallError(t,e);return dlog(`[IDE] direct-install ${e} failed: ${t instanceof Error?t.message:String(t)}`),{ide:e,status:"failed",error:n}}}function installToAllIDEs(e,t={}){const n=new Set(getInstalledIDEs());t.alwaysInclude&&n.add(t.alwaysInclude);const r=[...n];if(0===r.length)return[];let o;try{o=parseVsixOnce(e)}catch(e){return dlog(`[IDE] VSIX parse failed: ${e instanceof Error?e.message:String(e)}`),r.map(t=>({ide:t,status:"failed",error:formatInstallError(e,t)}))}return r.map(t=>directInstallExtension(t,e,o))}function getStatusHeadline(e,t){return"connected"===e?{prefix:"Connected to ",ide:t,suffix:""}:"installed"===e?{prefix:"IDE extension installed in ",ide:t,suffix:""}:"up_to_date"===e?{prefix:"IDE extension up to date in ",ide:t,suffix:""}:"needs_reload"===e?{prefix:"IDE extension installed — reload ",ide:t,suffix:"'s window to activate"}:"failed"===e?t?{prefix:"",ide:t,suffix:" extension install failed"}:{prefix:"Extension install failed",ide:null,suffix:""}:{prefix:"No supported IDE detected",ide:null,suffix:""}}__name(getMacAppBundle,"getMacAppBundle"),__name(getInstalledIDEs,"getInstalledIDEs"),__name(formatInstallError,"formatInstallError"),__name(verifyOnDisk,"verifyOnDisk"),__name(buildManifestEntry,"buildManifestEntry"),__name(upsertManifestEntry,"upsertManifestEntry"),__name(directInstallExtension,"directInstallExtension"),__name(installToAllIDEs,"installToAllIDEs"),Ot(),__name(getStatusHeadline,"getStatusHeadline");var RT={connected:ce.green("✔"),installed:ce.green("✔"),up_to_date:ce.green("✔"),needs_reload:ce.yellow("◌"),failed:ce.red("✖"),not_in_ide:ce.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${RT[e.status]} ${o}`,...(e.details??[]).map(e=>ce.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult");var MT=AT;async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}async function ensureExtensionInstalled(){if(process.env.CI)return;const e=Cv();if(!e)return;if(!await isAutoInstallEnabled())return;const t=getVsixPath();if(t)try{const n=installToAllIDEs(t,{alwaysInclude:e});for(const e of n)"failed"===e.status&&dlog(`[IDE] auto-install failed for ${e.ide}: ${e.error??"unknown"}`)}catch(e){dlog(`[IDE] auto-install threw: ${e instanceof Error?e.message:String(e)}`)}else dlog("[IDE] auto-install skipped: VSIX bundle missing")}__name(isAutoInstallEnabled,"isAutoInstallEnabled"),__name(ensureExtensionInstalled,"ensureExtensionInstalled");var LT="Select code in your IDE and it's automatically included in your prompt: no copy-paste needed.";async function runIDESetup(){const e=getVsixPath();if(!e)return{status:"failed",ide:null,details:["VSIX bundle missing from this build.","Reinstall Command Code or send feedback with /feedback"]};const t=Cv(),n=installToAllIDEs(e,{alwaysInclude:t??void 0});if(0===n.length)return{status:"not_in_ide",ide:null,details:["Install Visual Studio Code, Cursor, or Windsurf, then run /ide again."]};const r=n.filter(e=>"failed"!==e.status),o=n.filter(e=>"failed"===e.status);if(0===r.length)return{status:"failed",ide:o.map(e=>AT[e.ide]).join(", "),details:[...o.map(e=>e.error??`${AT[e.ide]}: unknown error`),"","Run /ide to retry the installation. Report the issue with /feedback including the error messages above."]};const s=r.map(e=>AT[e.ide]).join(", "),i=r.filter(e=>"installed"===e.status),a=r.filter(e=>"already_installed"===e.status),l=i.map(e=>AT[e.ide]).join(", "),u=a.map(e=>AT[e.ide]).join(", "),d=o.map(e=>`Note: ${e.error??`install failed for ${AT[e.ide]}`}`);if(t){const e=o.filter(e=>e.ide===t).map(e=>`Note: ${e.error??`install failed for ${AT[e.ide]}`}`),n=new Rv,r=await n.connect(500);n.disconnect();const s=MT[t]||t;if(r)return{status:"connected",ide:s,details:[LT,...e.length>0?["",...e]:[]]};const i="darwin"===process.platform?"Cmd+Shift+P":"Ctrl+Shift+P";return{status:"needs_reload",ide:s,details:[LT,"",`${i} → Developer: Reload Window in ${s}, then re-run /ide to verify.`,...e.length>0?["",...e]:[]]}}const m="Run /ide from inside the IDE's terminal to verify the connection.";if(0===i.length)return{status:"up_to_date",ide:s,details:[LT,"",m,...d.length>0?["",...d]:[]]};const g=a.length>0?`Already up to date in ${u}.`:null;return{status:"installed",ide:l,details:[LT,"",m,...g?[g]:[],...d.length>0?["",...d]:[]]}}__name(runIDESetup,"runIDESetup"),ro(),io(),Ot();var $T='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets.';function buildReviewPrompt({prNumber:e,autoDetected:t=!1}){const n=e.trim();return n?`${$T}\n\nReview PR number: ${n}${t?"\n(Note: PR number auto-detected from current branch.)":""}`:`${$T}\n\nReview PR number: `}__name(buildReviewPrompt,"buildReviewPrompt"),Ot(),Ot(),ao(),Rr();var DT=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),OT=__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"),FT=__name(({icon:e,label:t,children:n})=>Q.createElement(ne,null,Q.createElement(ne,{color:ar.CYAN},e," "),Q.createElement(ne,{color:ar.DIM},t.padEnd(12)),n),"Row"),qT=__name(({title:e})=>Q.createElement(ne,null,Q.createElement(ne,{color:ar.GRAY},"───"),Q.createElement(ne,{color:ar.WHITE}," ",e," "),Q.createElement(ne,{color:ar.GRAY},"─".repeat(35))),"Header"),jT=__name(({title:e,marginTop:t=0,children:n})=>Q.createElement(te,{flexDirection:"column",marginTop:t},Q.createElement(qT,{title:e}),Q.createElement(te,{flexDirection:"column",paddingY:1},n)),"Section"),UT=__name(({cpuCount:e,totalMem:t,systemInfo:n})=>Q.createElement(jT,{title:"System Information"},Q.createElement(FT,{icon:Pe.bullet,label:"Version"},Q.createElement(ne,{color:ar.GREEN},n.version)),Q.createElement(FT,{icon:Pe.bullet,label:"Date"},Q.createElement(ne,null,formatDate())),Q.createElement(FT,{icon:Pe.pointer,label:"Platform"},Q.createElement(ne,{color:ar.GREEN},n.os),Q.createElement(ne,{color:ar.DIM}," ","(",w.platform(),", ",w.arch(),")")),Q.createElement(FT,{icon:Pe.triangleUp,label:"Hostname"},Q.createElement(ne,null,w.hostname())),Q.createElement(FT,{icon:Pe.bullet,label:"User"},Q.createElement(ne,{color:ar.YELLOW},w.userInfo().username)),Q.createElement(FT,{icon:Pe.bullet,label:"CPUs"},Q.createElement(ne,{color:ar.MAGENTA},e," cores")),Q.createElement(FT,{icon:Pe.bullet,label:"Memory"},Q.createElement(ne,{color:ar.CYAN},t," GB")),Q.createElement(FT,{icon:Pe.play,label:"Uptime"},Q.createElement(ne,null,OT(w.uptime()))),Q.createElement(FT,{icon:Pe.arrowRight,label:"Home"},Q.createElement(ne,{color:ar.DIM},w.homedir())),Q.createElement(FT,{icon:Pe.pointer,label:"Shell"},Q.createElement(ne,null,n.shell)),Q.createElement(FT,{icon:Pe.bullet,label:"Node"},Q.createElement(ne,{color:ar.GREEN},process.version)),Q.createElement(FT,{icon:Pe.pointer,label:"Terminal"},Q.createElement(ne,{color:ar.CYAN},n.terminal)),Q.createElement(FT,{icon:Pe.bullet,label:"IDE"},Q.createElement(ne,null,n.ide))),"SystemInfoSection"),BT=__name(({cpus:e})=>Q.createElement(jT,{title:"CPU Details",marginTop:1},e.map((e,t)=>Q.createElement(FT,{key:t,icon:Pe.bullet,label:`Core ${t}`},Q.createElement(ne,null,e.model.trim()),Q.createElement(ne,{color:ar.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),zT=__name(({networkInterfaces:e})=>Q.createElement(jT,{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(FT,{key:`${e}-${n}`,icon:Pe.bullet,label:e},Q.createElement(ne,{color:ar.GREEN},t.address))):null})),"NetworkSection"),HT=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r,systemInfo:o})=>Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,null,"System Information"),Q.createElement(ne,null,"─".repeat(40)),Q.createElement(ne,null,"Version ",o.version),Q.createElement(ne,null,"Date ",formatDate()),Q.createElement(ne,null,"Platform ",o.os," (",w.platform(),", ",w.arch(),")"),Q.createElement(ne,null,"Hostname ",w.hostname()),Q.createElement(ne,null,"User ",w.userInfo().username),Q.createElement(ne,null,"CPUs ",e.length," cores"),Q.createElement(ne,null,"Memory ",t," GB"),Q.createElement(ne,null,"Uptime ",OT(w.uptime())),Q.createElement(ne,null,"Home ",w.homedir()),Q.createElement(ne,null,"Shell ",o.shell),Q.createElement(ne,null,"Node ",process.version),Q.createElement(ne,null,"Terminal ",o.terminal),Q.createElement(ne,null,"IDE ",o.ide),r&&Q.createElement(Q.Fragment,null,Q.createElement(ne,null,"\n","CPU Details"),Q.createElement(ne,null,"─".repeat(40)),e.map((e,t)=>Q.createElement(ne,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),Q.createElement(ne,null,"\n","Network"),Q.createElement(ne,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>Q.createElement(ne,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),WT=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r,systemInfo:o})=>Q.createElement(te,{flexDirection:"column"},Q.createElement(UT,{cpuCount:e.length,totalMem:t,systemInfo:o}),r&&Q.createElement(BT,{cpus:e}),r&&Q.createElement(zT,{networkInterfaces:n})),"StyledInfo"),GT=__name(({verbose:e=!1,text:t=!1,systemInfo:n})=>{const{exit:r}=ae();X(()=>{const e=setTimeout(()=>r(),50);return()=>clearTimeout(e)},[r]);const o=w.cpus(),s=w.networkInterfaces(),i=Math.round(w.totalmem()/1024/1024/1024);return t?Q.createElement(HT,{cpus:o,totalMem:i,networkInterfaces:s,verbose:e,systemInfo:n}):Q.createElement(WT,{cpus:o,totalMem:i,networkInterfaces:s,verbose:e,systemInfo:n})},"InfoUI"),VT={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},QT={26:"Tahoe",15:"Sequoia",14:"Sonoma",13:"Ventura",12:"Monterey",11:"Big Sur"},KT=5e3,YT=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),JT=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(YT("__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"),XT=__name(()=>{const e=JT();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&VT[t]?VT[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),ZT=__name(()=>{if("win32"===S.platform()){const e=process.env.COMSPEC;return e?u(e):process.env.SHELL?u(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=Se(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:KT,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=u(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?u(e):"N/A"},"getShellName"),e_=__name(()=>{const e=JT();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),t_=__name(e=>{if(!e)return"macOS";const t=parseInt(e.split(".")[0],10),n=QT[t];return n?`macOS ${n} ${e}`:`macOS ${e}`},"formatMacOSDetail"),n_=__name(()=>{try{const e=Se("sw_vers -productVersion",{encoding:"utf8",timeout:KT,stdio:["ignore","pipe","ignore"]}).trim();return e?t_(e):null}catch{return null}},"getMacOSDetail"),r_=__name(()=>{const e=S.platform();return"darwin"===e?n_()??DT(e):DT(e)},"getDetailedPlatform"),o_=__name(()=>{try{const e=Se("cmd --version",{encoding:"utf8",timeout:KT,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:r_(),terminal:XT(),shell:ZT(),version:o_(),ide:e_()}}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"),Ot();var s_=["Code","Code - Insiders","VSCodium","Cursor"],i_="Code",a_={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},l_=__name(e=>m(e).href,"formatPathForTerminal"),c_=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),u_=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),d_=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=u_({home:t,configSegments:n,variant:o});if(L.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),m_=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&p_(t.when)},"isTerminalShiftEnterBinding"),p_=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),g_=__name(e=>{const t=dt(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),h_=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),f_=__name(({error:e,content:t})=>{const n=e.message;return h_(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"),y_=__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"),w_=__name(e=>{try{const t=dt(e),n=y_(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:f_({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),S_=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:l_(t)}),"createSuccessResult"),E_=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:l_(t)}),"createErrorResult"),b_=__name(()=>{const t=w.homedir(),n=w.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=c_(n);if(!r)return u_({home:t,configSegments:[".config"],variant:i_});const o=d_({home:t,configSegments:r,variants:s_});return u_({home:t,configSegments:r,variant:o??i_})},"getVSCodeKeybindingsPath"),C_=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)m_(n)&&(n.command===a_.command&&n.args?.text===a_.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),v_=__name(t=>{try{if(!L.existsSync(t)){const n=e.dirname(t);return L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=L.readFileSync(t,"utf-8");if(g_(n))return{rawContent:n,keybindings:[]};const r=w_(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:E_({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):E_({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return E_({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),k_=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(a_,null,2);if(g_(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return E_({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?E_({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=b_();try{const t=v_(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=C_(r);if(o.hasConflicting)return E_({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return S_({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=k_({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(L.writeFileSync(e,s,"utf-8"),S_({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return E_({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"),Ot(),wn(),Kn(),io(),as(),Rr();var T_=(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.RENAME="/rename",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.MCP="/mcp",e.COMPACT="/compact",e.COMPACT_MODE="/compact-mode",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e.ADD_DIR="/add-dir",e.REVIEW="/review",e.PR_COMMENTS="/pr-comments",e.CONTEXT="/context",e.STATUS="/status",e.USAGE="/usage",e.UPGRADE="/upgrade",e.EXTRA="/extra",e.COURSES="/courses",e))(T_||{}),__=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/provider","/model","/memory","/init","/agents","/mcp","/compact","/compact-mode","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/pr-comments","/context","/status","/usage","/upgrade","/extra","/courses"]),x_=new Set(["/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/rename","/provider","/model","/memory","/init","/agents","/mcp","/compact","/compact-mode","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/context","/status","/usage","/upgrade","/extra","/courses"]),A_=[{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:"/compact-mode",description:"Select a compact mode to compact sessions"},{command:"/context",description:"Show context window usage and breakdown"},{command:"/exit",description:"Exit Command Code"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/help",description:"Show available shortcuts"},{command:"/ide",description:Fv},{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:"Log in to Command Code"},{command:"/logout",description:"Log out of Command Code"},{command:"/courses",description:"Open Command Code courses in your browser"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/memory",description:"Manage Command Code memory"},{command:"/model",description:"Switch between Command Code models"},{command:"/pr-comments",description:"Fetch all PR comments for current branch"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/rename",description:"Rename the current session"},{command:"/resume",description:"Resume a past conversation"},{command:"/review",description:"Review a pull request (optional PR number)"},{command:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/status",description:"Show comprehensive environment status"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/usage",description:"Display credits, plan, and usage metrics"},{command:"/upgrade",description:"Open billing page to upgrade your plan"},{command:"/extra",description:"Open billing page to buy on-demand credits"}];function shadowedSuffix(e){return` — shadowed by ${e}`}function buildCommandMenuItems(e){const{customMenuItems:t,builtinMenuItems:n,skills:r}=e,o=new Map;for(const e of n)o.set(e.command,"built-in");for(const e of t)o.has(e.command)||o.set(e.command,"custom command");const s=[],i=new Set;for(const e of r){if(i.has(e.name))continue;i.add(e.name);const t=`/${e.name}`,n=o.get(t)?shadowedSuffix(t):"";s.push({command:t,description:`[skill] ${e.description}${n}`})}return[...n,...t,...s]}__name(shadowedSuffix,"shadowedSuffix"),__name(buildCommandMenuItems,"buildCommandMenuItems");var P_=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[o,s]=Y(0),[i,a]=Y(0),[l,u]=Y([]);X(()=>{let e=!1;return loadAllSkillSummaries().then(t=>{e||u(deduplicateSkills(t))}).catch(t=>{e||(dlog("[CommandMenu] Failed to load skills for slash menu",t),u([]))}),()=>{e=!0}},[]);const{stdout:d}=oe(),m=d?.columns??80,g=Math.max(20,m-22-2-1-2),h=Z(()=>{const e=buildCommandMenuItems({customMenuItems:customCommandsToMenuItems(loadCustomCommands()),builtinMenuItems:A_.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal())),skills:l});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,l]),f=Z(()=>{const e=i,t=Math.min(e+8,h.length);return h.slice(e,t)},[h,i]);return X(()=>{s(0),a(0)},[r]),se((r,l)=>{if(l.escape)n();else if(l.upArrow)s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t});else if(l.downArrow)s(e=>{const t=Math.min(h.length-1,e+1);return t>=i+8&&a(Math.max(0,t-8+1)),t});else{if(l.return){const t=h[o];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=h[o];return void(e&&t(e.command))}}}),0===h.length?Q.createElement(te,{flexDirection:"column",paddingLeft:2},Q.createElement(ne,{color:ar.DIM},"No commands found")):(h.length,Q.createElement(te,{flexDirection:"column",paddingLeft:1},Q.createElement(te,{columnGap:2},Q.createElement(te,{flexDirection:"column",width:22},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:n,color:o===n?ar.WHITE:ar.DIM,wrap:"truncate"},e.command)})),Q.createElement(te,{flexDirection:"column"},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:n,color:o===n?ar.WHITE:ar.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:g}))})))))},"CommandMenu");async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=yn();if(await getAuthKey(n)){let t="";try{const e=await loadCredentials();t=e?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}return void e(e=>[...e,rE(formatAlreadyLoggedIn(t))])}t(!0)}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o,contextEngineRef:s}){if(n(!1),!e)return r(e=>[...e,lE(t)]),void o("Ready...");r(e=>[...e,rE(t)]),s.current&&s.current.refreshRequest(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,rE("Authentication cancelled")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t,setRetryAttempt:n,setIsCmdCodeBusy:r}){let o;try{o=await getUserName()||void 0}catch{o=void 0}const s=await performLogout();if(!s.success)return void e(e=>[...e,lE(formatLogoutFailed(s.error||"Unknown error"))]);if(n(null),r(!1),t.current&&(t.current.interrupt(),t.current.refreshRequest()),!s.wasAuthenticated)return void e(e=>[...e,rE("Not currently authenticated")]);const i=formatLogoutWarnings(s.warnings),a=i?`${formatLogoutSuccess(o)}. ${i}`:formatLogoutSuccess(o);e(e=>[...e,rE(a)])}async function handleCompactCommand({contextEngineRef:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){if(e.current)try{r(!0),n("Compacting conversation...");const i=await e.current.manualCompact();yb(),s(e=>e+1);let a="Compacted conversation.";i.didCompact||(a="Conversation is already compact."),i.didCompact&&i.tokensSaved>0&&(a=`Compacted conversation, saved ~${i.tokensSaved.toLocaleString()} tokens.`),t(e=>[...e,rE(a)]),r(!1),n("Ready..."),o({current:e.current.getContextTokensUsed()||0,limit:getContextLimit(getConfiguredModel())})}catch(e){const o=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,lE(o)]),r(!1),n("Ready...")}else t(e=>[...e,rE("No active conversation to compact.")])}async function handleRenameCommand({name:e,contextEngineRef:t,setFeed:n}){const r=e?.trim();if(!r)return void n(e=>[...e,rE("Usage: /rename [name]")]);const o=t.current?.getSessionManager();if(!o)return void n(e=>[...e,rE("No active session to rename")]);const s=o.getSessionId();await rk.isSessionNameTaken({name:r,excludeSessionId:s})?n(e=>[...e,lE(`A session named "${r}" already exists. Choose a different name.`)]):await o.saveSessionMeta({title:r,userRenamed:!0})?n(e=>[...e,rE(`Session renamed to "${r}"`)]):n(e=>[...e,lE("Failed to rename session. Please try again.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,rE("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,rE("No active conversation to rewind.")])}async function handleRewindSelect({messageId:e,mode:t,contextEngineRef:n,setFeed:r,setStatus:o,setShowRewindSelector:s,setStaticKey:i,setInput:a}){if(s(!1),n.current)try{const s=n.current.listCheckpoints().find(t=>t.messageId===e);o("Restoring checkpoint...");const l=await n.current.restoreToCheckpoint({messageId:e,mode:t});if(l.success){const e=n.current.getSessionManager(),t=n.current.getMessages();r(e.reconstructFeedFromMessages(t)),yb(),i(e=>e+1),s?.userPrompt&&a(s.userPrompt);const u=[];l.filesRestored>0&&u.push(`${l.filesRestored} file${l.filesRestored>1?"s":""} restored`),l.filesDeleted>0&&u.push(`${l.filesDeleted} file${l.filesDeleted>1?"s":""} deleted`),l.messagesRemoved>0&&u.push(`${l.messagesRemoved} message${l.messagesRemoved>1?"s":""} removed`);const d=u.length>0?`Restored to checkpoint: ${u.join(", ")}.`:"Restored to checkpoint.";return r(e=>[...e,rE(d)]),void o("Ready...")}r(e=>[...e,lE(`Failed to restore: ${l.error}`)]),o("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;r(e=>[...e,lE(t)]),o("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleHelpCommand({setFeed:e}){const{createSystemEntry:t}=await Promise.resolve().then(()=>(_E(),kE));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=nE(`/${tn.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=uE(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=dE(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveEntries:t,setShareInfo:n,setShowShareNotification:r,setUnshareNotificationMessage:o,setStaticKey:s,setContextUsage:i,setInteractionTokens:a,contextEngineRef:l,setSessionId:u,createContextEngineCallbacks:d,clearSessionPermissions:m,permissionModeRef:g}){if(e([]),t([]),yb(),n(null),r(!1),o(""),l.current){const t=l.current.getSessionManager();t&&await t.deleteShareInfo(),await(l.current.getHookSystem()?.shutdown()),l.current=null;const n=crypto.randomUUID();u(n),m();const r=getContextEngineCallbacks({createContextEngineCallbacks:d,sessionId:n}),{contextEngine:o,startupEntriesPromise:s}=bootstrapContextEngineWithHooks({projectRoot:process.cwd(),sessionId:n,runMode:"interactive",permissionMode:g.current,callbacks:r});l.current=o;const i=await s;i.length>0&&e(e=>[...e,...i])}s(e=>e+1),i(null),a(0)}async function handleInitCommand({setFeed:e}){try{const t=process.cwd(),n=`Created AGENTS.md at ${await initProjectMemory(t)}. You can now edit it with /memory or open it in your editor.`;e(e=>[...e,rE(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,rE(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await pe(n,{wait:!1,background:!0}),e(e=>[...e,rE(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(_E(),kE));e(e=>[...e,r("Failed to open browser"),t(createOSC8Link(n,"Open GitHub issue manually"))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=cE();n(o.id),r(e=>[...e,o])}async function handleCommand(e,t){const n=e.startsWith("/resume:"),r=n?null:parseCommandInput({input:e}),o=n?"/resume":r?.commandName??"";if(t.isCmdCodeBusy&&x_.has(o))return t.setFeed(e=>[...e,rE(`Cannot run ${o} while Command Code is working. Press Esc or Ctrl+C to interrupt the current turn first.`)]),{status:"handled"};if(n){const n=e.substring(8);return await handleSelectSession({selectedSessionId:n,sessionLoadIdRef:t.sessionLoadIdRef,contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,permissionModeRef:t.permissionModeRef,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,createContextEngineCallbacks:t.createContextEngineCallbacks}),{status:"handled"}}if(!r)return{status:"unknown"};const{commandName:s,rawArguments:i,positionalArgs:a}=r;if(__.has(s)&&i.trim().length>0)return{status:"unknown"};if("/exit"===s)return t.setShouldExit(!0),{status:"handled"};if("/clear"===s)return await handleClearCommand(t),{status:"handled"};if("/help"===s)return await handleHelpCommand(t),{status:"handled"};if("/share"===s)return await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/unshare"===s)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/taste"===s)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===s)return handleLearnCommand(t),{status:"handled"};if("/skills"===s)return t.setShowSkillsConfig(!0),{status:"handled"};if("/provider"===s)return isInternalTeamFlagEnforced()?(t.setShowProviderSelector(!0),{status:"handled"}):(t.setStatus("Provider selection not available"),{status:"handled"});if("/model"===s)return t.setShowModelSelector(!0),{status:"handled"};if("/memory"===s)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===s)return t.setShowSessionSelector(!0),{status:"handled"};if("/init"===s)return await handleInitCommand(t),{status:"handled"};if("/agents"===s)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===s)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===s)return await handleCompactCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/compact-mode"===s)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/context"===s)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===s)return handleRewindCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/login"===s)return await handleLoginCommand({setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay}),t.setInput(""),{status:"handled"};if("/logout"===s)return await handleLogoutCommand({setFeed:t.setFeed,contextEngineRef:t.contextEngineRef,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/courses"===s){const e="https://commandcode.ai/courses";try{await pe(e,{wait:!1,background:!0}),t.setFeed(t=>[...t,rE(`Opened ${createOSC8Link(e,"courses")} in your browser`)])}catch{t.setFeed(t=>[...t,rE(`Command Code courses: ${e}`)])}return{status:"handled"}}if("/feedback"===s)return await handleFeedbackCommand(t),{status:"handled"};if("/terminal-setup"===s)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===s)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===s)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===s)return await handleRenameCommand({name:i.trim(),contextEngineRef:t.contextEngineRef,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/usage"===s)return t.setShowUsageOverlay(!0),{status:"handled"};if("/review"===s){const e=i.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(vb(),bb));let r=e,o=!1;if(!e){const e=await xT();r=e?String(e.number):"",o=!!e}return await n({input:buildReviewPrompt({prNumber:r,autoDetected:o}),role:"user",displayMessage:r?`/review ${r}`:"/review",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}if("/pr-comments"===s)return await handleSubmit({input:"Fetch and display all comments from the current GitHub pull request.\n\n Run these commands in order:\n\n 1. `gh pr view --json number,headRepository` — if this fails, reply \"No comments found.\" and stop.\n 2. `gh api --paginate '/repos/{owner}/{repo}/issues/NUMBER/comments' --jq '.[] | {body,\n user: .user.login, id, created_at}' > /tmp/pr-NUMBER-issue-comments.json`\n 3. `gh api --paginate '/repos/{owner}/{repo}/pulls/NUMBER/comments' --jq '.[] | {body,\n diff_hunk: (.diff_hunk | split(\"\n\") | .[-5:] | join(\"\n\")), path, line, user: .user.login,\n in_reply_to_id, id, created_at}' > /tmp/pr-NUMBER-review-comments.json`\n\n If both return empty, reply \"No comments found.\"\n\n `{owner}` and `{repo}` are gh template variables — write them literally, never substitute. Always\n use `--jq` (not piped `| jq`).\n\n Read the temp JSON files to build output comments directly in markdown using the format:\n\n ## PR Comments\n\n - @author (date):\n > body\n\n ## Review Comments\n\n - @author path#line:\n ```diff (replace ```suggestion code blocks with ```diff to avoid rendering errors)\n [diff_hunk]\n ```\n > body [replies indented by in_reply_to_id]\n\n Number the comments in the order they were created (created_at).\n No explanatory text, no horizontal rules. No extra space in the end.",role:"user",displayMessage:"/pr-comments",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),lastResponseHasComments(t.contextEngineRef.current?.getMessages()??[])&&t.setInput("Fix all review comments"),{status:"handled"};if("/status"===s)return t.setShowStatusView(!0),{status:"handled"};if("/upgrade"===s){let e=await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})??"https://commandcode.ai/settings/billing";e+="#plans";try{await pe(e,{wait:!1,background:!0}),t.setFeed(t=>[...t,rE(`Opened ${createOSC8Link(e,"billing page")} in your browser`)])}catch{t.setFeed(t=>[...t,rE(`Upgrade your plan: ${e}`)])}return{status:"handled"}}if("/extra"===s){let e=await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})??"https://commandcode.ai/settings/billing";e+="#extra-usage";try{await pe(e,{wait:!1,background:!0}),t.setFeed(t=>[...t,rE(`Opened ${createOSC8Link(e,"billing page")} in your browser`)])}catch{t.setFeed(t=>[...t,rE(`Buy on-demand credits: ${e}`)])}return{status:"handled"}}const l=getCustomCommandContent(s);if(l){const n=processCommandTemplate({template:l,rawArguments:i,positionalArgs:a}),{handleSubmit:r}=await Promise.resolve().then(()=>(vb(),bb));return await r({input:n.content,role:"user",displayMessage:e,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}return await handleSkillCommand({commandName:s,command:e,rawArguments:i,positionalArgs:a,ctx:t})||{status:"unknown"}}async function handleSkillCommand({commandName:e,command:n,rawArguments:r,positionalArgs:o,ctx:s}){const i=e.startsWith("/")?e.substring(1):e;let a;try{a=await loadAllSkillSummaries()}catch{return null}const l=deduplicateSkills(a).find(e=>e.name===i);if(!l)return null;const{names:u}=await loadDisabledSkills();if(u.has(l.name))return s.setFeed(e=>[...e,rE(`Skill "${i}" is disabled. Toggle it back on with /skills.`)]),{status:"handled"};try{const a=await loadSkill({filePath:l.filePath}),u=buildSlashCommandMessage({commandName:e,rawArguments:r,skillName:i}),d=buildSlashCommandSkillContextMessage({rawArguments:r,positionalArgs:o,skillContent:a.content,skillDirectory:t.dirname(l.filePath)});return await handleSubmit({input:u,hiddenMessages:[{role:"user",content:d}],role:"user",displayMessage:n,isAutomated:!0,feed:s.feed,setFeed:s.setFeed,isCmdCodeBusy:s.isCmdCodeBusy,setIsCmdCodeBusy:s.setIsCmdCodeBusy,setQueuedMessages:s.setQueuedMessages,setStatus:s.setStatus,setInteractionTokens:s.setInteractionTokens,updateStatus:s.updateStatus,setUpdateStatus:s.setUpdateStatus,billingLink:s.billingLink,setBillingLink:s.setBillingLink,contextEngineRef:s.contextEngineRef,isSubmittingRef:s.isSubmittingRef,setInput:s.setInput,setStaticKey:s.setStaticKey,executeBash:s.executeBash}),{status:"handled"}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return s.setFeed(e=>[...e,lE(`Failed to load skill "${i}": ${t}`)]),{status:"handled"}}}function useCommandCtx({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,permissionState:a,contextEngineRef:l,isSubmittingRef:u,executeBash:d,createContextEngineCallbacks:m,setInput:g}){const h=Z(()=>({feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,setStaticKey:o.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,currentModel:r.currentModel,premiumCreditsExhausted:r.premiumCreditsExhausted,setPremiumCreditsExhausted:r.setPremiumCreditsExhausted,setCurrentModel:r.setCurrentModel,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setRetryAttempt:n.setRetryAttempt,setShowTasteConfig:o.setShowTasteConfig,setShowSkillsConfig:o.setShowSkillsConfig,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowMemorySelector:o.setShowMemorySelector,setShowAgentsConfig:o.setShowAgentsConfig,setShowMcpManager:o.setShowMcpManager,setShowRewindSelector:o.setShowRewindSelector,setShowCompactModeSelector:o.setShowCompactModeSelector,setShowContextView:o.setShowContextView,setShowAddDirModal:o.setShowAddDirModal,setShowLoginOverlay:o.setShowLoginOverlay,setShowStatusView:o.setShowStatusView,setShowUsageOverlay:o.setShowUsageOverlay,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:o.setShowSessionSelector,setPermissionMode:a.setPermissionMode,permissionModeRef:a.permissionModeRef,contextEngineRef:l,clearSessionPermissions:a.clearSessionPermissions,createContextEngineCallbacks:m,setShouldExit:i.setShouldExit,setInput:g,isSubmittingRef:u,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:d}),[e,t,n,r,o,s,i,a,l,u,d,m,g]),f=J(h);return f.current=h,{commandCtx:h,onCommand:ee(e=>handleCommand(e,f.current),[])}}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i}){try{const a=getProviderConfig(e);if(a?.requiresAuth&&a.checkAuth&&!await a.checkAuth()&&a.authComponent)return void r({provider:e,Component:a.authComponent});await updateUserConfig({provider:e}),t(e),n(!1),o(`Provider set to ${getProviderDisplayName(e)}`),i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),o("Failed to set provider"),n(!1)}}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i}){e&&(t(null),n(!1),r(e.provider),o(`${getProviderDisplayName(e.provider)} authentication successful`),i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},5e3))}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}async function resolveAuthBlock(e){if(!e)return null;const t=getProviderConfig(e);return t?.requiresAuth&&t.checkAuth?await t.checkAuth()?null:{displayName:t.displayName}:null}async function persistSelection(e){const{modelId:t,provider:n,setCurrentProvider:r}=e;n?(dlog(`[Model] Setting provider to ${n} for ${t}`),await updateUserConfig({provider:n,model:t}),r?.(n)):await updateUserConfig({model:t})}async function handleModelSelect({modelId:e,provider:t,setCurrentModel:n,setShowModelSelector:r,setStatus:o,modelNotificationTimer:s,setShowModelNotification:i,setCurrentProvider:a,setStaticKey:l,contextEngineRef:u,setFeed:d,setContextUsage:m}){try{const g=await resolveAuthBlock(t);if(g)return o(`Run /provider to authenticate with ${g.displayName} first`),void r(!1);const h=getConfiguredModel();await persistSelection({modelId:e,provider:t,setCurrentProvider:a}),n(e);const f=h!==e;f&&(hardResetForResize(),l(e=>e+1)),r(!1);const y=getModelDisplayName(e);o(`Model set to ${y}`),f&&await reconcileContextOnModelChange({modelId:e,modelName:y,previousLimit:getContextLimit(h),contextEngineRef:u,setFeed:d,setContextUsage:m}),s.current&&clearTimeout(s.current),i(!0),s.current=setTimeout(()=>{i(!1),s.current=null},5e3)}catch(e){console.error("Failed to set model:",e),o("Failed to set model"),r(!1)}}async function reconcileContextOnModelChange(e){const{modelId:t,modelName:n,previousLimit:r,contextEngineRef:o,setFeed:s,setContextUsage:i}=e,a=o?.current;if(!a)return void i?.({current:0,limit:getContextLimit(t)});const l=await a.onModelChanged(r);if(i?.({current:a.getContextTokensUsed(),limit:l.newLimit}),!l.overflowed)return;const u=Math.round(l.tokensUsed/l.newLimit*100),d=l.tokensSaved>0?`${n} has a smaller context window (${l.newLimit.toLocaleString()} tokens). Auto-compacted to fit — saved ~${l.tokensSaved.toLocaleString()} tokens.`:`${n} has a smaller context window (${l.newLimit.toLocaleString()} tokens) and current usage is ~${l.tokensUsed.toLocaleString()} (${u}%). Run /compact to free space before your next message.`;s?.(e=>[...e,rE(d)])}function handleModelCancel({setShowModelSelector:e}){e(!1)}Ot(),_E(),fb(),fs(),RE(),lb(),ws(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ot(),_E(),Sb(),Jr(),__name(handleCompactCommand,"handleCompactCommand"),Ot(),_E(),__name(handleRenameCommand,"handleRenameCommand"),Ot(),_E(),Sb(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),vb(),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(handleFeedbackCommand,"handleFeedbackCommand"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(handleSkillCommand,"handleSkillCommand"),__name(useCommandCtx,"useCommandCtx"),Ot(),Ot(),io(),Jr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Ot(),_E(),Jr(),io(),Qr(),Kn(),__name(resolveAuthBlock,"resolveAuthBlock"),__name(persistSelection,"persistSelection"),__name(handleModelSelect,"handleModelSelect"),__name(reconcileContextOnModelChange,"reconcileContextOnModelChange"),__name(handleModelCancel,"handleModelCancel"),Ot(),Jr();var I_={default:"Compact Normal",fast:"Compact Fast"};async function handleCompactModeSelect({mode:e,setShowCompactModeSelector:t,setStatus:n}){try{await setCompactMode({mode:e}),t(!1),n(`Compact mode set to: ${I_[e]}`)}catch{n("Failed to set compact mode"),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var N_=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l}){const u=J({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l});return u.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l},{onSelectSession:ee(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a}=u.current;handleSelectSession({selectedSessionId:e,sessionLoadIdRef:n.sessionLoadIdRef,contextEngineRef:i,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:o.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,permissionModeRef:s.permissionModeRef,setStaticKey:o.setStaticKey,setShareInfo:r.setShareInfo,createContextEngineCallbacks:a})},[]),onNewSession:ee(()=>{const{feedState:e,sessionState:t,uiOverlays:n,permissionState:r,contextEngineRef:o}=u.current;handleNewSession({contextEngineRef:o,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:n.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:r.setPermissionMode})},[]),onRewindSelect:ee(({messageId:e,mode:t})=>{const{feedState:n,statusState:r,uiOverlays:o,contextEngineRef:s,setInput:i}=u.current;handleRewindSelect({messageId:e,mode:t,contextEngineRef:s,setFeed:n.setFeed,setStatus:r.setStatus,setShowRewindSelector:o.setShowRewindSelector,setStaticKey:o.setStaticKey,setInput:i})},[]),onRewindCancel:ee(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:ee((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o,contextEngineRef:s}=u.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus,contextEngineRef:s})},[]),onLoginCancel:ee(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:ee(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:r.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:n.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer})},[]),handleProviderCancel:ee(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:ee((e,t)=>{const{authState:n,statusState:r,uiOverlays:o,feedState:s,contextEngineRef:i}=u.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:o.setShowModelSelector,setStatus:r.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:N_,setCurrentProvider:n.setCurrentProvider,setStaticKey:o.setStaticKey,contextEngineRef:i,setFeed:s.setFeed,setContextUsage:r.setContextUsage})},[]),handleModelCancel:ee(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleCompactModeSelect:ee(e=>{const{statusState:t,uiOverlays:n}=u.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),handleCompactModeCancel:ee(()=>{handleCompactModeCancel({setShowCompactModeSelector:u.current.uiOverlays.setShowCompactModeSelector})},[]),handleAuthSuccess:ee(()=>{const{authState:e,statusState:t,uiOverlays:n}=u.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:n.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:t.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer})},[]),handleAuthCancel:ee(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}function findNewThreshold({depletionPct:e,warnedThresholds:t}){const n=[...en].sort((e,t)=>t-e);for(const r of n)if(e>=r&&!t.has(r))return r;return null}function getDepletionPct({planId:e,monthlyCredits:t}){const n=Yt[e];if(!n||n.total<=0)return null;const r=n.total-t;return Math.min(100,Math.max(0,r/n.total*100))}function buildWarningMessage({depletionPct:e,remainingCredits:t,billingUrl:n}){return`${Math.round(e)}% of plan credits used (${Number.isInteger(t)?String(t):t.toFixed(1)} remaining). Upgrade: ${n}`}function useCreditWarning({interactionTokens:e}){const[t,n]=Y(null),r=J(new Set),o=J(null),s=J(!1),i=J(null),a=J("https://commandcode.ai/settings/billing"),l=J(null),u=J(null),d=ee(async()=>{try{const e=getApiBaseUrl(),t=new jw({baseUrl:e});if(!s.current){s.current=!0;try{const e=await getAuthenticatedEntity();i.current=e.org?.id??null,a.current=e.org?`https://commandcode.ai/${e.org.login}/settings/billing`:"https://commandcode.ai/settings/billing";const n=await t.get({endpoint:buildEndpoint({endpoint:Bt.ALPHA.BILLING.SUBSCRIPTIONS,params:{orgId:i.current}})});o.current=n}catch{return}}const l=o.current;if(!l?.success||!l.data)return;const{planId:d,status:m}=l.data;if("active"!==m&&"past_due"!==m)return;if(!Yt[d]||Yt[d].total<=0)return;let g;try{g=await t.get({endpoint:buildEndpoint({endpoint:Bt.ALPHA.BILLING.CREDITS,params:{orgId:i.current}})})}catch{return}const{monthlyCredits:h}=g.credits,f=getDepletionPct({planId:d,monthlyCredits:h});if(null===f)return;const y=findNewThreshold({depletionPct:f,warnedThresholds:r.current});if(null===y)return;for(const e of en)e<=y&&r.current.add(e);const w=buildWarningMessage({depletionPct:f,remainingCredits:h,billingUrl:a.current});n(w),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{n(null),u.current=null},3e4)}catch{}},[]);return X(()=>{if(0!==e)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{d(),l.current=null},2e3),()=>{l.current&&clearTimeout(l.current)}},[e,d]),X(()=>()=>{u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current)},[]),{creditWarning:t}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Ot(),fS(),sS(),Eb(),wn(),__name(findNewThreshold,"findNewThreshold"),__name(getDepletionPct,"getDepletionPct"),__name(buildWarningMessage,"buildWarningMessage"),__name(useCreditWarning,"useCreditWarning"),Ot(),Ot(),Ot();var R_=__name(({staticKey:e})=>Q.createElement(re,{items:[{staticKey:e}],key:e},()=>Q.createElement(ne,{key:e},"\0")),"Responsive");Ot(),wn(),Rr();var M_=__name(({onTrust:e,onExit:t})=>{const{exit:n}=ae(),[r,o]=Y(1),s=process.cwd().replace(process.env.HOME||"","~");return se((s,i)=>{i.upArrow||i.downArrow?o(1===r?2:1):i.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||i.escape||i.ctrl&&"c"===s)&&(t(),n())}),Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.YELLOW,padding:1},Q.createElement(ne,{color:ar.YELLOW,bold:!0},"Do you trust the files in this folder?"),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},s)),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:1===r?ar.CYAN:ar.GRAY},1===r?Pe.pointer:" "," 1. Yes, proceed")),Q.createElement(te,null,Q.createElement(ne,{color:2===r?ar.CYAN:ar.GRAY},2===r?Pe.pointer:" "," 2. No, exit"))))},"TrustPrompt"),L_=K(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return Q.createElement(Q.Fragment,null,Q.createElement(R_,{staticKey:e}),Q.createElement(M_,{onTrust:t,onExit:n}))},"TrustView"));Ot(),Ot(),as(),Rr();var $_=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=ae(),[r,o]=Y([]),[s,i]=Y(0),[a,l]=Y(!0),[u,d]=Y(0),m=30;X(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await rk.listSessions();o(e),l(!1)},"loadSessions");if(se((t,o)=>{o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):o.downArrow?i(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()}),a)return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:ar.GRAY},"Loading sessions..."));const h=__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),i=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===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),f=__name(e=>truncateString({text:e,maxChars:Yo}),"truncateMessage");if(0===r.length)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.GRAY},"No sessions available"));const y=r.slice(u,u+m),w=u;return Q.createElement(te,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.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(te,{columnGap:2,marginBottom:1},Q.createElement(te,{width:7},Q.createElement(ne,{color:ar.GRAY}," ")),Q.createElement(te,{width:13},Q.createElement(ne,{color:ar.GRAY},"Modified")),Q.createElement(te,{width:11},Q.createElement(ne,{color:ar.GRAY},"# Messages")),Q.createElement(te,{width:20},Q.createElement(ne,{color:ar.GRAY},"Git Branch")),Q.createElement(te,null,Q.createElement(ne,{color:ar.GRAY},"Summary"))),Q.createElement(te,{columnGap:2},Q.createElement(te,{flexDirection:"column",width:7},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`sel-${n}`,color:s===n?ar.CYAN:ar.GRAY},s===n?`${Pe.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(te,{flexDirection:"column",width:13},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`mod-${e.id}`,color:s===n?ar.WHITE:ar.GRAY},h(e.lastModified))})),Q.createElement(te,{flexDirection:"column",width:11},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`msg-${e.id}`,color:s===n?ar.WHITE:ar.GRAY},e.messageCount)})),Q.createElement(te,{flexDirection:"column",width:20},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`branch-${e.id}`,color:s===n?ar.WHITE:ar.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(te,{flexDirection:"column"},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`summary-${e.id}`,color:s===n?ar.WHITE:ar.GRAY},f(e.firstMessage))}))))},"SessionTable"),D_=K(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return Q.createElement($_,{onSelectSession:e,onNewSession:t})},"SessionView"));Ot(),Ot(),$r(),Rr();var O_=__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"),F_=__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,i)=>{const a=i===t&&!r,l=n.has(i);let u,d;a?(u=Pe.bullet,d=ar.CYAN):l?(u=Pe.tick,d=ar.GREEN):(u=Pe.circle,d=ar.GRAY),s.push(Q.createElement(ne,{key:i},Q.createElement(ne,{color:d},u),Q.createElement(ne,{color:a?ar.CYAN:void 0}," ",o.header),i<e.length-1?Q.createElement(ne,{color:ar.DIM}," | "):null))}),!o){const e=r;s.push(Q.createElement(ne,{key:"review"},Q.createElement(ne,{color:ar.DIM}," | "),Q.createElement(ne,{color:e?ar.CYAN:ar.GRAY},e?Pe.bullet:Pe.circle),Q.createElement(ne,{color:e?ar.CYAN:void 0,bold:e}," ","Review")))}return Q.createElement(te,null,s)},"TabIndicator"),q_=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,o]=Y(0),[s,i]=Y(new Map),a=J(new Map),[l,u]=Y(""),[d,m]=Y(new Set),[g,h]=Y(null),[f,y]=Y(!1),[w,S]=Y(!1),[E,C]=Y(!1),[v,k]=Y(null),[T,_]=Y(!1),x=e[r],A=x?.multiSelect??!1,P=s.get(r),I=x?[...x.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],N=I.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),R=new Map(N.map((e,t)=>[e.label,I[t]])),M=__name(e=>{"submit"===e.value?q():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),L=__name(()=>{if(!P||0===P.length)return 0;const e=P[0],t=x.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),$=__name(e=>{if(!f)if(A){const t=O_(e.value,x.options.length-1);if(null===t)return;const n=x.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=O_(e.value,x.options.length-1);if(null===t)return;y(!0);const n=x.options[t]?.label||"";F([n])}},"handleSelect"),D=__name(()=>{if(f)return;y(!0);const e=Array.from(d);F(e)},"handleMultiSelectDone"),O=__name(()=>{if(!f&&l.trim())if(A){const e=new Set(x.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 y(!0),F([l.trim()])},"handleOtherSubmit"),F=__name(t=>{a.current.set(r,t);const s=new Map(a.current);i(s);const l=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),o(e),y(!1),C(!1),k(null),_(!1)}else if(e.every((e,t)=>s.has(t))){if(n&&1===e.length)return void q();m(new Set),u(""),S(!0),y(!1)}else{const t=e.findIndex((e,t)=>!s.has(t));-1!==t&&(l(t),o(t)),y(!1),C(!1),k(null),_(!1)}},"finishQuestion"),q=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),j=__name(t=>{S(!1),o(t),_(!1),C(!1),k(null);const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),U=__name(t=>{if(t<0||t>=e.length)return;A&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),y(!1),C(!1),k(null),_(!1);const n=e[t],s=a.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"),B=__name(()=>{if(!g||!A)return;if("done"===g.value)return;const e=O_(g.value,x.options.length-1);if(null===e)return;const t=x.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return se((t,o)=>{if(" "===t&&A&&!E&&B(),"d"!==t||!A||E||w||D(),!w&&!f){if(o.downArrow&&!E&&!T&&!n&&g&&N.length>0&&g.value===N[N.length-1]?.value&&C(!0),o.upArrow&&!E&&!T&&g&&N.length>0&&g.value===N[0]?.value&&(A?_(!0):n||(C(!0),k(N.length-1))),o.upArrow&&E){C(!1),k(N.length-1);const e=N[N.length-1];e&&h(e)}if(o.downArrow&&E)if(C(!1),A)_(!0);else{k(0);const e=N[0];e&&h(e)}if(o.upArrow&&T&&(_(!1),C(!0)),o.downArrow&&T){_(!1),k(0);const e=N[0];e&&h(e)}o.return&&T&&A&&D()}if(f||E||T||(w?o.leftArrow&&j(e.length-1):o.leftArrow&&r>0?U(r-1):o.rightArrow&&(r<e.length-1?U(r+1):(A&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),S(!0)))),o.escape&&!f)if(w)S(!1);else if(E){C(!1);const e=v??N.length-1;k(e);const t=N[e];t&&h(t)}else if(T){_(!1);const e=N[N.length-1];e&&h(e)}}),x||w?w?Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(F_,{questions:e,currentIndex:e.length,answeredQuestions:new Set(s.keys()),isReviewPage:!0})),e.map((e,t)=>Q.createElement(te,{key:t,marginBottom:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},t+1,". ",e.question),Q.createElement(ne,{color:ar.GREEN}," ",s.get(t)?.join(", ")||"No answer"))),Q.createElement(mt,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:M,initialIndex:0,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(ne,{color:t?ar.CYAN:ar.WHITE},e)}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},Pe.arrowLeft," to go back and edit"))):Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(F_,{questions:e,currentIndex:r,answeredQuestions:new Set(s.keys()),isReviewPage:!1,hideReview:n})),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0},x.question)),E||T?Q.createElement(te,{flexDirection:"column"},N.map((e,t)=>{const n=R.get(e.label),r=A&&n&&d.has(n.label),o=!A&&n&&P?.includes(n.label),s=r||o;return Q.createElement(te,{key:t,flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,null," "),Q.createElement(ne,{color:s?ar.GREEN:ar.WHITE}," ",t+1,"."," "),A&&(s?Q.createElement(ne,{color:ar.GREEN},"[",Pe.tick,"]"," "):Q.createElement(ne,{color:ar.DIM},"[ ] ")),Q.createElement(ne,{color:s?ar.GREEN:ar.WHITE},n?.label||""),!A&&s&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick)),n?.description&&Q.createElement(te,null,Q.createElement(ne,null," "),Q.createElement(ne,{color:ar.DIM},A?" ":" ",n.description)))})):Q.createElement(mt,{key:`${r}-${v??"default"}`,items:N,initialIndex:v??L(),onSelect:$,onHighlight:h,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=R.get(e),r=A&&n&&d.has(n.label),o=!A&&n&&P?.includes(n.label),s=r||o,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:t?ar.CYAN:s?ar.GREEN:ar.WHITE}," ",a,"."," "),A&&(s?Q.createElement(ne,{color:ar.GREEN},"[",Pe.tick,"]"," "):Q.createElement(ne,{color:ar.DIM},"[ ] ")),Q.createElement(ne,{color:t?ar.CYAN:s?ar.GREEN:ar.WHITE},l),!A&&s&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick)),n?.description&&Q.createElement(ne,{color:ar.DIM},A?" ":" ",n.description))}}),!n&&Q.createElement(te,null,Q.createElement(ne,{color:ar.CYAN},E?Pe.pointer:" "),Q.createElement(ne,{color:E?ar.CYAN:void 0}," ",N.length+1,"."," "),A&&(d.has(l.trim())?Q.createElement(ne,{color:ar.GREEN},"[",Pe.tick,"] "):Q.createElement(ne,{color:ar.DIM},"[ ] ")),Q.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),A&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:O,placeholder:"Type something...",focus:E,stripBracketedPaste:!0})),A&&Q.createElement(te,null,Q.createElement(ne,{color:ar.CYAN},T?Pe.pointer:" "),Q.createElement(ne,{color:T?ar.CYAN:void 0,bold:T}," ",r===e.length-1?"Submit":"Next")),e.length>1&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,dangerouslySkipPermissions:n,setPendingQuestion:r,setStatus:o,setStaticKey:s}){return Q.createElement(te,{marginY:1},Q.createElement(q_,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,onResponse:i=>{if(e.params.exitPlanMode){const e=i.answers[0]?.selectedOptions[0]||"";e.startsWith("Yes, auto-accept")?(t("auto-accept"),yb(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t(n?"bypass":"standard"),yb(),s(e=>e+1))}if(e.params.enterPlanMode){const e=i.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),yb(),s(e=>e+1))}e.resolve(i),r(null),o("Answers submitted")}}))}Sb(),__name(QuestionView,"QuestionView"),Ot(),Ot(),wn(),Ot(),Rr();var j_=/\[([^\]]+)\]/g;function BracketWrap({children:e,color:t,bold:n=!1}){return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIMMEST,bold:n},"["),"string"==typeof e?Q.createElement(ne,{color:t,bold:n},e):e,Q.createElement(ne,{color:ar.DIMMEST,bold:n},"]"))}function BracketedText({text:e,color:t,bold:n=!1,wrap:r}){const o=Z(()=>{const t=[];let n=0;for(const r of e.matchAll(j_)){const o=r.index??0;o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"bracket",value:r[1]??""}),n=o+r[0].length}return n<e.length&&t.push({type:"text",value:e.slice(n)}),0===t.length&&t.push({type:"text",value:e}),t},[e]),s=Z(()=>o.map((e,r)=>"bracket"===e.type?Q.createElement(BracketWrap,{key:`bracket-${r}`,color:t,bold:n},e.value):e.value),[o,t,n]);return Q.createElement(ne,{color:t,bold:n,wrap:r},s)}__name(BracketWrap,"BracketWrap"),__name(BracketedText,"BracketedText"),Rr(),Ot(),_E(),as(),ao(),Rr(),Ot(),Rr();var U_=class extends ht{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}hr(){return"\n"+ce.dim("───")+"\n"}blockquote(e){return"object"==typeof e&&(e=this.parser.parse(e.tokens)),this.o.blockquote(e.trim()).split("\n").map(e=>`│ ${e}`).join("\n")+"\n\n"}listDepth=0;list(e,t=!1,n=""){let r;this.listDepth++;try{r=super.list(e,t,n),r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),1===this.listDepth&&(r=r.replace(/^ /gm,""))}finally{this.listDepth--}return r}},B_=new gt;B_.setOptions({renderer:new U_({strong:ce.bold,em:ce.italic,del:ce.dim.strikethrough,codespan:ce.hex(Tr.CODE),code:ce.hex(Tr.CODE),heading:ce.bold,firstHeading:ce.bold.hex(Tr.HEADING).underline,link:ce.hex(ar.CYAN),href:ce.hex(ar.CYAN).underline,blockquote:ce.hex(ar.GRAY).italic,table:ce.reset,tableOptions:{style:{head:[ar.CYAN],border:[ar.GRAY]}},hr:ce.reset,paragraph:ce.reset,html:ce.hex(ar.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var z_=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=Z(()=>{if(!e)return"";const t=[],n=e.replace(z_,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=B_.parse(n);if("string"!=typeof r)return e;return r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").replace(/^(\s*)\* /gm,"$1- ").replace(/\n{3,}/g,"\n\n").trim()}catch{return e}},[e]);return Q.createElement(ne,{color:t,dimColor:n,wrap:r},o)}function buildTreeConnectors(e,t={}){const{isTruncated:n=!1,closesFrame:r=!0}=t;return e.split("\n").map((e,t,o)=>r&&!n&&t===o.length-1?wT:ST).join("\n")}__name(Markdown,"Markdown"),Ot(),__name(buildTreeConnectors,"buildTreeConnectors");var H_=" │ ";function computeSimilarity({strA:e,strB:t}){const n=e.trim(),r=t.trim();if(n===r)return 1;if(!n||!r)return 0;const o=Object.create(null);for(let e=0;e<n.length;e++){const t=n[e];o[t]=(o[t]??0)+1}let s=0;for(let e=0;e<r.length;e++){const t=r[e],n=o[t];n&&(s++,o[t]=n-1)}return 2*s/(n.length+r.length)}function buildSimilarityMatrix(e,t,n){const r=new Float64Array(e.length*n);for(let o=0;o<e.length;o++)for(let s=0;s<n;s++)r[o*n+s]=computeSimilarity({strA:e[o],strB:t[s]});return r}function collectSimilarityCandidates(e,t,n){const r=[];for(let o=0;o<t;o++)for(let t=0;t<n;t++){const s=e[o*n+t];s>=.3&&r.push({score:s,removedIdx:o,addedIdx:t})}return r}function buildLinePairs(e,t){const n=e.length,r=t.length,o=new Map;if(n*r>200){const e=Math.min(n,r);for(let t=0;t<e;t++)o.set(t,t);return o}const s=collectSimilarityCandidates(buildSimilarityMatrix(e,t,r),n,r);s.sort((e,t)=>t.score-e.score);const i=new Set,a=new Set;for(const{removedIdx:e,addedIdx:t}of s)i.has(e)||a.has(t)||(o.set(e,t),i.add(e),a.add(t));return o}function groupAdjacentChanges(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r.added&&!r.removed){const e=r.value.split("\n");""===e.at(-1)&&e.pop(),t.push({type:"context",contextLines:e,removedLines:[],addedLines:[]}),n++;continue}const o=[],s=[];for(;n<e.length&&(e[n].added||e[n].removed);){const t=e[n].value.split("\n");""===t.at(-1)&&t.pop(),e[n].removed?(o.push(...t),n++):(s.push(...t),n++)}t.push({type:"change",contextLines:[],removedLines:o,addedLines:s})}return t}function renderWordSegments({wordChanges:e,type:t,dimDiff:n}){const r="removed"===t?mr.REMOVED_HIGHLIGHT_BG:mr.ADDED_HIGHLIGHT_BG,o=[];let s=0;for(const i of e){if("removed"===t&&i.added)continue;if("added"===t&&i.removed)continue;const e="removed"===t?i.removed:i.added,a=i.value.replace(/\s/g," "),l=`${t}-${s++}-${e?"highlighted":"unchanged"}`;e?o.push(Q.createElement(ne,{key:l,backgroundColor:r,dimColor:n},a)):o.push(Q.createElement(ne,{key:l,color:ar.WHITE,dimColor:n},a))}return o}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:o}){return Q.createElement(te,{key:o,width:"100%"},Q.createElement(ne,{color:mr.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:r},H_),Q.createElement(ne,{color:ar.WHITE,dimColor:r}," ",e.replace(/\s/g," ")))}function renderContextGroup({lines:e,leadCount:t,trailCount:n,lineNumWidth:r,dimDiff:o,counters:s}){const i=[];if(t+n>=e.length){for(const t of e)i.push(renderContextLine({line:t,lineNum:s.newLineNum,lineNumWidth:r,dimDiff:o,nodeKey:"ctx-"+s.nodeKey++})),s.oldLineNum++,s.newLineNum++;return i}for(let n=0;n<t;n++)i.push(renderContextLine({line:e[n],lineNum:s.newLineNum,lineNumWidth:r,dimDiff:o,nodeKey:"ctx-"+s.nodeKey++})),s.oldLineNum++,s.newLineNum++;const a=e.length-t-n;a>0&&(s.oldLineNum+=a,s.newLineNum+=a,i.push(Q.createElement(te,{key:"sep-"+s.nodeKey++},Q.createElement(ne,{color:mr.LINE_NUM,dimColor:o}," ".repeat(r+1)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:o},H_),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:o},`⋮ ${a} line${1===a?"":"s"}`))));for(let t=e.length-n;t<e.length;t++)i.push(renderContextLine({line:e[t],lineNum:s.newLineNum,lineNumWidth:r,dimDiff:o,nodeKey:"ctx-"+s.nodeKey++})),s.oldLineNum++,s.newLineNum++;return i}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const u=pt.diffLines(e,t);let d=0,m=0;for(const e of u)e.added&&(d+=e.count||1),e.removed&&(m+=e.count||1);const g=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),h=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),f=Math.max(3,(i+g-1).toString().length,(i+h-1).toString().length),y=groupAdjacentChanges(u),w=[],S={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<y.length;e++){const t=y[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===y[e-1].type,o=e<y.length-1&&"change"===y[e+1].type;if(!r&&!o){S.oldLineNum+=n.length,S.newLineNum+=n.length;continue}const s=r?Math.min(3,n.length):0,i=o?Math.min(3,Math.max(0,n.length-s)):0;w.push(...renderContextGroup({lines:n,leadCount:s,trailCount:i,lineNumWidth:f,dimDiff:a,counters:S}));continue}const{removedLines:n,addedLines:r}=t,o=buildLinePairs(n,r),s=new Map,i=new Map;for(const[e,t]of o){const o=pt.diffWordsWithSpace(n[e],r[t]);s.set(e,o),i.set(t,o)}for(let e=0;e<n.length;e++){const t=s.get(e);w.push(Q.createElement(te,{key:"rm-"+S.nodeKey++,width:"100%",backgroundColor:mr.REMOVED_BG},Q.createElement(ne,{color:mr.REMOVED_TEXT,dimColor:a}," "+S.oldLineNum.toString().padStart(f)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:a},H_),Q.createElement(ne,{color:mr.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):Q.createElement(ne,{color:mr.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),S.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);w.push(Q.createElement(te,{key:"add-"+S.nodeKey++,width:"100%",backgroundColor:mr.ADDED_BG},Q.createElement(ne,{color:mr.ADDED_TEXT,dimColor:a}," "+S.newLineNum.toString().padStart(f)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:a},H_),Q.createElement(ne,{color:mr.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):Q.createElement(ne,{color:mr.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),S.newLineNum++}}const E=void 0!==l&&w.length>l,C=E?w.slice(0,l):w;return{diffContent:Q.createElement(te,{flexDirection:"column"},o&&!r&&(d>0||m>0)&&Q.createElement(ne,{color:ar.GRAY},"Updated"," ",Q.createElement(ne,{color:ar.WHITE,bold:!0},n)," ","with"," ",d>0&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:fr.SUCCESS},d)," ","addition",1!==d?"s":"",m>0?" and ":""),m>0&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:fr.ERROR},m)," ","removal",1!==m?"s":"")),r&&Q.createElement(ne,{color:ar.RED},"Rejected update to",Q.createElement(ne,{color:ar.RED},` ${n}`)),Q.createElement(te,{flexDirection:"column",marginLeft:s,marginRight:s+4,width:(process.stdout.columns||80)-2*s-8},C)),isTruncated:E,totalLines:w.length}}function formatTodosForDisplay(e){const t=CE(e);return t?Q.createElement(te,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?Pe.checkboxOn:Pe.checkboxOff;let r,o=!1;switch(e.status){case"completed":r=fr.SUCCESS,o=!0;break;case"in_progress":r=fr.IN_PROGRESS;break;default:r=ar.WHITE}return Q.createElement(te,{key:e.id||t,flexDirection:"row"},Q.createElement(te,{width:2},Q.createElement(ne,{color:r},n)),Q.createElement(ne,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):Q.createElement(ne,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){if(!e)return e;if(t){const t=e.split(/[.\n]/)[0];return t?t+(e.includes(".")||e.includes("\n")?".":""):e}return n&&!r?truncateCommand({command:e}):e}function formatToolInput({input:e,isShell:t}){return Q.createElement(BracketWrap,null,t?e:Q.createElement(Markdown,null,e))}function parseReadSummaryLine(e){if(!e)return null;const t=e.split("\n")[0]?.trim();return t?t.match(CC):null}function getReadToolInlineSummary({name:e,summaryMatch:t}){if(!t||"READ"!==e)return null;const n=t[3]?Number(t[3]):void 0;return{dimText:void 0===n?void 0:`${n} ${1===n?"line":"lines"}`}}function renderReadToolInlineSummary(e){return e?.dimText?Q.createElement(ne,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:ar.YELLOW,symbol:Pe.arrowRight};if(t)return{symbolColor:ar.RED,symbol:Pe.square};if(n)return{symbolColor:ur,symbol:"✻"};if(r&&o){const e=CE(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?fr.SUCCESS:fr.WARNING,symbol:Pe.square}}return{symbolColor:pr.BG,symbol:Pe.square}}function renderToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:o,expandedOutput:s,expandKey:i,output:a}){if(e){const e=a?Math.max(1,Math.round(a.length/500)):1;return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ur},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&Q.createElement(BracketWrap,{color:ar.DIM},`${i}+o to expand`))}if(t)return Q.createElement(Q.Fragment,null,Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG,bold:!0},bT)),Q.createElement(ne,null," ","Using your taste"," ",n?"package of ":"packages",n&&Q.createElement(ne,{bold:!0},n)));let l=r;return"READ[n]"===r&&o&&(l=`READ[${Number(o[1])}]`),Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:pr.BG,color:pr.FG,bold:!0},`${ET}${l}${ET}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:o}){const s=`${formatTime2(r)} | ${formatTokens(o)}`;return"running"===e?Q.createElement(ne,{color:ar.GRAY},"Running (",s,")"):"interrupted"===e||"Interrupted by user"===n?Q.createElement(ne,{color:ar.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?Q.createElement(ne,{color:ar.RED,wrap:"wrap"},n," (",s,")"):Q.createElement(Q.Fragment,null,Q.createElement(ne,{wrap:"wrap"},"Done"),Q.createElement(ne,{color:ar.GRAY}," (",s,")"))}function getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}){if(n)return{text:e,isTruncated:!1,remainingLines:0,truncationMsg:null};const o=dedentText(e),{text:s,isTruncated:i,remainingLines:a}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?zo:Bo,maxChars:"Question"===t?1/0:Ko}),l=i&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?Q.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:ar.DIM}):Q.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:ar.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:o,isTruncated:s,truncationMsg:i}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return s?Q.createElement(Q.Fragment,null,o,"\n",i):o}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:o,expandKey:s}){const i=n?void 0:Ho,{diffContent:a,isTruncated:l,totalLines:u}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue,newValue:t.newValue,startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i});return Q.createElement(te,{flexDirection:"column"},a,l&&Q.createElement(te,{marginTop:1},Q.createElement(BracketedText,{text:`… (${u-Ho} more lines) [${s}+o to expand]`,color:ar.DIM})),r&&o&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.RED,wrap:"wrap"},o)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const o=t.content;if(!o)return Q.createElement(ne,{color:ar.GRAY},"Created"," ",Q.createElement(ne,{color:ar.WHITE,bold:!0},e)," ","(empty file)");const s=o.endsWith("\n")?o.slice(0,-1).split("\n"):o.split("\n"),i="number"==typeof t.totalLines?t.totalLines:s.length,a=n?void 0:Wo,l=void 0!==a&&i>a,u=l?s.slice(0,a):s,d=String(i).length;return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.GRAY},"Created"," ",Q.createElement(ne,{color:ar.WHITE,bold:!0},e)," ","(",i," line",1!==i?"s":"",")"),Q.createElement(te,{marginTop:1,flexDirection:"column"},u.map((e,t)=>Q.createElement(te,{key:t,width:"100%",backgroundColor:mr.ADDED_BG},Q.createElement(ne,{color:mr.ADDED_TEXT}," "+String(t+1).padStart(d)),Q.createElement(ne,{color:mr.LINE_NUM},H_),Q.createElement(ne,{color:mr.ADDED_TEXT,wrap:"truncate-end"},e.replace(/\s/g," "))))),l&&void 0!==a&&Q.createElement(te,{marginTop:1},Q.createElement(BracketedText,{text:`… (${i-a} more lines) [${r}+o to expand]`,color:ar.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:o,output:s,expandedOutput:i,isPermissionDenied:a,input:l,hasError:u,name:d,expandKey:m,showTreeConnector:g,closesFrame:h}){if(e)return formatTodosForDisplay(s);if(t)return i?Q.createElement(te,{width:"100%",flexDirection:"column"},Q.createElement(ne,null," "),Q.createElement(ne,{color:ur,wrap:"wrap",italic:!0},s)):null;const f=h?wT:ST;if(n&&o?.oldValue&&o?.newValue){const e=renderEditFileDiff({input:l,metadata:o,expandedOutput:i,isPermissionDenied:a,output:s,expandKey:m});return g?Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},f," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:i,expandKey:m});return g?Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},f," "),e):e}return g?renderTextWithLongConnector({output:s,name:d,expandedOutput:i,expandKey:m,hasError:u,closesFrame:h}):Q.createElement(te,{width:"100%"},Q.createElement(ne,{color:u?ar.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:d,expandedOutput:i,expandKey:m})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:o,closesFrame:s}){const{text:i,isTruncated:a,truncationMsg:l}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),u=o?ar.RED:void 0,d=buildTreeConnectors(i,{isTruncated:a,closesFrame:s}),m=s?wT:ST;return Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(te,{columnGap:1,width:"100%"},Q.createElement(ne,{color:Ar},d),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:u,wrap:"wrap"},i))),a&&Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},m," "),l))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,u="EDIT"===e,d="WRITE"===e,m="READ"===e||e.startsWith("READ[")&&e.endsWith("]"),g=!0===s?.isTasteFile,h=s?.tasteCategory,f=!0===s?.permissionDenied,y=!a&&!l&&!g,w="ctrl",S=!0===s?.isAgent,E=computeDisplayInput({input:t,isAgent:S,isShell:"SHELL"===e,expandedOutput:i}),C=!a&&E&&!g,v=s?.status,k=s?.tokensUsed||0,T="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0,_=m?parseReadSummaryLine(n):null,x=m?getReadToolInlineSummary({name:e,summaryMatch:_}):null,A=Boolean(n&&!g&&!S&&(!m||o)),{symbolColor:P,symbol:I}=resolveSymbol({isPending:r,hasError:o,isThinking:a,isTodos:l,output:n}),N=s?.preHookLines,R=s?.postHookLines,M=Boolean(N?.length),L=Boolean(R?.length),$=Boolean(s?.hookOutcome),D=r&&!S&&!$,O=!$&&!D,F=A&&!L&&!$&&!D,q=M&&!A&&!L&&!$&&!D;return Q.createElement(te,null,a&&Q.createElement(ne,{color:P},I),Q.createElement(te,{flexDirection:"column",marginLeft:a?1:0},Q.createElement(te,null,renderToolHeader({isThinking:a,isTasteFile:g,tasteCategory:h,name:e,summaryMatch:_,expandedOutput:i,expandKey:w}),C&&Q.createElement(ne,null," ",formatToolInput({input:E,isShell:"SHELL"===e})),renderReadToolInlineSummary(x)),S&&("running"===v||n)&&Q.createElement(te,{columnGap:1,marginLeft:y?1:0},y&&Q.createElement(ne,{color:Ar},wT," "),renderAgentStatus({agentStatus:v,hasError:o,output:n,elapsedSeconds:T,tokensUsed:k})),renderHookLines({lines:N,showTreeConnector:y,closesFrame:q}),A&&Q.createElement(te,{marginLeft:y?1:0},renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,isWriteFile:d,metadata:s,output:n,expandedOutput:i,isPermissionDenied:f,input:t,hasError:o,name:e,expandKey:w,showTreeConnector:y,closesFrame:F})),renderHookLines({lines:R,showTreeConnector:y,closesFrame:O}),renderHookOutcome({outcome:s?.hookOutcome,showTreeConnector:y}),D&&Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,{color:Ar},wT," "),Q.createElement(ne,{color:ar.GRAY},"Processing…"))))}function renderHookLines({lines:e,showTreeConnector:t,closesFrame:n=!1}){if(!e||0===e.length)return null;const r=e.length-1;return Q.createElement(te,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?wT:ST;return Q.createElement(te,{key:t,columnGap:1},Q.createElement(ne,{color:Ar},o),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.DIM},e)))}))}function renderHookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?ar.YELLOW:ar.RED;return Q.createElement(te,{columnGap:1,marginLeft:t?1:0},Q.createElement(ne,{color:Ar},wT),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:n},e.text)))}__name(computeSimilarity,"computeSimilarity"),__name(buildSimilarityMatrix,"buildSimilarityMatrix"),__name(collectSimilarityCandidates,"collectSimilarityCandidates"),__name(buildLinePairs,"buildLinePairs"),__name(groupAdjacentChanges,"groupAdjacentChanges"),__name(renderWordSegments,"renderWordSegments"),__name(renderContextLine,"renderContextLine"),__name(renderContextGroup,"renderContextGroup"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(formatToolInput,"formatToolInput"),__name(parseReadSummaryLine,"parseReadSummaryLine"),__name(getReadToolInlineSummary,"getReadToolInlineSummary"),__name(renderReadToolInlineSummary,"renderReadToolInlineSummary"),__name(resolveSymbol,"resolveSymbol"),__name(renderToolHeader,"renderToolHeader"),__name(renderAgentStatus,"renderAgentStatus"),__name(getTruncatedOutputParts,"getTruncatedOutputParts"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderWriteFileContent,"renderWriteFileContent"),__name(renderOutputContent,"renderOutputContent"),__name(renderTextWithLongConnector,"renderTextWithLongConnector"),__name(ToolMessage,"ToolMessage"),__name(renderHookLines,"renderHookLines"),__name(renderHookOutcome,"renderHookOutcome");var W_=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[o]=Y(0),[s,i]=Y(1);X(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&i(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session [shift+tab]",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],l=__name(e=>{const t=a.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),u=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),d=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),m=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,paddingX:1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0,color:ar.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&Q.createElement(te,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:s}).diffContent),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0},"Do you want to ",u()," ",Q.createElement(ne,{color:ar.CYAN},d()),"?")),Q.createElement(mt,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:o,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(ne,{color:t?ar.CYAN:ar.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?ar.CYAN:ar.WHITE,bold:!0},"shift+tab")):e.includes("(")?Q.createElement(Q.Fragment,null,e.split("(")[0],Q.createElement(ne,{color:ar.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Ot(),wn(),Rr();var G_=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=Y(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"),i=__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(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,paddingX:1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0,color:ar.YELLOW},"Execute Shell Command")),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",Q.createElement(ne,{color:ar.CYAN},i()),".")),e.workingDirectory&&Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.GRAY},"Working directory: ",e.workingDirectory)),e.description&&Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM,italic:!0},e.description)),Q.createElement(mt,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(ne,{color:t?ar.CYAN:ar.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?ar.CYAN:ar.WHITE,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function getKillShellRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}function getFileAction2(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:o,permissionMode:s,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const u="no"!==e.value;t(u),n(null),u?(o(a),"standard"===s&&i("Use shift+tab to enable auto-accept")):o(l)}__name(getKillShellRequest,"getKillShellRequest"),__name(getFileAction2,"getFileAction"),__name(handlePermissionResponse,"handlePermissionResponse");var V_=K(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:o,showHintMessage:s,handleToggleAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:o,setStatus:r,permissionMode:t,showHintMessage:s};if("shell_command"===e.toolName){const t=e.params;return Q.createElement(te,{marginY:1},Q.createElement(G_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"}),onToggleAutoAccept:i}))}if("kill_shell"===e.toolName){const t=getKillShellRequest(e.params);return Q.createElement(te,{marginY:1},Q.createElement(G_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"}),onToggleAutoAccept:i}))}const l=e.params,u={action:getFileAction2(e.toolName),filePath:String(l.filePath??l.file_path??l.path??l.absolutePath??l.notebook_path??"unknown"),description:`Allow ${e.toolName} operation`,oldContent:"edit_file"===e.toolName&&"string"==typeof l.oldContent?l.oldContent:void 0,newContent:"edit_file"===e.toolName&&"string"==typeof l.newContent?l.newContent:void 0};return Q.createElement(te,{marginY:1},Q.createElement(W_,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Ot(),Sb(),Ot(),Ot(),wn();var Q_=Ye`
|
|
281
|
+
`})])),b($w)}}),Zw=__esm({"../shared/src/database/schema/device-fingerprints.ts"(){Ot(),cd(),md(),ff(),yf(),Dw=pgEnum("device_fingerprint_source",["signup","api_key_create","checkout","session"]),c(Ow=gc("device_fingerprints",{id:uuid("id").defaultRandom().primaryKey(),userId:uuid("user_id").references(()=>nf.id,{onUpdate:"cascade",onDelete:"cascade"}).notNull(),thumbmark:text("thumbmark").notNull(),components:jsonb("components").default("{}").notNull(),ipAddress:text("ip_address"),userAgent:text("user_agent"),firstSource:Dw("first_source").notNull(),lastSource:Dw("last_source").notNull(),seenCount:integer("seen_count").default(1).notNull(),firstSeenAt:timestamp("first_seen_at",{withTimezone:!0}).defaultNow().notNull(),lastSeenAt:timestamp("last_seen_at",{withTimezone:!0}).defaultNow().notNull()},e=>[uniqueIndex("device_fingerprints_user_thumbmark_idx").on(e.userId,e.thumbmark),index("device_fingerprints_thumbmark_idx").on(e.thumbmark),index("device_fingerprints_user_id_idx").on(e.userId),pgPolicy("device_fingerprints_select_admin",{as:"permissive",to:"app_user",for:"select",using:sql`(public.current_user_is_app_admin())`}),pgPolicy("device_fingerprints_insert_admin",{as:"permissive",to:"app_user",for:"insert",withCheck:sql`(public.current_user_is_app_admin())`}),pgPolicy("device_fingerprints_update_admin",{as:"permissive",to:"app_user",for:"update",using:sql`(public.current_user_is_app_admin())`}),pgPolicy("device_fingerprints_delete_admin",{as:"permissive",to:"app_user",for:"delete",using:sql`(public.current_user_is_app_admin())`})])),b(Ow)}}),eS=__esm({"../shared/src/database/schema/index.ts"(){Ot(),wf(),Bw(),zw(),yf(),Hw(),Ww(),Gw(),Vw(),Qw(),Kw(),Yw(),Jw(),Xw(),Sf(),Zw()}}),tS=__esm({"../shared/src/database/config/database.ts"(){Ot(),Uw(),eS()}}),nS=__esm({"../shared/src/database/index.ts"(){Ot(),tS(),eS()}}),rS=__esm({"../shared/src/deals.ts"(){Ot()}}),oS=__esm({"../shared/src/index.ts"(){Ot(),Ms(),Ls(),$f(),Of(),Ff(),Qr(),qf(),jf(),Gf(),wn(),Ft(),Vf(),nS(),rS()}}),sS=__esm({"src/api/request.ts"(){Ot(),Ns(),Co(),Rs(),hs(),Oo(),co(),oS(),Fw=getPackageJson(),qw="string"==typeof Fw.version&&Fw.version.trim()?Fw.version:"unknown",jw=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,cliVersion:qw}),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 Es({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}if(r.end({statusCode:s.status}),e.onHeaders)try{e.onHeaders(s.headers)}catch{}return 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,i=getTelemetryEnv(),a="prod"===i?"production":i,l="1"===process.env.CMD_ZDR;return{"Content-Type":"application/json",[Ut.CLI_ENVIRONMENT]:a,...n?{Authorization:`Bearer ${n}`}:{},...s?{traceparent:s}:{},...e,[Ut.CLI_VERSION]:qw,...l?{[Ut.CMD_ZDR]:"1"}:{}}}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:Ss.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 getApiBaseUrl(){const e="true"===process.env.COMMANDCODE_SANDBOX,t=process.env.COMMANDCODE_API_URL;if(e&&t)return t;const n=process.argv.includes("--local"),r=process.argv.includes("--staging");return n?"http://localhost:9090":r?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}var iS,aS,lS,cS,uS,dS,mS,pS,gS,hS,fS=__esm({"src/api/utils.ts"(){Ot(),__name(getApiBaseUrl,"getApiBaseUrl")}}),yS=__esm({"../shared/src/constants/tools.ts"(){Ot(),iS={READ_FILE:"read_file",EDIT_FILE:"edit_file",WRITE_FILE:"write_file",READ_DIRECTORY:"read_directory",READ_MULTIPLE_FILES:"read_multiple_files",GREP:"grep",GLOB:"glob",SHELL_COMMAND:"shell_command",THINKING:"think",TODO_WRITE:"todo_write",QUESTION:"ask_user_question",EXPLORE:"explore",KILL_SHELL:"kill_shell",ENTER_PLAN_MODE:"enter_plan_mode",EXIT_PLAN_MODE:"exit_plan_mode",DIAGNOSTICS:"diagnostics",GET_SELF_KNOWLEDGE:"get_self_knowledge"},aS={WEB_SEARCH:"web_search",WEB_FETCH:"web_fetch"},lS=__name(e=>e===aS.WEB_SEARCH,"isWebSearchTool"),cS=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],uS=__name(({serverToolBlock:e,contentBlocks:t})=>{const n=e.toolCallId??e.id,r=e.toolName??e.name??"",o=t.find(e=>"tool-result"===e.type&&e.providerExecuted&&e.toolCallId===n);if(o)return"error-text"===o.output?.type||"error-json"===o.output?.type?{message:o.output?.value??"Error",isError:!0}:"string"==typeof o.output?.value&&o.output.value.trim()?{message:lS(r)?"Found results":"Content fetched",isError:!1}:{message:lS(r)?"Found 10 results":"Content fetched",isError:!1};const s=t.find(e=>("web_search_tool_result"===e.type||"web_fetch_tool_result"===e.type)&&e.tool_use_id===n);return cS.includes(s?.content?.type)?{message:`Error: ${s?.content?.error_code||"unknown_error"}`,isError:!0}:lS(r)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),dS=["create_file","delete_file",iS.EDIT_FILE,iS.WRITE_FILE,iS.SHELL_COMMAND],mS=[iS.SHELL_COMMAND]}}),wS=__esm({"src/mcp/constants.ts"(){Ot(),pS="2025-03-26",gS={name:"command-code",version:"1.0.0"},Promise.resolve().then(()=>(Co(),uo)).then(({getPackageJson:e})=>{gS.version=e().version??"1.0.0"}).catch(()=>{})}});function originOf(e){try{return new URL(e).origin}catch{return null}}function getTokenFilePath(){return e.join(S.homedir(),".commandcode",hS)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await v.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 v.mkdir(r,{recursive:!0}),await v.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await v.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],t.discoveredClients?.[e]&&delete t.discoveredClients[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,expectedUrl:t,refreshCallback:n}){const r=await getTokens(e);if(!r)return null;const o=originOf(t);if(!o)return dlog("[MCP] Refusing to attach token: invalid expectedUrl",t),null;if(!r.issuerUrl)return dlog(`[MCP] Stored token for "${e}" has no issuerUrl; refusing and clearing. Re-authenticate to continue.`),await deleteTokens(e),null;if(originOf(r.issuerUrl)!==o)return dlog(`[MCP] Refusing to attach token for "${e}": configured url ${o} does not match issuer ${r.issuerUrl}`),null;if(!isTokenExpired(r))return r.accessToken;if(r.refreshToken&&n)try{const t=await n(r.refreshToken);return await storeTokens(e,{...t,issuerUrl:r.issuerUrl}),t.accessToken}catch(t){return dlog("[MCP] Token refresh failed",t),await deleteTokens(e),null}return await deleteTokens(e),null}async function migrateLegacyTokens(e){const t=await loadTokenStorage(),n={bound:[],cleared:[]};let r=!1;for(const[o,s]of Object.entries(t.tokens)){if(s.issuerUrl)continue;const i=await e(o);i&&originOf(i)?(t.tokens[o]={...s,issuerUrl:i},n.bound.push(o),dlog(`[MCP] Migrated legacy token "${o}" → issuerUrl=${i}`)):(delete t.tokens[o],n.cleared.push(o),dlog(`[MCP] No trusted URL for legacy token "${o}"; cleared.`)),r=!0}return r&&await saveTokenStorage(t),n}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}async function deleteClientSecret(e){const t=await loadTokenStorage();return!!t.clientSecrets?.[e]&&(delete t.clientSecrets[e],await saveTokenStorage(t),!0)}async function storeDiscoveredClient(e,t){const n=await loadTokenStorage();n.discoveredClients||(n.discoveredClients={}),n.discoveredClients[e]=t,await saveTokenStorage(n)}async function getDiscoveredClient(e){const t=await loadTokenStorage();return t.discoveredClients?.[e]??null}var SS,ES,bS,CS=__esm({"src/mcp/auth/token-storage.ts"(){Ot(),wn(),Kn(),__name(originOf,"originOf"),hS="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(migrateLegacyTokens,"migrateLegacyTokens"),__name(listServersWithTokens,"listServersWithTokens"),__name(storeClientSecret,"storeClientSecret"),__name(getClientSecret,"getClientSecret"),__name(deleteClientSecret,"deleteClientSecret"),__name(storeDiscoveredClient,"storeDiscoveredClient"),__name(getDiscoveredClient,"getDiscoveredClient")}});function isSecureOrLoopback(e){try{const t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol&&("localhost"===t.hostname||"127.0.0.1"===t.hostname||"[::1]"===t.hostname)}catch{return!1}}var vS,kS,TS=__esm({"src/mcp/types.ts"(){Ot(),__name(isSecureOrLoopback,"isSecureOrLoopback"),SS=f.string().url().refine(isSecureOrLoopback,{message:"URL must use https:// (or http:// for loopback hosts)"}),ES=f.object({authorizationUrl:SS,tokenUrl:SS,clientId:f.string(),clientSecret:f.string().optional(),scopes:f.array(f.string()).optional()}),bS=f.preprocess(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;if("transport"in t)return t;if("type"in t){const{type:e,...n}=t;return{...n,transport:e}}return"string"==typeof t.command?{...t,transport:"stdio"}:"string"==typeof t.url?{...t,transport:"http"}:t},f.object({transport:f.enum(["stdio","http"]),enabled:f.boolean().default(!0),command:f.string().optional(),args:f.array(f.string()).optional(),url:f.string().url().optional(),headers:f.record(f.string(),f.string()).optional(),oauth:ES.optional(),env:f.record(f.string(),f.string()).optional()}).refine(e=>!e.oauth||!e.url||isSecureOrLoopback(e.url),{message:"OAuth requires the server url to use https:// (or http:// for loopback hosts)",path:["url"]})),f.object({mcpServers:f.record(f.string(),bS)})}});function getUserMcpConfigPath(){return e.join(S.homedir(),".commandcode",vS)}function getLocalMcpConfigPath(t=process.cwd()){const n=Fe(t);return e.join(S.homedir(),".commandcode","projects",n,vS)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,kS)}function getMcpConfigPath({scope:e,projectPath:t=process.cwd()}){switch(e){case"user":return getUserMcpConfigPath();case"local":return getLocalMcpConfigPath(t);case"project":return getProjectMcpConfigPath(t)}}function getAllMcpConfigPaths(e=process.cwd()){return[{scope:"user",path:getUserMcpConfigPath()},{scope:"project",path:getProjectMcpConfigPath(e)},{scope:"local",path:getLocalMcpConfigPath(e)}]}var _S=__esm({"src/mcp/config/scopes.ts"(){Ot(),wn(),vS="mcp.json",kS=".mcp.json",__name(getUserMcpConfigPath,"getUserMcpConfigPath"),__name(getLocalMcpConfigPath,"getLocalMcpConfigPath"),__name(getProjectMcpConfigPath,"getProjectMcpConfigPath"),__name(getMcpConfigPath,"getMcpConfigPath"),__name(getAllMcpConfigPaths,"getAllMcpConfigPaths")}});async function loadMcpConfig({scope:e,projectPath:t=process.cwd()}){try{const n=getMcpConfigPath({scope:e,projectPath:t}),r=await v.readFile(n,"utf-8"),o=JSON.parse(r);if(!o||"object"!=typeof o||!o.mcpServers||"object"!=typeof o.mcpServers)return null;const s={};for(const[e,t]of Object.entries(o.mcpServers)){const n=bS.safeParse(t);n.success?s[e]=n.data:dlog(`[MCP] Skipping invalid server "${e}"`,n.error.issues)}return{mcpServers:s}}catch(e){return"ENOENT"!==e?.code&&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 v.mkdir(s,{recursive:!0}),await v.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()}){const o=bS.safeParse(t);if(!o.success){const t=o.error.issues.map(e=>`${e.path.join(".")||"<root>"}: ${e.message}`).join("; ");throw new Error(`Invalid MCP server config for "${e}": ${t}`)}let s=await loadMcpConfig({scope:n,projectPath:r});s||(s={mcpServers:{}});let i=t;if("project"===n&&t.oauth?.clientSecret){await storeClientSecret(e,t.oauth.clientSecret);const{clientSecret:n,...r}=t.oauth;i={...i,oauth:r}}i={...i,enabled:i.enabled??!0},s.mcpServers[e]=i,await saveMcpConfig({config:s,scope:n,projectPath:r})}async function removeMcpServer({name:e,scope:t,projectPath:n=process.cwd()}){const r=await loadMcpConfig({scope:t,projectPath:n});return!!r?.mcpServers[e]&&(delete r.mcpServers[e],await saveMcpConfig({config:r,scope:t,projectPath:n}),!0)}async function updateMcpServerStatus({name:e,enabled:t,scope:n,projectPath:r=process.cwd()}){const o=await loadMcpConfig({scope:n,projectPath:r});return!!o?.mcpServers[e]&&(o.mcpServers[e]={...o.mcpServers[e],enabled:t},await saveMcpConfig({config:o,scope:n,projectPath:r}),!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)}))}var xS,AS,PS=__esm({"src/mcp/config/mcp-config.ts"(){Ot(),Kn(),CS(),TS(),_S(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(updateMcpServerStatus,"updateMcpServerStatus"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers")}}),IS=__esm({"src/mcp/client/stdio-transport.ts"(){Ot(),xS=class _StdioTransport extends qe{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=be(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)}}}});function fetchWithTimeout(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),AS);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var NS,RS=__esm({"src/mcp/fetch.ts"(){Ot(),AS=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}});function getBinNames(){const e=getPackageJson();return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name]:[NS]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||NS;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||NS}catch{return NS}}var MS,LS,$S=__esm({"src/cli/command-name.ts"(){Ot(),Co(),NS="cmd",__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName")}}),DS={};function generateRandomString(e){return N.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:N.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 i=new Promise((e,t)=>{o=e,s=t}),a=G.createServer((n,r)=>{const i=new g(n.url||"/",`http://${LS}:${e}`);if("/callback"===i.pathname){const e=i.searchParams.get("code"),n=i.searchParams.get("error"),a=i.searchParams.get("error_description");if(i.searchParams.get("state")!==t)r.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),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(a||n);r.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),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(a||n))}else e?(r.writeHead(200,{"Content-Type":"text/html",Connection:"close"}),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",Connection:"close"}),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,{Connection:"close"}),r.end("Not Found")});a.on("error",r),a.keepAliveTimeout=1,a.headersTimeout=5e3,a.listen(e,LS,()=>{n({server:a,getCode:__name(()=>i,"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 i=await s.json();return{accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?Date.now()+1e3*i.expires_in:void 0,tokenType:i.token_type,scope:i.scope}}async function refreshAccessToken({config:e,refreshToken:t}){const n=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId});e.clientSecret&&n.set("client_secret",e.clientSecret);const r=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});if(!r.ok){const e=await r.text();throw new Error(`Token refresh failed: ${r.status} ${e}`)}const 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,r){if(!isSecureOrLoopback(t))return{success:!1,error:`MCP server url must use https:// when OAuth is configured (got "${t}"). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]).`};const o=r?.port||MS,s=r?.timeout||12e4,i=r?.onStatus||(()=>{});let a=null;try{const r=generatePKCE(),l=generateRandomString(32),u=`http://${LS}:${o}/callback`;i("Starting authentication server...");const{server:d,getCode:m}=await startCallbackServer(o,l);a=d;const h=new g(n.authorizationUrl);if(h.searchParams.set("response_type","code"),h.searchParams.set("client_id",n.clientId),h.searchParams.set("redirect_uri",u),h.searchParams.set("state",l),h.searchParams.set("code_challenge",r.challenge),h.searchParams.set("code_challenge_method","S256"),n.scopes&&n.scopes.length>0&&h.searchParams.set("scope",n.scopes.join(" ")),n.extraParams)for(const[e,t]of Object.entries(n.extraParams))h.searchParams.set(e,t);i("Opening browser for authentication..."),await pe(h.toString()),i("Waiting for authorization...");const f=m();let y;const w=new Promise((e,t)=>{y=setTimeout(()=>t(new Error("Authentication timed out")),s)}),S=await Promise.race([f,w]);clearTimeout(y),i("Exchanging authorization code for tokens...");const E=await exchangeCodeForTokens(n,S,r.verifier,u);return await storeTokens(e,{...E,issuerUrl:t}),i("Authentication successful!"),{success:!0,tokens:E}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{a&&(a.closeIdleConnections?.(),a.closeAllConnections?.(),a.close(),a.unref())}}function createRefreshCallback(e){return t=>refreshAccessToken({config:e,refreshToken:t})}__export(DS,{DEFAULT_OAUTH_CALLBACK_PORT:()=>MS,LOCALHOST_IP:()=>LS,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var OS,FS,qS,jS=__esm({"src/mcp/auth/oauth-flow.ts"(){Ot(),CS(),RS(),TS(),MS=8085,LS="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")}}),US=__esm({"src/mcp/client/http-transport.ts"(){Ot(),TS(),wS(),CS(),RS(),$S(),OS=class _HttpTransport extends qe{constructor(e){if(super(),this.options=e,e.oauth&&!isSecureOrLoopback(e.url))throw new Error(`MCP server url must use https:// when OAuth is configured (got "${e.url}"). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]).`)}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":`${gS.name}/${gS.version}`,...this.options.headers};if(this.sessionId&&(e["Mcp-Session-Id"]=this.sessionId),this.options.serverName&&!this.options.oauth){const e=await getDiscoveredClient(this.options.serverName);e&&(this.options.oauth={authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,clientId:e.clientId,scopes:e.scopes})}if(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(()=>(jS(),DS));return t({config:this.options.oauth,refreshToken:e})},"refreshCallback"),n=await getValidAccessToken({serverName:this.options.serverName,expectedUrl:this.options.url,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(),AS);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){if(401===t.status&&this.options.serverName){const e=getInvokedCommandName(),t=this.options.oauth?"Re-authentication":"Authentication";throw new Error(`${t} required (HTTP 401) — Run: ${e} mcp auth ${this.options.serverName}`)}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")||"",i=await t.text();if(s.includes("text/event-stream")||i.startsWith("event:")||i.startsWith("data:")){const e=this.parseSSEResponse(i);if(e)return e;throw new Error("Failed to parse SSE response")}return JSON.parse(i)}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new Error("Request timed out");throw e}finally{clearTimeout(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(),AS);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}}}});function getMcpConnectionManager(){return qS||(qS=new FS),qS}var BS=__esm({"src/mcp/client/connection-manager.ts"(){Ot(),wS(),PS(),CS(),IS(),US(),zS(),FS=class extends qe{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 t=await migrateLegacyTokens(async t=>{const n=await loadMcpConfig({scope:"user",projectPath:e});return n?.mcpServers?.[t]?.url??null});t.cleared.length>0&&this.emit("legacyTokensCleared",t.cleared);const{config:n,serverScopes:r}=await loadMergedMcpConfig(e),o=[];for(const[e,t]of Object.entries(n.mcpServers)){if(!t.enabled)continue;const n=r.get(e);o.push(this.connectServer(e,t,n))}await Promise.allSettled(o),this.initialized=!0}async connectServer(e,t,n){const r={name:e,config:t,scope:n,transport:this.createTransport(t,e),status:"connecting",tools:[]};this.connections.set(e,r),this.emit("connecting",e);try{await r.transport.connect();const t=await this.initializeProtocol(r);if(r.serverInfo=t.serverInfo,r.capabilities=t.capabilities,r.transport instanceof xS?r.transport.notify("notifications/initialized"):await r.transport.notify("notifications/initialized"),t.capabilities.tools){const e=await this.fetchTools(r);r.tools=e.tools}r.status="connected",this.emit("connected",e,r.tools.length)}catch(t){r.status="error",r.error=t instanceof Error?t.message:String(t),this.listenerCount("error")>0&&this.emit("error",e,r.error)}}createTransport(e,t){return"stdio"===e.transport?xS.fromConfig(e):OS.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:pS,capabilities:{roots:{}},clientInfo:gS});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)}async ensureServerConnection(e,t=process.cwd()){const{config:n,serverScopes:r}=await loadMergedMcpConfig(t),o=n.mcpServers[e];if(!o)throw new Error(`Server '${e}' not found`);if(!1===o.enabled)throw new Error(`Server '${e}' is disabled`);if(this.connections.get(e))await this.reconnectServer(e);else{const t=r.get(e);if(!t)throw new Error(`Server '${e}' scope not found`);await this.connectServer(e,o,t)}const s=this.connections.get(e);if("error"===s?.status)throw new Error(s.error||"Connection failed")}get isInitialized(){return this.initialized}},qS=null,__name(getMcpConnectionManager,"getMcpConnectionManager")}});function mcpToolToSchema({serverName:e,tool:t}){const n=`mcp__${e}__${t.name}`,r=t.inputSchema||{},o=r.properties??{},s=r.required;return{name:n,description:t.description||`MCP tool: ${t.name} (from ${e})`,input_schema:{type:"object",properties:o,...s&&s.length>0?{required:s}:{}}}}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)}}}var zS=__esm({"src/mcp/client/tool-adapter.ts"(){Ot(),BS(),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool")}});function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",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}var HS,WS,GS,VS,QS,KS,YS,JS,XS,ZS,eE,tE,nE,rE,oE,sE,iE,aE,lE,cE,uE,dE,mE,pE,gE,hE,fE,yE,wE,SE,EE,bE,CE,vE,kE=__esm({"src/tools/utils/path-display.ts"(){Ot(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText")}}),TE={};function setPreHookLines(e,t){if(0===t.length)return;const n=e.metadata??{};n.preHookLines=t,e.metadata=n}function setPostHookLines(e,t){if(0===t.length)return;const n=e.metadata??{};n.postHookLines=t,e.metadata=n}function setHookOutcome(e,t){const n=e.metadata??{};n.hookOutcome=t,e.metadata=n}__export(TE,{FeedEntrySchema:()=>nE,LLM_STATUS_MESSAGES:()=>wE,createAgentToolEntry:()=>pE,createAssistantEntry:()=>sE,createBashEntry:()=>aE,createCommandResultEntry:()=>dE,createErrorEntry:()=>cE,createIDEStatusEntry:()=>mE,createInfoEntry:()=>oE,createSystemEntry:()=>lE,createTasteOnboardingEntry:()=>uE,createToolEntry:()=>iE,createUserEntry:()=>rE,formatError:()=>hE,getRandomLLMStatus:()=>SE,getToolDisplayName:()=>EE,getToolInputContent:()=>CE,isErrorEntry:()=>fE,isPendingEntry:()=>yE,parseTodosFromOutput:()=>vE,setHookOutcome:()=>setHookOutcome,setPostHookLines:()=>setPostHookLines,setPreHookLines:()=>setPreHookLines,updateEntryWithOutput:()=>gE});var _E,xE=__esm({"src/types/feed.ts"(){Ot(),yS(),zS(),kE(),as(),HS=f.object({id:f.string(),timestamp:f.number(),type:f.literal("image"),source:f.object({type:f.enum(["base64","url"]),media_type:f.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:f.string()})}),WS=f.object({id:f.string(),timestamp:f.number(),input:f.string(),output:f.string().optional(),metadata:f.record(f.string(),f.any()).optional(),images:f.array(HS).optional().default([])}),GS=WS.extend({role:f.literal("user")}),VS=WS.extend({role:f.literal("assistant")}),QS=WS.extend({role:f.literal("tool"),name:f.string(),description:f.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),KS=WS.extend({role:f.literal("bash"),command:f.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),YS=WS.extend({role:f.literal("system")}),JS=WS.extend({role:f.literal("error")}),XS=WS.extend({role:f.literal("info")}),ZS=WS.extend({role:f.literal("taste-onboarding")}),eE=WS.extend({role:f.literal("command-result"),hasError:f.boolean().optional(),details:f.string().optional()}),tE=WS.extend({role:f.literal("ide-status"),status:f.enum(["connected","installed","up_to_date","needs_reload","not_in_ide","failed"]),ide:f.string().nullable(),details:f.array(f.string()).optional()}),nE=f.discriminatedUnion("role",[GS,VS,QS,KS,YS,JS,XS,ZS,eE,tE]),__name(setPreHookLines,"setPreHookLines"),__name(setPostHookLines,"setPostHookLines"),__name(setHookOutcome,"setHookOutcome"),rE=__name((e,t)=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),oE=__name((e,t)=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),sE=__name(e=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),iE=__name((e,t,n)=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),aE=__name(e=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),lE=__name((e,t)=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e,metadata:t}),"createSystemEntry"),cE=__name(e=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),uE=__name(()=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),dE=__name((e,t=!1,n)=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),mE=__name((e,t,n)=>nE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),pE=__name(({name:e,input:t})=>{const n=Date.now();return nE.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"),gE=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return nE.parse(n)},"updateEntryWithOutput"),hE=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),fE=__name(e=>/^error:/i.test(e.output??""),"isErrorEntry"),yE=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),wE=["Pondering…","Contemplating…","Reasoning…","Reflecting…","Considering…","Deliberating…","Analyzing…","Evaluating…","Examining…","Inspecting…","Investigating…","Reviewing…","Researching…","Studying…","Exploring…","Mapping…","Tracing…","Parsing…","Processing…","Calculating…","Computing…","Synthesizing…","Planning…","Outlining…","Sketching…","Drafting…","Composing…","Crafting…","Building…","Assembling…","Constructing…","Designing…","Formulating…","Structuring…","Organizing…","Preparing…","Refining…","Polishing…","Honing…","Tuning…","Aligning…","Connecting…","Resolving…","Weaving…","Threading…","Sculpting…","Crystallizing…","Channeling…","Conjuring…","Brewing…","Working…","Cogitating…","Ruminating…","Hypothesizing…","Conceptualizing…","Philosophizing…","Deciphering…","Demystifying…","Articulating…","Illuminating…","Elaborating…","Orchestrating…","Choreographing…","Architecting…","Calibrating…","Materializing…","Visualizing…","Harmonizing…","Contemplificating…","Supercalifragilisting…","Bibbidibobbidibooing…","Abracadabraing…","Hocuspocusing…","Razzmatazzing…"],SE=__name(()=>wE[Math.floor(Math.random()*wE.length)],"getRandomLLMStatus"),EE=__name(e=>{switch(e){case iS.READ_FILE:return"READ";case iS.EDIT_FILE:return"EDIT";case iS.WRITE_FILE:return"WRITE";case iS.READ_DIRECTORY:return"LIST";case iS.READ_MULTIPLE_FILES:return"READ[n]";case iS.GREP:return"SEARCH";case iS.SHELL_COMMAND:return"SHELL";case iS.TODO_WRITE:return"TODOS";case iS.THINKING:return"thinking…";case aS.WEB_SEARCH:return"WEB SEARCH";case aS.WEB_FETCH:return"WEB FETCH";case iS.QUESTION:return"QUESTION";case iS.EXPLORE:return"EXPLORE";case iS.KILL_SHELL:return"KILL SHELL";default:if(isMcpTool(e)){const t=parseMcpToolName(e);if(t){const e=t.toolName.replace(/[-_]/g," ").toUpperCase();return`${t.serverName}: ${e} (MCP)`}}return e.replace(/_/g," ").toUpperCase()}},"getToolDisplayName"),bE=__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:Xo})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),CE=__name((e,t)=>{try{switch(e){case iS.READ_FILE:case iS.WRITE_FILE:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case iS.EDIT_FILE:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case iS.READ_DIRECTORY:return toRelativePath(t.path||"directory");case iS.GREP:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case iS.SHELL_COMMAND:if(t.command){const e=Array.isArray(t.args)&&t.args.length>0?` ${t.args.join(" ")}`:"string"==typeof t.args&&t.args?` ${t.args}`:"";return`${t.command}${e}`}return t.command||"";case iS.TODO_WRITE:let o;try{o="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=vE(o);return`${e?e.length:0} items`}catch{return"items"}case iS.THINKING:return t.content||"planning";case iS.READ_MULTIPLE_FILES:const s=t.include||[];if(!Array.isArray(s)||0===s.length)return"multiple files";const i=s.slice(0,es).map(toRelativePath).join(", "),a=s.length-es;return a>0?`${i} (+${a} more)`:i;case aS.WEB_SEARCH:return t.query||"search";case aS.WEB_FETCH:return t.url||"fetch";case iS.QUESTION:return"User answered questions";case iS.KILL_SHELL:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case iS.ENTER_PLAN_MODE:case iS.EXIT_PLAN_MODE:return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return bE(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:Zo})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),vE=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput")}});async function 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=Me.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=G.createServer((e,o)=>{const i=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],a=e.headers.origin||"",l=i.includes(a)?a:i[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 _E(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const i=e;if(!(i.apiKey&&i.state&&i.userId&&i.userName&&i.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(i.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const a={success:!0};o.writeHead(200),o.end(JSON.stringify(a)),n(i),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()})})}var AE,PE=__esm({"src/utils/auth/local-server.ts"(){Ot(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable"),_E=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}},__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer")}});function generateStateToken(){return N.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await pe(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:cs.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(yn()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await v.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 v.writeFile(n,r,{mode:384}),await v.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await v.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}var IE,NE,RE,ME=__esm({"src/utils/auth/auth-flow.ts"(){Ot(),PE(),Sn(),Rn(),hs(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl"),AE=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}},__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials")}});async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${Bt.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:cs.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=IE}=e,[s,i]=Y("initializing"),[a,l]=Y("Starting authentication..."),[u,d]=Y(""),[m,g]=Y(null),h=J(null),f=J(!1),y=J(!1),w=J(null),S=J(null),E=J(t),C=J(n),v=J(r);X(()=>{E.current=t,C.current=n,v.current=r});const k=ee(()=>{w.current&&(clearTimeout(w.current),w.current=null),S.current&&(clearTimeout(S.current),S.current=null),h.current&&(stopServer(h.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),h.current=null)},[]),T=ee(()=>{y.current||(y.current=!0,f.current=!0,k(),v.current())},[k]),_=ee((e,t)=>{y.current||(y.current=!0,k(),E.current(e,t))},[k]),x=ee((e,t)=>{y.current||(y.current=!0,k(),C.current(e,t))},[k]),A=ee(async e=>{const t=sanitizeApiKey(e);if(!t)return;i("validating"),l("Validating API key...");const n=await validateApiKey(t);if(f.current)return;if(y.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return i("invalid_key"),l(e),void(w.current=setTimeout(()=>{f.current||y.current||(i("manual_entry"),l("Paste a valid API key below.")),w.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(y.current)return;await storeCredentials(e),i("success"),_(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:cs.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),l("Failed to save API key. Please try again."),i("manual_entry")}},[_]);return X(()=>{let e=!0;return __name(async()=>{if(!f.current)try{const t=await findAvailablePort(NE,RE);if(!e||f.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);g(r);const{server:s,waitForCallback:a}=createAuthServer(t,n);if(h.current=s,!e||f.current)return void await stopServer(s);i("waiting_browser"),l("Complete login in your browser...");const u=await openBrowser(r);if(!e||f.current)return;if(!u)return k(),l("Could not open browser. Paste your API key below."),void i("manual_entry");const d=new Promise((e,t)=>{S.current=setTimeout(()=>{S.current=null,t(new AE("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([a,d]);if(!e||f.current)return;if(y.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(y.current)return;if(await storeCredentials(n),!e||f.current||y.current)return;i("browser_success"),_(n,"browser")}catch(t){if(y.current)return;if(!e||f.current)return;if(t instanceof _E)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:cs.AUTH_FLOW,heading:"Authorization denied by user"}}),i("denied"),void x("denied","Authorization denied by user.");k(),t instanceof AE&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:cs.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:cs.AUTH_FLOW,heading:"Browser auth failed"}}),l("Browser auth failed. Paste your API key below.")),i("manual_entry")}}catch(t){if(y.current)return;if(!e||f.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:cs.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),k(),i("manual_entry"),l("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,k()}},[o,_,x,k]),{authState:s,statusMessage:a,browserUrl:m,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:A,cancel:T,hasCompleted:y.current}}var LE=__esm({"src/tui/hooks/use-auth-flow.ts"(){Ot(),ME(),PE(),fS(),wn(),hs(),IE=12e4,NE=5959,RE=10,__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow")}});function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){return"waiting_browser"===e?"Authorize in browser, or paste API key here":"invalid_key"===e?"That key was invalid. Try again.":"Paste your API key and press Enter"}function getAuthUrlLabel(e){return"waiting_browser"===e?"Login: ":"Get API key: "}var $E,DE,OE,FE=__esm({"src/utils/auth/auth-status.ts"(){Ot(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel")}}),qE=__esm({"src/tui/auth-flow-ui.tsx"(){Ot(),$r(),FE(),Rr(),Xr(),($E=Q.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:o})=>{const s="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,i=t&&("waiting_browser"===e||"manual_entry"===e);return Q.createElement(Q.Fragment,null,s&&Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?ar.YELLOW:ar.GRAY,paddingX:1},Q.createElement(ne,{color:ar.DIM},"API Key: "),Q.createElement(te,{flexGrow:1},Q.createElement(TextInput,{value:n,onChange:r,onSubmit:o,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},getAuthHelpText(e))),i&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},getAuthUrlLabel(e)),Q.createElement(Kr,{url:t,text:"Open login page ↗",color:ar.CYAN,dimColor:!0}))),"validating"===e&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Ctrl+C to cancel")))})).displayName="AuthInputSection",DE=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const i=__name(()=>{switch(e){case"initializing":case"validating":default:return Q.createElement(je,{type:"dots"});case"waiting_browser":return Q.createElement(ne,{color:ar.CYAN},Pe.ellipsis);case"browser_success":case"success":return Q.createElement(ne,{color:ar.GREEN},Pe.tick);case"denied":case"invalid_key":return Q.createElement(ne,{color:ar.RED},Pe.cross);case"manual_entry":return Q.createElement(ne,{color:ar.YELLOW},Pe.arrowDown);case"error":return Q.createElement(ne,{color:ar.RED},Pe.warning)}},"getStatusIcon"),a=__name(()=>getAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:Q.createElement(te,{flexDirection:"column",paddingY:1},Q.createElement(te,{marginBottom:1},Q.createElement(te,{marginRight:1},i()),Q.createElement(ne,{color:a()},t)),Q.createElement($E,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s}))},"AuthFlowUI")}}),jE=__esm({"src/tui/login-with-api-key.tsx"(){Ot(),LE(),qE(),OE=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i,cancel:a}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return se((e,t)=>{t.ctrl&&"c"===e&&a()}),Q.createElement(DE,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:i})},"LoginWithApiKey")}});function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${ue.bgGreen(ue.black(` ${e} `))}${o}`:n?`${ue.bgBlack(ue.white(` ${e} `))}${o}`:`${ue.bold(ue.bgCyan(ue.black(` ${e} `)))}${o}`}var UE=__esm({"src/utils/heading.ts"(){Ot(),__name(heading,"heading")}});async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=On.createAuthorizationUrl(),r=await ze({message:"Open the Anthropic auth page?",initialValue:!0});if(Ve(r))return{success:!1,error:"Anthropic authentication cancelled"};console.log(),console.log(ue.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log(),!0===r?(await pe(e),console.log(ue.yellow(" Copy your authorization code and paste it below.")),console.log()):(console.log(ue.yellow(" Open the URL above and copy your authorization code below.")),console.log());const o=await Qe({message:"Paste your authorization code:",mask:"*"});if(Ve(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 On.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}var BE=__esm({"src/commands/auth/anthropic-auth.ts"(){Ot(),Wn(),ro(),__name(performAnthropicAuth,"performAnthropicAuth")}});async function performCodexAuth(){try{const e=await ze({message:"Open browser to sign in with ChatGPT (Codex)?",initialValue:!0});return Ve(e)?{success:!1,error:"Codex authentication cancelled"}:(await Gn.login({onAuth:__name(({authorizeUrl:t})=>{console.log(),!0===e?pe(t).catch(()=>{console.log(ue.dim(" Could not auto-open browser.")),console.log(` ${createOSC8Link(t,"Open auth page ↗")}`)}):console.log(` ${createOSC8Link(t,"Open auth page ↗")}`),console.log()},"onAuth"),onProgress:__name(e=>{console.log(` ${ue.dim(Pe.circleFilled)} ${ue.dim(e)}`)},"onProgress")}),{success:!0})}catch(e){const t=e instanceof Error?e.message:"Unknown error";return dlog("[CodexAuth] performCodexAuth failed",{error:t}),{success:!1,error:t}}}var zE=__esm({"src/commands/auth/codex-auth.ts"(){Ot(),Yn(),ro(),Kn(),__name(performCodexAuth,"performCodexAuth")}});async function performCopilotAuth(){try{const e=await ze({message:"Open GitHub to authorize Copilot access?",initialValue:!0});return Ve(e)?{success:!1,error:"Copilot authentication cancelled"}:(await Vn.login({onAuth:__name(({userCode:t,verificationUri:n})=>{console.log(),console.log(ue.yellow(` Enter this code on GitHub: ${ue.bold(t)}`)),console.log(),!0===e?pe(n).catch(()=>{console.log(ue.dim(` Open: ${n}`))}):(console.log(ue.dim(" Open this URL in your browser:")),console.log(` ${n}`),console.log())},"onAuth"),onProgress:__name(e=>{console.log(` ${ue.dim(Pe.circleFilled)} ${ue.dim(e)}`)},"onProgress")}),{success:!0})}catch(e){const t=e instanceof Error?e.message:"Unknown error";return dlog("[CopilotAuth] performCopilotAuth failed",{error:t}),{success:!1,error:t}}}var HE=__esm({"src/commands/auth/copilot-auth.ts"(){Ot(),Jn(),Kn(),__name(performCopilotAuth,"performCopilotAuth")}});async function trackLifecycleEvent({eventType:e,metadata:t}){if(isTelemetryEnabled())try{const n=getApiBaseUrl(),r=new jw({baseUrl:n});await r.post({endpoint:Bt.ALPHA.LIFECYCLE_EVENTS.TRACK,body:{eventType:e,metadata:t}}),dlog("[lifecycle-event tracked]",{eventType:e})}catch(t){dlog("[lifecycle-event failed]",{eventType:e,error:t})}}var WE,GE=__esm({"src/api/track-lifecycle-event.ts"(){Ot(),sS(),fS(),wn(),Kn(),co(),__name(trackLifecycleEvent,"trackLifecycleEvent")}});async function hasBeenInstalled(){try{return!0===(await loadUserConfig()).installed}catch{return!1}}async function markAsInstalled(){try{await updateUserConfig({installed:!0})}catch(e){dlog("[detect-first-install] failed to mark as installed",{error:e})}}async function detectAndTrackFirstInstall(){if(!await hasBeenInstalled())return WE||(WE=(async()=>{try{const e=getPackageJson().version||"unknown";await trackLifecycleEvent({eventType:"cli_installed",metadata:{cliVersion:e}}),await markAsInstalled(),dlog("[detect-first-install] tracked first install")}catch(e){dlog("[detect-first-install] failed to track",{error:e})}finally{WE=null}})())}var VE,QE,KE,YE,JE,XE,ZE,eb=__esm({"src/utils/detect-first-install.ts"(){Ot(),GE(),Co(),Kn(),Jr(),WE=null,__name(hasBeenInstalled,"hasBeenInstalled"),__name(markAsInstalled,"markAsInstalled"),__name(detectAndTrackFirstInstall,"detectAndTrackFirstInstall")}}),tb=__esm({"src/commands/auth/errors.ts"(){Ot(),VE=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},QE=class extends Error{static{__name(this,"AuthorizationDeniedError")}constructor(e){super(e),this.name="AuthorizationDeniedError"}}}});function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,i]=Y("loading"),[a,l]=Y(null);return X(()=>{n().then(e=>{l(e),i(o?"success":"done")})},[n,o]),X(()=>{if("done"===s&&null!==a&&r(a),"success"===s&&null!==a){const e=setTimeout(()=>r(a),100);return()=>clearTimeout(e)}},[s,a,r]),"done"===s?null:Q.createElement(JE,null,"loading"===s?Q.createElement(KE,{message:e}):Q.createElement(YE,{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 buildAlreadyLoggedInMessage(e){return formatAlreadyLoggedInStyled(e)}function buildSuccessMessage(e,t){return formatLoginSuccessStyled({userName:e,authFileName:t})}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 QE(e.message):isLoginCancelled(e)?new VE(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 isCopilotProvider(e){return"github-copilot"===e}function isCodexProvider(e){return"codex"===e}function isUserCancellation(e){return e instanceof VE||e instanceof QE}function getErrorMessage2(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),Ue.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await Ge({message:"Select provider",options:e});if(Ve(t))throw We(`${Pe.cross} No provider selected.`),new VE("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){We(`${Pe.cross} ${e}`)}function showAnthropicAuthNote(){He("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=>{i(),o(e)},"handleComplete"),{unmount:i}=ie(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}=ie(Q.createElement(OE,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=ie(Q.createElement(XE,{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 handleProviderAuth(e){if(dlog("[Auth] handleProviderAuth",e),isAnthropicProvider(e))return showAnthropicAuthNote(),void await performAnthropicAuth();if(isCopilotProvider(e))return dlog("[Auth] starting copilot auth flow"),He("Command Code authentication complete. Now authenticating with GitHub Copilot..."),void await performCopilotAuth();if(isCodexProvider(e)){dlog("[Auth] starting codex auth flow"),He("Command Code authentication complete. Now authenticating with ChatGPT (Codex)...");const e=await performCodexAuth();if(!e.success)throw new Error(e.error??"Codex authentication failed")}}async function finalizeLogin(e,t,n){await saveConfigWithSpinner(e),printMessage(buildSuccessMessage(t,getAuthFileName(n)))}async function runLogin(){const e=yn(),t=await checkAuthWithSpinner(e);if(t.isAuthenticated)return printMessage(buildAlreadyLoggedInMessage(t.userName)),!0;showAuthIntro();const n=await executeLoginFlow();detectAndTrackFirstInstall().catch(()=>{});let r="command-code";return isInternalTeamFlagEnforced()&&(r=await selectProvider(),await handleProviderAuth(r)),await finalizeLogin(r,n,e),!0}async function loginAction(){try{await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${Pe.cross} Login failed:`,getErrorMessage2(e)),process.exit(1)}}var nb=__esm({"src/tui/auth/login.tsx"(){Ot(),wn(),jE(),Hn(),Sn(),UE(),io(),Jr(),BE(),zE(),HE(),Kn(),eb(),tb(),Ns(),ws(),Rr(),KE=__name(({message:e})=>Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.CYAN},Q.createElement(je,{type:"dots"})),Q.createElement(ne,null," ",e)),"LoadingIndicator"),YE=__name(({message:e})=>Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.GREEN},Pe.tick),Q.createElement(ne,null," ",e)),"SuccessIndicator"),JE=__name(({children:e})=>Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,null," "),Q.createElement(te,null,e)),"StatusContainer"),__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__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(isCopilotProvider,"isCopilotProvider"),__name(isCodexProvider,"isCodexProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage2,"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"),XE=__name(({env:e,onComplete:t})=>{const[n,r]=Y("checking"),[o,s]=Y(null);return X(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),X(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),Q.createElement(JE,null,"checking"===n&&Q.createElement(KE,{message:"Checking authentication status..."}),"logged_in"===n&&Q.createElement(YE,{message:"Authenticated"}),"not_logged_in"===n&&Q.createElement(YE,{message:"Ready to log in"}))},"AuthCheckSpinner"),__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleProviderAuth,"handleProviderAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction"),ZE=new Ie("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction)}});async function safeRemoveFile(e,t){try{return await k.unlink(e),{existed:!0}}catch(e){return"ENOENT"===e.code?{existed:!1}:{existed:!0,warning:`Could not remove ${t}: ${e.message}`}}}function collectWarnings(...e){return e.map(e=>e.warning).filter(e=>void 0!==e)}async function performLogout(){try{const e=await safeRemoveFile(getAuthFile(),"auth file"),t=collectWarnings(e);return{success:!0,wasAuthenticated:e.existed,warnings:t}}catch(e){return{success:!1,wasAuthenticated:!1,warnings:[],error:e instanceof Error?e.message:"Unknown error"}}}var rb,ob,sb,ib,ab,lb,cb=__esm({"src/utils/auth/logout.ts"(){Ot(),Rn(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout")}});function printWarnings(e){e.length>0&&(console.warn(ue.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(ue.yellow(` - ${e}`))))}async function renderLogoutUI(){let e;try{const t=await getUserName();e=t||void 0}catch{e=void 0}return new Promise(t=>{const{unmount:n}=ie(Q.createElement(ab,{onComplete:e=>{n(),t(e)},userName:e}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}var ub,db,mb,pb,gb,hb,fb=__esm({"src/tui/auth/logout.tsx"(){Ot(),cb(),fs(),Rr(),ws(),rb=__name(({userName:e})=>{const t=e?`Logging out ${e}...`:"Logging out...";return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.CYAN},Q.createElement(je,{type:"dots"})),Q.createElement(ne,null," ",t))},"LoadingIndicator"),ob=__name(({userName:e,wasAuthenticated:t})=>{const n=!1===t?"Not currently authenticated":formatLogoutSuccess(e);return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.GREEN},Pe.tick),Q.createElement(ne,null," ",n))},"SuccessIndicator"),sb=__name(({errorMessage:e})=>Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.RED},Pe.cross),Q.createElement(ne,{color:ar.RED}," Logout failed: ",e)),"ErrorIndicator"),ib=__name(({status:e,errorMessage:t,userName:n,wasAuthenticated:r})=>"loading"===e?Q.createElement(rb,{userName:n}):"success"===e?Q.createElement(ob,{userName:n,wasAuthenticated:r}):Q.createElement(sb,{errorMessage:t}),"StatusDisplay"),ab=__name(({onComplete:e,userName:t})=>{const[n,r]=Y("loading"),[o,s]=Y(""),[i,a]=Y(null);return X(()=>{performLogout().then(e=>{a(e),e.success?r("success"):(s(e.error||"Unknown error"),r("error"))})},[]),X(()=>{if(("success"===n||"error"===n)&&i){const t=setTimeout(()=>e(i),100);return()=>clearTimeout(t)}},[n,i,e]),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,null," "),Q.createElement(te,null,Q.createElement(ib,{status:n,errorMessage:o,userName:t,wasAuthenticated:i?.wasAuthenticated})))},"LogoutSpinner"),__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction"),lb=new Ie("logout").description("Log out of Command Code").allowUnknownOption().allowExcessArguments().action(logoutAction)}}),yb=__esm({"src/commands/auth/index.ts"(){Ot(),nb(),fb(),Ns(),tb(),Ns(),fb(),ws(),nb(),BE(),HE(),Sn(),Rn(),new Ie("auth").description("Manage authentication with Command Code").addCommand(ZE).addCommand(lb).addCommand(ys)}});function ensureSession(){if(!mb){mb=!0;try{j(r(db),{recursive:!0});const e=`\n=== SESSION ${(new Date).toISOString()} pid=${process.pid} cols=${process.stdout.columns??"?"} rows=${process.stdout.rows??"?"} ===\n`;W(db,e,"utf-8")}catch{}}}function emit(e,t){if(!ub)return;ensureSession();const n=++pb,r=Date.now()-gb,o=process.stdout.columns??0,s=[`+${r.toString().padStart(7)}ms`,`#${n.toString().padStart(5)}`,e.padEnd(14),`cols=${o}`];for(const[e,n]of Object.entries(t)){const t="string"==typeof n?JSON.stringify(n):String(n);s.push(`${e}=${t}`)}try{W(db,s.join(" ")+"\n","utf-8")}catch{}}var wb,Sb=__esm({"src/utils/resize-flicker-debug.ts"(){Ot(),ub="1"===process.env.CMD_FLICKER_DEBUG,db=process.env.CMD_FLICKER_LOG??n(C(),".commandcode","logs","flicker.log"),mb=!1,pb=0,gb=Date.now(),__name(ensureSession,"ensureSession"),__name(emit,"emit"),hb={enabled:ub,logFile:db,resize(e){emit("RESIZE",e)},clearConsole(){emit("CLEAR_CONSOLE",{})},statusRender(e){emit("STATUS_RENDER",e)},custom(e,t){emit(e,t)}}}}),Eb=__esm({"src/utils/clear-console.ts"(){Ot(),Sb(),wb=__name(()=>{hb.clearConsole(),process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H")},"clearConsole")}});async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new jw({baseUrl:e});return await t.get({endpoint:Bt.ALPHA.WHOAMI})}var bb=__esm({"src/utils/get-entity.ts"(){Ot(),fS(),sS(),wn(),__name(getAuthenticatedEntity,"getAuthenticatedEntity")}}),Cb={};function isModelPremium(e){const t=Object.values(sn).find(t=>t.id===e);return!!t&&"premium"===getModelCategory({provider:t.provider,model:e})}async function getBillingLink({billingLink:e,setBillingLink:t}){if(e)return e;try{const e=await getAuthKey();if(!e)return;const n=await getAuthenticatedEntity();if(e.startsWith("user_")){const e=`https://commandcode.ai/${n.user.userName}/settings/billing`;return t(e),e}if(n.org){const e=`https://commandcode.ai/${n.org.login}/settings/billing`;return t(e),e}}catch{return"https://commandcode.ai/settings/billing"}}async function handleSubmit({role:e,input:t,images:n,ideContext:r,ideHint:o,displayMessage:s,isAutomated:i,hiddenMessages:a,feed:l,setFeed:u,isCmdCodeBusy:d,setIsCmdCodeBusy:m,setQueuedMessages:g,setStatus:h,setInteractionTokens:f,updateStatus:y,setUpdateStatus:w,billingLink:S,setBillingLink:E,currentModel:C,premiumCreditsExhausted:v,setPremiumCreditsExhausted:k,setCurrentModel:T,contextEngineRef:_,isSubmittingRef:x,setInput:A,setStaticKey:P,executeBash:I}){if(!t.length)return;if(y&&w(null),f(0),"bash"===e){if(x.current)return;x.current=!0;const e=aE(t);return u([...l,e]),A(""),await I(t,e=>{u(e)},()=>{wb(),P(e=>e+1)}),void(x.current=!1)}if(d)return g(e=>[...e,{input:t,displayMessage:s,isAutomated:i,hiddenMessages:a}]),void A("");if(x.current)return;x.current=!0,m(!0),h(SE()),A("");let N=!1;if(v&&C&&isModelPremium(C))return N=!0,h("Premium credits exhausted"),u(e=>[...e,oE("Premium model requests already consumed. Pick a standard model instead.\nRun /upgrade to check plans or /extra to buy on-demand credits")]),m(!1),void(x.current=!1);try{if(_.current){const e=i||a?{...i?{isAutomated:!0}:{},...a?{hiddenMessages:a}:{}}:void 0;await _.current.sendMessage(t,n,r,s,e,o)}}catch(e){const t=e instanceof Error?e.message:"An unexpected error occurred",n=e instanceof Error?e.name:"",r=null!==e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"";if("Interrupted by user"===t||t.toLowerCase().includes("interrupt")||t.toLowerCase().includes("abort")||"InterruptedError"===n||"AbortError"===n||"ECONNABORTED"===r)return void(N=!0);if(N=!0,"Insufficient credits"===t){h("Insufficient credits");const e=`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${await getBillingLink({billingLink:S,setBillingLink:E})}`;return void u(t=>[...t,cE(e)])}if("Premium credits exhausted"===t){k?.(!0);const e=sn.KIMI_K2_5.id;return await setSelectedModel({model:e}),T?.(e),wb(),P(e=>e+1),h("Switched to Kimi K2"),void u(e=>[...e,oE("Auto switched model to Kimi K2. Plan Premium requests used.\n`/upgrade` plan or buy `/extra` on-demand credits")])}if(t.startsWith("Model not in plan:")){const e=t.slice(19);return h("Model not available"),void u(t=>[...t,oE(`${e}\nRun /upgrade to check plans or /extra to buy on-demand credits`)])}if(t.startsWith("Error:"))return h("Error"),void u(e=>[...e,cE(t)]);h("Error"),u(e=>[...e,cE(t)])}finally{m(!1),N||h("Ready..."),x.current=!1}}__export(Cb,{getBillingLink:()=>getBillingLink,handleSubmit:()=>handleSubmit});var vb,kb=__esm({"src/tui/actions/submit.ts"(){Ot(),xE(),yb(),bb(),wn(),Jr(),Eb(),__name(isModelPremium,"isModelPremium"),__name(getBillingLink,"getBillingLink"),__name(handleSubmit,"handleSubmit")}});function isCorruptedArchiveError(e){const t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("zlib")||t.includes("unexpected end")||t.includes("tar_bad_archive")||t.includes("unrecognized archive")||t.includes("invalid tar header")}async function clearGigetCache(e,n){const r=t.join(S.homedir(),".cache","giget","gh",`${e}-${n}`);await k.rm(r,{recursive:!0,force:!0}).catch(()=>{})}async function cleanupStaleTempDirectories(){try{const e=S.tmpdir(),n=await k.readdir(e,{withFileTypes:!0}),r=Date.now();for(const o of n)if(o.isDirectory()&&(o.name.startsWith("commandcode-skill-")||o.name.startsWith("commandcode-skill-discovery-")))try{const n=t.join(e,o.name);r-(await k.stat(n)).mtimeMs>vb&&await k.rm(n,{recursive:!0,force:!0})}catch(e){}}catch(e){}}function wrapFetchError(e,t,n){const r=e instanceof Error?e.message:String(e),o=r.toLowerCase();return o.includes("could not find commit hash")||o.includes("not found")||o.includes("404")?new Error(`Repository "${t}/${n}" not found on GitHub.\nIf the repo doesn't use "main" branch, specify the branch: ${t}/${n}@<branch>`):o.includes("403")||o.includes("401")||o.includes("forbidden")||o.includes("unauthorized")||o.includes("could not download")?new Error(`Repository "${t}/${n}" is private or inaccessible.\nSkills can only be installed from public repositories.`):o.includes("enotfound")||o.includes("econnrefused")||o.includes("etimedout")?new Error("Network error: unable to reach GitHub. Check your internet connection."):o.includes("zlib")||o.includes("unexpected end")||o.includes("tar_bad_archive")||o.includes("unrecognized archive")||o.includes("invalid tar header")?new Error(`Download of "${t}/${n}" failed (corrupted archive).\nThis is usually a transient GitHub issue. Please try again.`):new Error(`Failed to fetch "${t}/${n}": ${r}`)}var Tb,_b,xb=__esm({"src/services/skill-utils.ts"(){Ot(),vb=864e5,__name(isCorruptedArchiveError,"isCorruptedArchiveError"),__name(clearGigetCache,"clearGigetCache"),__name(cleanupStaleTempDirectories,"cleanupStaleTempDirectories"),__name(wrapFetchError,"wrapFetchError")}}),Ab={};async function findSkillMdFiles(e){const{dir:n,maxDepth:r=5,currentDepth:o=0,relativePath:s="",foundCount:i={value:0}}=e;if(o>r)return[];if(i.value>=Tb)return[];const a=[];try{const e=await k.readdir(n,{withFileTypes:!0}),l=e.find(e=>("SKILL.md"===e.name||"skill.md"===e.name)&&e.isFile());if(l){const e=t.join(n,l.name);try{if((await k.stat(e)).size>_b);else{const r=await k.readFile(e,"utf-8"),{data:o}=Ke(r),l=s.split("/").filter(Boolean),u=l[l.length-1]||t.basename(n);a.push({name:o.name||u,path:s||".",description:o.description}),i.value++}}catch(e){process.env.DEBUG&&console.error(`Failed to parse SKILL.md at ${s||"."}: ${e instanceof Error?e.message:String(e)}`)}}const u=e.filter(e=>e.isDirectory());for(const e of u){if("node_modules"===e.name||".git"===e.name||"dist"===e.name||"build"===e.name||".next"===e.name)continue;const l=t.join(n,e.name),u=s?`${s}/${e.name}`:e.name,d=await findSkillMdFiles({dir:l,maxDepth:r,currentDepth:o+1,relativePath:u,foundCount:i});a.push(...d)}}catch(e){process.env.DEBUG&&console.error(`Failed to read directory ${s||"."}: ${e instanceof Error?e.message:String(e)}`)}return a}async function discoverSkillsLocally(e){const{owner:n,repo:r,path:o,branch:s,keepTempDir:i=!1}=e;await cleanupStaleTempDirectories();const a=t.join(S.tmpdir(),`commandcode-skill-discovery-${M()}`);try{await k.mkdir(a,{recursive:!0});let e=`gh:${n}/${r}`;o&&(e+=`/${o}`),s&&(e+=`#${s}`);const{downloadTemplate:t}=await import("giget");try{await t(e,{dir:a,force:!0,silent:!0})}catch(o){if(!isCorruptedArchiveError(o))throw o;await clearGigetCache(n,r),await t(e,{dir:a,force:!0,silent:!0})}const l=await findSkillMdFiles({dir:a,maxDepth:5});return i?{skills:l,tempDir:a}:(await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),{skills:l})}catch(e){throw await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),wrapFetchError(e,n,r)}}__export(Ab,{discoverSkillsLocally:()=>discoverSkillsLocally});var Pb=__esm({"src/services/local-skill-discovery.ts"(){Ot(),xb(),Tb=100,_b=1048576,__name(findSkillMdFiles,"findSkillMdFiles"),__name(discoverSkillsLocally,"discoverSkillsLocally")}});Ot(),Ot();var Ib=process.argv.includes("-d")||process.argv.includes("--debug");Ib&&(process.env.DEBUG="true"),Ib||(process.removeAllListeners("warning"),process.on("warning",()=>{})),globalThis.AI_SDK_LOG_WARNINGS=!1,Ot(),Ot(),hs();var{red:Nb,yellow:Rb,dim:Mb}=ce,Lb=__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:cs.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Je.error} ${Nb(t)}`),console.log(`${Je.error} ${Nb("ERROR →")} ${n.name}`),console.log(`${Je.info} ${Nb("REASON →")} ${n.message}`),console.log(`${Je.info} ${Nb("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Je.info} ${Mb(`Request ID: ${e}`)}`),console.log(`${Mb(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Je.warning} ${Rb(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:cs.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),Lb({heading:Ye`CRITICAL: Unhandled Promise Rejection!
|
|
282
|
+
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:cs.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),Lb({heading:Ye`CRITICAL: Uncaught Exception!
|
|
283
|
+
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)})})}function getEnterpriseMemoryPath(){switch(w.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=w.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:D(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(D(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:D(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return D(e)&&z(e).isFile()?await v.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=[],i=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(s.push(e),`__CODE_BLOCK_${s.length-1}__`)),a=Array.from(i.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let l=i;for(const t of a){const s=t[1];let i=s;s.startsWith("~/")?i=e.join(w.homedir(),s.slice(2)):e.isAbsolute(s)||(i=e.resolve(e.dirname(n),s));const a=await loadMemoryFile(i);if(a){const e=await processImports(a,i,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(D(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const s=getUserMemoryPath();if(D(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const i=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of i)if(D(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(D(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 D(r)||await v.mkdir(r,{recursive:!0}),D(t)||await v.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const o=be(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 D(n)||await v.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(),i=getUserMemoryPath(),a=[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(i)&&o.push(`# Memory from: ${i}\n\n${r.get(i)}`);for(const e of a)if(r.has(e)){o.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===s||e===i||a.includes(e)||o.push(`# Memory from: ${e}\n\n${t}`);return o.join("\n\n---\n\n")}catch(e){return null}}hs(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ot(),Ot(),Ns(),sS(),fS(),wn(),yS(),Jr(),ao(),Lo(),Ot(),wn(),__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"),Ot(),wn(),Ot();var $b="# Taste (Continuously Learned by [CommandCode][cmd])",Db="[cmd]: https://commandcode.ai/",Ob=`${$b}\n\n${Db}`,Fb="# Taste (Continuously Learned by CommandCode)",qb="# Taste (Continuously Learned by CommandCode.ai)",jb=/^(\s*)# Taste \(Continuously Learned by CommandCode\)(?!\.ai)/,Ub=/^(\s*)# Taste \(Continuously Learned by CommandCode\.ai\)/;function migrateHeader(e){const{content:t}=e;if(t.includes($b))return t.includes(Ob)?t:t.includes(Db)?t.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"").replace($b,Ob):t.replace($b,Ob);let n=t;return n.includes(Db)&&(n=n.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"")),jb.test(n)?n=n.replace(jb,`$1${Ob}`):Ub.test(n)&&(n=n.replace(Ub,`$1${Ob}`)),n}async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!D(n))return null;const r=await v.readFile(n,"utf-8"),o=r.trim();return o&&o!==Ob&&o!==$b&&o!==qb&&o!==Fb?r:null}catch(e){return null}}function getGlobalSkillsDir(){return t.join(S.homedir(),".commandcode","skills")}function getGlobalAgentsCompatSkillsDir(){return t.join(S.homedir(),".agents","skills")}function findGitRoot(){return walkUpToFindDir({dirName:".git"})}function walkUpToFindDir(e){const{dirName:n}=e,r=S.homedir();let o=process.cwd();for(let e=0;e<10&&o!==r;e++){if(D(t.join(o,n)))return o;const e=t.dirname(o);if(e===o)break;o=e}}function getProjectSkillsDir(e){const n=e?.gitRoot??findGitRoot();if(n)return t.join(n,".commandcode","skills");const r=walkUpToFindDir({dirName:".commandcode"});return r?t.join(r,".commandcode","skills"):t.join(process.cwd(),".commandcode","skills")}function getProjectAgentsCompatSkillsDir(e){const n=e?.gitRoot??findGitRoot();if(n)return t.join(n,".agents","skills");const r=walkUpToFindDir({dirName:".agents"});return r?t.join(r,".agents","skills"):t.join(process.cwd(),".agents","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await k.access(r),r}catch{}const o=t.join(n,"skill.md");try{return await k.access(o),o}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await k.access(n);const e=await k.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await k.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 k.readFile(r,"utf-8"),{data:s}=Ke(o),i=hf.parse(s);return i.name!==e.name?null:{name:i.name,description:i.description,filePath:r}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}function mergeSkillSummaries(e){const{primary:t,secondary:n}=e,r=new Set(t.map(e=>e.name)),o=n.filter(e=>!r.has(e.name));return[...t,...o]}async function loadAllSkillSummaries(){const e=findGitRoot(),n=process.cwd(),r=S.homedir(),o=t.join(n,".commandcode","skills"),s=t.join(n,".agents","skills"),i=getProjectSkillsDir({gitRoot:e}),a=getProjectAgentsCompatSkillsDir({gitRoot:e}),l=n!==r,u=[...l&&o!==i?[o]:[],...l&&s!==a?[s]:[],i,a],[d,m,...g]=await Promise.all([loadSkillSummariesFromDirectory({dir:getGlobalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getGlobalAgentsCompatSkillsDir()}),...u.map(e=>loadSkillSummariesFromDirectory({dir:e}))]),h=g.reduce((e,t)=>mergeSkillSummaries({primary:e,secondary:t}),[]);return{global:mergeSkillSummaries({primary:d,secondary:m}),project:h}}function deduplicateSkills(e){const t=new Set,n=[];for(const r of[...e.project,...e.global])t.has(r.name)||(t.add(r.name),n.push(r));return n}async function loadSkill(e){const{filePath:t}=e,n=await k.readFile(t,"utf-8"),r=Ke(n),o=hf.parse(r.data);return{name:o.name,description:o.description,content:r.content.trim(),filePath:t}}function escapeXML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function generateSkillsXML(e){const n=deduplicateSkills(e);return 0===n.length?"":`<available_skills>\n${n.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>`}__name(migrateHeader,"migrateHeader"),__name(getTasteContent,"getTasteContent"),Ot(),Ot(),Ot(),Rf(),wn(),__name(getGlobalSkillsDir,"getGlobalSkillsDir"),__name(getGlobalAgentsCompatSkillsDir,"getGlobalAgentsCompatSkillsDir"),__name(findGitRoot,"findGitRoot"),__name(walkUpToFindDir,"walkUpToFindDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(getProjectAgentsCompatSkillsDir,"getProjectAgentsCompatSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(mergeSkillSummaries,"mergeSkillSummaries"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),__name(deduplicateSkills,"deduplicateSkills"),__name(loadSkill,"loadSkill"),Ot(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),Ot(),Ot();var Bb=f.object({disabledSkills:f.array(f.string()).optional()}).passthrough();Ot(),wn(),Ot();var zb=1048576;Kn(),Ot(),Ot();var Hb=(e=>(e.PreToolUse="PreToolUse",e.PostToolUse="PostToolUse",e))(Hb||{}),Wb=new Set(["PreToolUse"]);function formatZodErrorForModel(e,t){return[`Invalid input for tool "${e}". Please correct and retry:`,...t.issues.map(e=>0===e.path.length?` • (root): ${e.message}`:` • ${e.path.join(".")}: ${e.message}`)].join("\n")}function recordRepairOutcome(e){try{emitRepairOutcomeTelemetry(e)}catch{}}function emitRepairOutcomeTelemetry(e){const{toolName:t,outcome:n,validationError:r}=e,o="recovered"===n?`tool_input_repaired:${t}`:`tool_input_invalid:${t}`,s=Array.from(new Set(r.issues.map(e=>e.code))).join(",");trackError({error:r,context:{component:cs.TOOL_REPAIR,heading:o,code:n,"tool.name":t,"repair.outcome":n,"repair.issue_count":r.issues.length,"repair.issue_codes":s}})}function deepCloneToolInput(e){if(null===e)return e;if("object"!=typeof e)return e;if(Array.isArray(e))return e.map(deepCloneToolInput);const t=e,n={};for(const[e,r]of Object.entries(t))n[e]=deepCloneToolInput(r);return n}yS(),Ot(),Ot(),Ot(),Ot(),__name(formatZodErrorForModel,"formatZodErrorForModel"),Ot(),ps(),gs(),__name(recordRepairOutcome,"recordRepairOutcome"),__name(emitRepairOutcomeTelemetry,"emitRepairOutcomeTelemetry"),Ot(),Ot(),__name(deepCloneToolInput,"deepCloneToolInput"),Ot();var Gb=__name(({parent:e,key:t,value:n,issue:r})=>"invalid_type"===r.code&&"array"===r.expected&&"object"==typeof n&&null!==n&&!Array.isArray(n)&&0===Object.keys(n).length&&(delete e[t],!0),"dropEmptyObjectPlaceholder");Ot();var Vb=__name(({parent:e,key:t,value:n})=>null==n&&(delete e[t],!0),"dropNullOrUndefinedField");Ot();var Qb=__name(({parent:e,key:t,value:n,issue:r})=>{if("invalid_type"!==r.code)return!1;if("array"!==r.expected)return!1;if("string"!=typeof n)return!1;const o=n.trim();if(!o.startsWith("["))return!1;if(!o.endsWith("]"))return!1;let s;try{s=JSON.parse(o)}catch{return!1}return!!Array.isArray(s)&&(e[t]=s,!0)},"parseJsonStringifiedArray");Ot();var Kb=[Vb,Gb,Qb,__name(({parent:e,key:t,value:n,issue:r})=>"invalid_type"===r.code&&"array"===r.expected&&"string"==typeof n&&(e[t]=[n],!0),"wrapBareStringAsArray")];function repairToolInput(e,t){if(null===e)return e;if("object"!=typeof e)return e;const n=deepCloneToolInput(e);let r=!1;for(const e of t.issues)applyRepairsToIssue(n,e)&&(r=!0);return r?n:e}function applyRepairsToIssue(e,t){const n=t.path;if(0===n.length)return!1;const r=walkToParentContainer(e,n);if(void 0===r)return!1;const o=n[n.length-1];if(void 0===o)return!1;const s=r[o];for(const e of Kb)if(e({parent:r,key:o,value:s,issue:t}))return!0;return!1}function walkToParentContainer(e,t){const n=t.slice(0,-1);let r=e;for(const e of n){if(null===r)return;if("object"!=typeof r)return;r=r[e]}if(null!==r&&"object"==typeof r)return r}function parseRepairedToolInput(e){const t=e.schema.safeParse(e.input);if(t.success)return{ok:!0,data:t.data};const n=repairToolInput(e.input,t.error);if(n===e.input)return recordRepairOutcome({toolName:e.toolName,outcome:"unrepairable",validationError:t.error}),{ok:!1,message:formatZodErrorForModel(e.toolName,t.error)};const r=e.schema.safeParse(n);return r.success?(recordRepairOutcome({toolName:e.toolName,outcome:"recovered",validationError:t.error}),{ok:!0,data:r.data}):(recordRepairOutcome({toolName:e.toolName,outcome:"unrepairable",validationError:r.error}),{ok:!1,message:formatZodErrorForModel(e.toolName,r.error)})}__name(repairToolInput,"repairToolInput"),__name(applyRepairsToIssue,"applyRepairsToIssue"),__name(walkToParentContainer,"walkToParentContainer"),__name(parseRepairedToolInput,"parseRepairedToolInput"),Ot();var Yb=/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g,Jb=/^https?:\/\//;function unwrapMarkdownAutoLinks(e){return e.replace(Yb,(e,t,n)=>n.replace(Jb,"")!==t?e:t)}function pathString(){return f.preprocess(e=>"string"!=typeof e?e:unwrapMarkdownAutoLinks(e),f.string())}__name(unwrapMarkdownAutoLinks,"unwrapMarkdownAutoLinks"),__name(pathString,"pathString");var Xb=f.object({command:f.string().min(1,"Command cannot be empty"),args:f.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},f.array(pathString())).optional(),directory:pathString().optional(),timeout:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number()).optional()}),Zb=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,i){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=i}};Ot();var eC=f.object({absolutePath:pathString().describe("The absolute path to the file to read"),offset:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number()).optional().describe("Optional line number to start reading from (0-based index)"),limit:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number()).optional().describe("Optional number of lines to read")});f.object({content:f.union([f.string(),f.instanceof(Buffer)]),contentType:f.enum(["text","binary"]),fileType:f.string(),size:f.number(),linesRead:f.number().optional(),appliedDefaults:f.object({defaulted:f.enum(["offset","limit"]),offset:f.number(),limit:f.number(),reason:f.string()}).optional()});var tC=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};Ot();var nC=f.object({filePath:pathString().describe("The absolute path to the file to edit"),oldValue:f.string().describe("The text to replace"),newValue:f.string().describe("The new text to insert"),replacementCount:f.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:f.boolean().optional().describe("Whether to replace all occurrences (default: false)")});f.object({path:f.string(),replacementsCount:f.number(),oldContent:f.string(),newContent:f.string()}),f.object({name:f.string(),message:f.string(),code:f.string().optional()}),Ot();var rC=f.object({filePath:pathString().describe("The absolute path where the file should be written"),content:f.string().describe("The content to write to the file")});f.object({success:f.boolean(),message:f.string(),path:f.string().optional()});var oC=class extends Error{static{__name(this,"WriteFileError")}code;constructor(e,t){super(e),this.name="WriteFileError",this.code=t}},sC=f.object({type:f.literal("command"),command:f.string().min(1),timeout:f.number().positive().max(600).optional(),async:f.boolean().optional(),failClosed:f.boolean().optional()}),iC=f.object({matcher:f.string().optional(),hooks:f.array(sC).min(1)}),aC=f.object({hooks:f.record(f.string(),f.array(f.unknown())).optional()}).passthrough(),lC=f.nativeEnum(Hb),cC=f.object({session_id:f.string().min(1),transcript_path:f.string().min(1),cwd:f.string().min(1),hook_event_name:lC,permission_mode:f.string().optional()}),uC={[iS.SHELL_COMMAND]:"SHELL",[iS.READ_FILE]:"READ",[iS.EDIT_FILE]:"EDIT",[iS.WRITE_FILE]:"WRITE",[iS.GREP]:"SEARCH",[iS.GLOB]:"GLOB",[iS.READ_DIRECTORY]:"LIST",[iS.READ_MULTIPLE_FILES]:"READ_MULTI",[iS.TODO_WRITE]:"TODOS",[iS.THINKING]:"THINK",[iS.KILL_SHELL]:"KILL_SHELL",[iS.QUESTION]:"QUESTION",[iS.EXPLORE]:"EXPLORE",[aS.WEB_SEARCH]:"WEB_SEARCH",[aS.WEB_FETCH]:"WEB_FETCH",[iS.ENTER_PLAN_MODE]:"ENTER_PLAN_MODE",[iS.EXIT_PLAN_MODE]:"EXIT_PLAN_MODE",[iS.DIAGNOSTICS]:"DIAGNOSTICS",[iS.GET_SELF_KNOWLEDGE]:"GET_SELF_KNOWLEDGE"};Xb.passthrough(),eC.passthrough(),nC.passthrough(),rC.passthrough(),iS.SHELL_COMMAND,iS.READ_FILE,iS.EDIT_FILE,iS.WRITE_FILE;var dC=f.record(f.string(),f.unknown()),mC=cC.extend({hook_event_name:f.literal("PreToolUse"),tool_use_id:f.string().optional(),tool_name:f.string().min(1),tool_display_name:f.string().min(1),tool_input:dC}),pC=cC.extend({hook_event_name:f.literal("PostToolUse"),tool_use_id:f.string().optional(),tool_name:f.string().min(1),tool_display_name:f.string().min(1),tool_input:dC,tool_response:f.string()});f.discriminatedUnion("hook_event_name",[mC,pC]);var gC=f.object({continue:f.boolean().optional(),suppressOutput:f.boolean().optional(),stopReason:f.string().optional(),systemMessage:f.string().optional()}),hC=gC.extend({hookSpecificOutput:f.object({hookEventName:f.literal("PreToolUse").optional(),additionalContext:f.string().optional(),permissionDecision:f.enum(["allow","deny"]).optional(),permissionDecisionReason:f.string().optional()}).strict().optional()}),fC=gC.extend({decision:f.enum(["block"]).optional(),reason:f.string().optional(),hookSpecificOutput:f.object({hookEventName:f.literal("PostToolUse").optional(),additionalContext:f.string().optional()}).strict().optional()});function getOrCompileRegex(e){const{cache:t,pattern:n}=e,r=t.get(n);if(r)return r;if(n.length>200)return dlog(`[Hook] Matcher regex too long (${n.length} > 200): "${n.slice(0,50)}..."`),null;try{const e=new RegExp(n,"i");return t.set(n,e),e}catch{return dlog(`[Hook] Invalid matcher regex: "${n}"`),null}}function getErrorMessage(e){return e instanceof Error?e.message:String(e)}function resolveBlockReason(e){return e.reason||e.stderr||e.fallback}function logFireAndForget(e){e.catch(e=>dlog(`[Hook] Fire-and-forget failed: ${getErrorMessage(e)}`))}function buildHookLabel(e){const t=e.command.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32)||"hook";return`${e.source}#${e.definitionIndex}.${e.hookIndex} ${t}`}Ot(),Kn(),__name(getOrCompileRegex,"getOrCompileRegex"),Ot(),Kn(),__name(getErrorMessage,"getErrorMessage"),__name(resolveBlockReason,"resolveBlockReason"),__name(logFireAndForget,"logFireAndForget"),__name(buildHookLabel,"buildHookLabel");var yC=/[|;<>`]|&&|\|\||\$\(/,wC=/\.(?:sh|js|ts|mjs|cjs)$/i,SC=/^[A-Za-z0-9_.\-]+$/;function deriveCommandName(e){const t=e.trim();if(!t)return null;if(yC.test(t))return null;const n=t.split(/\s+/,1)[0]??"";if(!n)return null;if(!(n.startsWith("/")||n.startsWith("./")||n.startsWith("~/")||SC.test(n)))return null;const r=n.lastIndexOf("/");return(r>=0?n.slice(r+1):n).replace(wC,"")}function buildHookDisplayLabel(e){return deriveCommandName(e)??e}function deriveScriptPath(e){const t=e.trim();if(!t)return;if(yC.test(t))return;const n=t.split(/\s+/,1)[0]??"";return n.startsWith("/")||n.startsWith("./")||n.startsWith("~/")?n:void 0}function firstNonEmptyLine(e){for(const t of e.split("\n")){const e=t.trim();if(e)return e}}function getProjectLocalPath(t){return e.join(t,".commandcode","settings.local.json")}function getProjectSharedPath(t){return e.join(t,".commandcode","settings.json")}function getUserSettingsPath(){return e.join(w.homedir(),".commandcode","settings.json")}async function loadSettingsFile(e){let t,n;try{t=await v.readFile(e,"utf-8")}catch(t){return"ENOENT"===t.code?null:{warning:`Failed to read hooks settings in ${e}: ${getErrorMessage(t)}`}}try{n=JSON.parse(t)}catch(t){return{warning:`Invalid JSON in ${e}: ${getErrorMessage(t)}`}}const r=aC.safeParse(n);return r.success?{settings:{hooks:r.data.hooks}}:{warning:`Invalid hooks structure in ${e}: ${r.error.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ")}`}}function loadHooksFromSource(e){const{settings:t,validationWarnings:n,normalizeEventName:r}=e;if(!t.hooks)return;const o={settingsPath:e.settingsPath,source:e.source,seenCommands:e.seenCommands,entries:e.entries,matcherCache:e.matcherCache};for(const[e,s]of Object.entries(t.hooks)){const t=r(e);if(!t){const t=`Unknown event "${e}" in ${o.settingsPath}, skipping`;dlog(`[Hook] ${t}`),n.push(t);continue}if(!Array.isArray(s)){const t=`Invalid hooks.${e} in ${o.settingsPath}: expected array, got ${typeof s}`;dlog(`[Hook] ${t}`),n.push(t);continue}loadDefinitionsForEvent({ctx:o,eventName:t,definitions:s,validationWarnings:n})}}function loadDefinitionsForEvent(e){const{ctx:t,eventName:n,definitions:r,validationWarnings:o}=e;for(const[e,s]of r.entries()){const r=iC.safeParse(s);if(!r.success){const e=`Invalid hook in ${t.settingsPath}: ${r.error.message}`;dlog(`[Hook] ${e}`),o.push(e);continue}const i=r.data;if(void 0!==i.matcher&&!getOrCompileRegex({cache:t.matcherCache,pattern:i.matcher})){const e=i.matcher.length>200?`matcher exceeds 200 char cap (got ${i.matcher.length})`:"invalid regex",r=`Invalid matcher in ${t.settingsPath} (event=${n}): ${e}. Hook skipped. Matcher: "${i.matcher.slice(0,80)}"`;dlog(`[Hook] ${r}`),o.push(r);continue}for(const[r,o]of i.hooks.entries())processHookConfig({ctx:t,def:i,eventName:n,definitionIndex:e,hookIndex:r,rawHookConfig:o})}}function processHookConfig(e){const{ctx:t,def:n,eventName:r,definitionIndex:o,hookIndex:s,rawHookConfig:i}=e,a=`${r}:${n.matcher??""}:${i.command}`;t.seenCommands.has(a)?dlog(`[Hook] Hook in ${t.settingsPath} shadowed by higher-priority source (event=${r}, matcher=${n.matcher??"(any)"}, command=${i.command})`):(t.seenCommands.add(a),t.entries.push({config:i,source:t.source,eventName:r,matcher:n.matcher,definitionIndex:o,hookIndex:s}))}function resolveScopePaths(e){const t=[{scope:"user",filePath:getUserSettingsPath()}];return e&&(t.push({scope:"projectShared",filePath:getProjectSharedPath(e)}),t.push({scope:"projectLocal",filePath:getProjectLocalPath(e)})),t}async function readDisabledNames(e){let t,n;try{t=await v.readFile(e,"utf-8")}catch(t){return"ENOENT"===t.code||dlog(`[Skills] Failed to read settings ${e}: ${t.message}`),null}try{n=JSON.parse(t)}catch(t){return dlog(`[Skills] Invalid JSON in ${e}: ${t.message}`),null}const r=Bb.safeParse(n);return r.success?r.data.disabledSkills??null:(dlog(`[Skills] Invalid disabledSkills shape in ${e}`),null)}function resolveProjectRoot(e){return e?.projectRoot?e.projectRoot:findGitRoot()??walkUpToFindDir({dirName:".commandcode"})}async function loadDisabledSkills(e){const t=resolveProjectRoot(e),n=resolveScopePaths(t),r=new Set,o=new Map;for(const{scope:e,filePath:t}of n){const n=await readDisabledNames(t);if(n)for(const t of n)r.add(t),o.has(t)||o.set(t,e)}return{names:r,bySkill:o,noProjectRoot:!t}}__name(deriveCommandName,"deriveCommandName"),__name(buildHookDisplayLabel,"buildHookDisplayLabel"),__name(deriveScriptPath,"deriveScriptPath"),__name(firstNonEmptyLine,"firstNonEmptyLine"),__name(getProjectLocalPath,"getProjectLocalPath"),__name(getProjectSharedPath,"getProjectSharedPath"),__name(getUserSettingsPath,"getUserSettingsPath"),__name(loadSettingsFile,"loadSettingsFile"),__name(loadHooksFromSource,"loadHooksFromSource"),__name(loadDefinitionsForEvent,"loadDefinitionsForEvent"),__name(processHookConfig,"processHookConfig"),Kn(),__name(resolveScopePaths,"resolveScopePaths"),__name(readDisabledNames,"readDisabledNames"),__name(resolveProjectRoot,"resolveProjectRoot"),__name(loadDisabledSkills,"loadDisabledSkills");var EC=Promise.resolve();async function readSettingsObject(e){try{const t=await v.readFile(e,"utf-8"),n=JSON.parse(t);return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}catch(e){if("ENOENT"===e.code)return{};throw e}}async function writeDisabledSkillsTo(t,n){const r=await readSettingsObject(t);0===n.length?delete r.disabledSkills:r.disabledSkills=n,await v.mkdir(e.dirname(t),{recursive:!0}),await v.writeFile(t,JSON.stringify(r,null,2)+"\n")}async function setSkillEnabled(e,t,n){const r=resolveProjectRoot(n),o=n?.scope??"projectLocal",s=r||"user"===o?o:"user";let i;switch(s){case"user":i=getUserSettingsPath();break;case"projectShared":i=getProjectSharedPath(r);break;case"projectLocal":i=getProjectLocalPath(r)}const a=EC.then(async()=>{const n=await readDisabledNames(i)??[],r=new Set(n);t?r.delete(e):r.add(e),await writeDisabledSkillsTo(i,[...r].sort())});return EC=a.catch(()=>{}),await a,s}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}__name(readSettingsObject,"readSettingsObject"),__name(writeDisabledSkillsTo,"writeDisabledSkillsTo"),__name(setSkillEnabled,"setSkillEnabled"),Ot(),Ot(),Ot(),Ot(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath"),Ao(),Ot(),Ao();var bC=new Set(["DIRECTORY_OUTSIDE_WORKSPACE"]);function isSoftToolErrorCode(e){return void 0!==e&&bC.has(e)}function formatOutsideWorkspaceMessage(e,t){return`${t===(e.replace(/[/\\]+$/,"")||e)?e:`${e} (resolved to ${t})`} is outside workspace (allowed: ${getWorkspaceDirectories().join(", ")})`}async function readFileContent(t){const{absolutePath:n,offset:r,limit:o}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new tC("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const s=e.normalize(n);if(!isPathInWorkspace(s))throw new tC(formatOutsideWorkspaceMessage(n,s),"DIRECTORY_OUTSIDE_WORKSPACE");try{await v.access(s,L.constants.F_OK|L.constants.R_OK)}catch{throw new tC(`File not found or not readable: ${s}`,"FILE_ACCESS_ERROR")}if(!(await v.stat(s)).isFile())throw new tC("Path does not point to a file","NOT_A_FILE");const i=getFileType(s),a=isBinaryFile(i);let l,u=r,d=o;if(void 0===u&&void 0!==d?(u=0,l={defaulted:"offset",offset:0,limit:d,reason:"offset was not provided; defaulted to 0 (read from start of file). To read a different range, retry with both offset and limit."}):void 0!==u&&void 0===d&&(d=2e3,l={defaulted:"limit",offset:u,limit:2e3,reason:"limit was not provided; defaulted to 2000 lines. To read more or fewer lines, retry with both offset and limit."}),void 0!==u&&u<0)throw new tC("Offset must be >= 0","INVALID_OFFSET");if(void 0!==d&&d<=0)throw new tC("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await v.readFile(s);return{fileType:i,content:e,size:e.length,contentType:"binary"}}if(void 0!==u&&void 0!==d){const e=await readTextFileLines(s,u,d);return{fileType:i,contentType:"text",content:e.content,size:Buffer.byteLength(e.content,"utf8"),linesRead:e.linesRead,appliedDefaults:l}}{const e=await v.readFile(s,"utf8");return{content:e,fileType:i,contentType:"text",size:Buffer.byteLength(e,"utf8")}}}catch(e){if(e instanceof tC)throw e;throw new tC(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(isSoftToolErrorCode,"isSoftToolErrorCode"),__name(formatOutsideWorkspaceMessage,"formatOutsideWorkspaceMessage"),__name(readFileContent,"readFileContent");var CC={".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",...CC}[n]||"unknown"}function isBinaryFile(e){return Object.values(CC).includes(e)}async function readTextFileLines(e,t,n){const r=(await v.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),i=r.slice(o,s);return{content:i.join("\n"),linesRead:i.length}}function formatReadSummary({successfulReads:e,totalFiles:t}){return`Read ${e}/${t} ${1===t?"file":"files"}`}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),Ot(),Ot(),__name(formatReadSummary,"formatReadSummary");var vC=/^Read\s+(\d+)\/(\d+)\s+files?(?:,\s+(\d+)\s+lines?)?$/i;function formatOutput(e){const t=[];if("binary"===e.contentType)return t.push(formatReadSummary({successfulReads:1,totalFiles:1})),t.push(`Binary file: ${e.fileType}`),t.join("\n");const n=e.linesRead??(e.content?String(e.content).split("\n").length:0);if(e.appliedDefaults){const r=e.appliedDefaults,o=r.offset+n-1;t.push(`${formatReadSummary({successfulReads:1,totalFiles:1})}, lines ${r.offset}-${o} (${n} of ${r.limit} requested)`),t.push(`Note: ${r.reason}`)}else t.push(`${formatReadSummary({successfulReads:1,totalFiles:1})}, ${n} ${1===n?"line":"lines"}`);return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(formatOutput,"formatOutput");var kC={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 path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"read_file",schema:eC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput(await readFileContent(e))}catch(e){return e instanceof tC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading file"}},"execute")};Ot(),Ot(),Ao(),Ot(),Ot();var TC=f.object({backupFileName:f.string().nullable(),version:f.number().int().positive(),backupTime:f.string().datetime()}),_C=f.object({messageId:f.string().uuid(),trackedFileBackups:f.record(f.string(),TC),timestamp:f.string().datetime()});f.object({type:f.literal("file-history-snapshot"),messageId:f.string().uuid(),snapshot:_C,isSnapshotUpdate:f.boolean()}),f.object({maxFileSize:f.number().int().positive().default(10485760),retentionDays:f.number().int().positive().default(30)});var xC=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`${R.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(S.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 k.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 k.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await k.writeFile(r,n);const e=await k.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 k.rename(r,t)}catch(e){try{await k.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await k.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await k.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),i=Math.floor(s/24);return i>0?`${i}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}Ot(),Ot(),wn(),__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"),hs();var AC={maxFileSize:10485760,retentionDays:30},PC=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...AC,...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 k.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 i={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,i),this.trackedState.versions.set(t,n),{success:!0,backup:i,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:cs.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 k.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new xC(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:cs.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await k.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 k.access(t,k.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 k.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await k.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await k.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}};Ot(),as(),hs();var IC=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new PC({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,i=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:cs.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(i=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const a=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&a.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&a.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:a}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:i}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}};Ot();var NC=null;function initializeCheckpointService(e){const{sessionId:t}=e;return NC=new IC({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return NC?NC.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:i=1}=t;if(!n)throw createFileEditError("filePath is required","INVALID_PATH");if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const a=e.normalize(n);if(!isPathInWorkspace(a))throw createFileEditError(formatOutsideWorkspaceMessage(n,a),"DIRECTORY_OUTSIDE_WORKSPACE");if(!r)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==o)throw createFileEditError("newValue is required","INVALID_INPUT");if(!s&&i<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await O.access(a,q.F_OK|q.R_OK|q.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${a}`,"FILE_ACCESS_ERROR")}let l;try{const e=await readFileContent({absolutePath:a});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");l=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 u=(l.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===u)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let d,m;if(s)d=u;else if(d=i,d>u)throw createFileEditError(`Expected ${d} replacements, but only found ${u} occurrences`,"INSUFFICIENT_MATCHES");let g=0;if(s||d===u)m=l.split(r).join(o),g=u;else{m=l;for(let e=0;e<d;e++){const e=m.indexOf(r);-1!==e&&(m=m.substring(0,e)+o+m.substring(e+r.length),g++)}}if(0===g)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:a}),await O.writeFile(a,m,"utf-8"),{path:a,replacementsCount:g,oldContent:l,newContent:m}}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"),Ot(),__name(formatOutput2,"formatOutput");var RC={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 path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"edit_file",schema:nC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput2(await editFile(e))}catch(e){return e&&"object"==typeof e&&"code"in e&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while editing file"}},"execute")};Ot(),Ot();var MC=f.object({path:pathString().describe("The absolute path to the directory to read"),exclude:f.array(pathString()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:f.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});f.object({files:f.array(f.string()),directories:f.array(f.string())});var LC=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 LC("Path must be absolute, not relative","INVALID_PATH");const s=e.normalize(n);if(!isPathInWorkspace(s))throw new LC(formatOutsideWorkspaceMessage(n,s),"DIRECTORY_OUTSIDE_WORKSPACE");try{if(!(await v.stat(n)).isDirectory())throw new LC("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof LC)throw e;throw new LC(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await v.readdir(n);let s=[];o&&(s=await loadGitIgnorePatterns(n));const i=[...r,...s],a=[],l=[];for(const r of t){if(shouldIgnoreEntry(r,i))continue;const t=e.join(n,r);try{const e=await v.stat(t);e.isDirectory()?l.push(r):e.isFile()&&a.push(r)}catch(e){dlog(`[read-directory] skipped ${t}: ${e instanceof Error?e.message:String(e)}`)}}return{files:a.sort(),directories:l.sort()}}catch(e){if(e instanceof LC)throw e;throw new LC(`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 findGitRoot2(t);for(;r&&isWithinGitRoot(r,o);){const t=e.join(r,".gitignore");try{const e=(await v.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch{}const o=e.dirname(r);if(o===r)break;r=o}}catch{}return n}async function isInGitRepository(e){try{return null!==await findGitRoot2(e)}catch{return!1}}async function findGitRoot2(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await v.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(Xe(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")}Ot(),Ao(),Kn(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot2,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),Ot(),__name(formatOutput3,"formatOutput");var $C={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 path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"read_directory",schema:MC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput3(await readDirectory(e))}catch(e){return e instanceof LC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading directory"}},"execute")};async function writeFile3({filePath:e,content:n}){const o=e.startsWith("~/")?t.join(S.homedir(),e.slice(2)):e;if(!i(o))throw new Error(`Invalid file path: '${o}'. Only absolute paths are supported.`);const s=t.normalize(o);if(!isPathInWorkspace(s))throw new oC(formatOutsideWorkspaceMessage(e,s),"DIRECTORY_OUTSIDE_WORKSPACE");try{const e=r(s);return D(e)||await T(e,{recursive:!0}),await backupFileBeforeEdit({filePath:s}),await _(s,n,"utf-8"),{path:s,bytesWritten:Buffer.byteLength(n,"utf-8")}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";throw new Error(`Failed to write file '${s}': ${t}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}Ot(),Ot(),Ao(),__name(writeFile3,"writeFile"),Ot(),__name(formatOutput4,"formatOutput");var DC={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). The path must be inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"write_file",schema:rC,input:e});if(!t.ok)return t.message;try{const e=t.data,n=await writeFile3(e);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return e instanceof oC&&isSoftToolErrorCode(e.code)?e.message:formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")};Ot(),Ot();var OC=f.object({include:f.array(pathString()).describe("Array of glob patterns to include files"),exclude:f.array(pathString()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:f.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:f.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:pathString().optional().describe("Base directory for relative paths. Default: current working directory")}),FC=f.object({filePath:f.string(),content:f.string(),fileType:f.string(),size:f.number()});f.object({content:f.string(),filesRead:f.array(f.string()),errors:f.array(f.object({file:f.string(),error:f.string()})),fileDetails:f.array(FC)});var qC=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}};Ot(),Ao();var jC=["**/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:i=process.cwd()}=e;if(!n||0===n.length)throw new qC("At least one include pattern must be provided","NO_PATTERNS");const a=t.resolve(i);if(!isPathInWorkspace(a))throw new qC(formatOutsideWorkspaceMessage(i,a),"DIRECTORY_OUTSIDE_WORKSPACE");const l={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];s&&e.push(...jC);const i=await findMatchingFiles({include:n,exclude:e,gitIgnore:o,targetDirectory:a});for(const e of i)try{const n=t.resolve(a,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 qC)throw e;throw new qC(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){const t=e.fileDetails.length,n=e.filesRead.length,r=e.errors.length,{fileTypesCounts:o}=e.fileDetails.reduce((e,t)=>(e.fileTypesCounts[t.fileType]=(e.fileTypesCounts[t.fileType]||0)+1,e),{fileTypesCounts:{}});return{totalFiles:t,successfulReads:n,failedReads:r,fileTypesCounts:o,contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];if(n.push(formatReadSummary(t)),e.errors.length>0){n.push("Errors:");for(const t of e.errors)n.push(` - ${t.file}: ${t.error}`)}return n.push("--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),Ot(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var UC={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. The path must resolve inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"read_multiple_files",schema:OC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatOutput5(await readMultipleFiles(e))}catch(e){return e instanceof qC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading multiple files"}},"execute")};Ot(),Ot();var BC=f.object({pattern:f.string().min(1,"Pattern is required"),include:f.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},f.array(pathString())).optional(),directory:pathString().optional()});Ot(),as(),Ot(),as(),jf(),Qr();var zC=rs;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){const e=n,r=e.image??e.source?.data??"";t+=estimateImageTokens("string"==typeof r?r.replace(/^data:[^;]+;base64,/,""):"")}else if("tool-call"===n.type){const e=n;t+=5,e.toolName&&(t+=estimateTextTokens(e.toolName)),e.input&&(t+=1.1*estimateTextTokens(JSON.stringify(e.input)))}else if("tool-result"===n.type){const e=n;t+=3,e.output&&"object"==typeof e.output&&"string"==typeof e.output.value&&(t+=estimateTextTokens(e.output.value))}return Math.ceil(t)}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)>zC}__name(estimateTokens,"estimateTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit");var HC="Results are too large. Let's try a more specific pattern to narrow it down. There's a 25K token limit on tool outputs per request.";function checkToolOutputTokensLimit(e){return exceedsOutputTokenLimit(e)?HC: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 execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=be(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>ts)return i=HC,void o.kill("SIGTERM");s+=t}catch(e){i+=`\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(i.length+t.length>ns)return void(i+="\n[Error output truncated: too large]");i+=t}catch(e){i+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||i?r(new Error(i||`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"),i=[];for(const e of s){const t=parseGrepLine(e);t&&i.push(t)}return i}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),Ot(),__name(formatGrepResults,"formatGrepResults");var WC={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=>{const t=parseRepairedToolInput({toolName:"grep",schema:BC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatGrepResults(await grepSearchInDirectory(e))}catch(e){return e instanceof Error?e.message===HC?e.message:`ERROR: ${e.message}`:"ERROR: Unknown error occurred while searching files"}},"execute")};Ot(),Ot();var GC=f.object({pattern:f.string().min(1,"Pattern is required"),path:pathString().optional()}),VC=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 VC("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new VC(formatOutsideWorkspaceMessage(r,e),"DIRECTORY_OUTSIDE_WORKSPACE");const o=await Ze(n,{cwd:e,ignore:gn,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 k.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 VC)throw e;if(e instanceof Error)throw new VC(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new VC("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")}Ot(),wn(),Ao(),__name(globSearch,"globSearch"),Ot(),__name(formatGlobResults,"formatGlobResults");var QC={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. The path must resolve inside the workspace (the current directory or one of its added directories). 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=>{const t=parseRepairedToolInput({toolName:"glob",schema:GC,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatGlobResults(await globSearch(e))}catch(e){return e instanceof VC&&isSoftToolErrorCode(e.code)?e.message:e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while finding files"}},"execute")};async function executeShellCommand(t){const{command:n,args:r=[],directory:o,timeout:s=3e4}=t,i=Date.now();if(!n.trim())throw new Zb("Command cannot be empty","EMPTY_COMMAND");const a=o?e.resolve(process.cwd(),o):process.cwd();if(o&&!isPathInWorkspace(a))throw new Zb(formatOutsideWorkspaceMessage(o,a),"DIRECTORY_OUTSIDE_WORKSPACE");try{if(!(await k.stat(a)).isDirectory())throw new Zb(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof Zb)throw e;throw new Zb(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:a,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((t,o)=>{let a="",l="",u=!1,d=!1;const m=r.length>0?tt([n,...r]):n,g=setTimeout(()=>{if(!u){h.kill("SIGTERM");const e=Date.now()-i;o(new Zb(`Command timed out after ${s}ms`,"TIMEOUT",null,"SIGTERM",a,l,e))}},s),h=be(m,[],e);h.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>ts)return l=HC,d=!0,void h.kill("SIGTERM");a+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,h.kill("SIGTERM")}}),h.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>ns)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"}]`}}),h.on("close",(e,n)=>{u=!0,clearTimeout(g);const r=Date.now()-i;0===e?t({stdout:a.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):o(new Zb(d?HC:`Command failed with exit code ${e}`,d?"OUTPUT_TRUNCATED":"COMMAND_FAILED",e,n,a.trim(),l.trim(),r))}),h.on("error",e=>{u=!0,clearTimeout(g);const t=Date.now()-i;o(new Zb(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),l.trim(),t))})})}catch(e){if(e instanceof Zb)throw e;throw new Zb(`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")}Ot(),Ot(),as(),Ao(),__name(executeShellCommand,"executeShellCommand"),Ot(),__name(formatShellCommandResult,"formatShellCommandResult");var KC={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. Accepts absolute or relative paths; relative paths are resolved against the current working directory. The path must be inside the workspace (the current directory or one of its added directories) and must exist. Examples: "src" runs in src folder, "packages/core" runs in packages/core, "/Users/you/project/packages/core" runs in the specified absolute path. 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=>{const t=parseRepairedToolInput({toolName:"shell_command",schema:Xb,input:e});if(!t.ok)return t.message;try{const e=t.data;return formatShellCommandResult(await executeShellCommand(e))}catch(e){if(e instanceof Zb){if("OUTPUT_TRUNCATED"===e.code)return[e.stdout,HC].filter(Boolean).join("\n");if(isSoftToolErrorCode(e.code))return e.message;if(e.stdout||e.stderr){let t=`ERROR: ${e.message}`;return e.stdout&&(t+=`\nOutput:\n${e.stdout}`),e.stderr&&(t+=`\nError output:\n${e.stderr}`),t}return`ERROR: ${e.message}`}return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while executing command"}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}Ot(),Ot(),__name(think,"think");var YC={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)}Ot(),Ot(),__name(todoWrite,"todoWrite");var JC={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")}Ot(),Ot(),__name(askUserQuestion,"askUserQuestion"),Ot(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var XC={name:"ask_user_question",description:'Ask the user a question with predefined answer choices.\n\nUse it when the request has more than one reasonable reading, when a requirement or preference is missing, or when the user needs to pick between viable approaches.\n\n- A free-text reply ("Type something") is always offered to the user. Never list it yourself.\n- To surface a recommendation, put that option first and append " (Recommended)" to its label.\n- Set multiSelect: true when more than one option can apply to the same 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:'Full sentence ending in "?". Specific enough that the user can answer without rereading the conversation.'},header:{type:"string",description:'Short topic label, 20 characters or fewer so it fits in a chip. Used to disambiguate when multiple questions are asked at once. Examples: "DB choice", "Test runner", "Cache layer".'},options:{type:"array",description:'2 to 4 distinct answer choices. They must be mutually exclusive unless multiSelect is true. Do not include a "Type something" or other free-text choice; the user is always offered one automatically.',items:{type:"object",properties:{label:{type:"string",description:'1 to 5 words, the answer the user picks. Put your recommended choice first and append " (Recommended)" to its label.'},description:{type:"string",description:"One-sentence consequence: what the user gets, gives up, or commits to by picking this answer. Use it to explain trade-offs."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true when more than one option can apply to the same question. Defaults to a single answer."}},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")};Ot(),Ot();var ZC=f.object({port:f.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:f.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"}),ev=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=be(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",i="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{i+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(i.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 i=parseInt(r[r.length-1],10);if(!isNaN(i))return i}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new ev(`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 ev("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 ev(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${Pe.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}Ot(),__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"),Ot(),__name(formatKillshellResult,"formatKillshellResult");var tv={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=ZC.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?"ERROR: Permission denied — Process termination was not approved":formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while killing process"}},"execute")};Ot();var nv={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")};Ot();var rv={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")};Ot(),Ot(),Ot(),Ot();var ov=f.preprocess(e=>{if("string"==typeof e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{return[e]}return e},f.array(pathString())).optional(),sv=f.object({filePaths:ov.describe('Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.')});Ot(),Ot(),Kn(),Ot(),Ot();var iv=nt().add([".env",".env.*","*.pem","*.key","id_rsa","id_rsa.*","id_ed25519","id_ed25519.*","id_ecdsa","id_ecdsa.*","credentials","credentials.*","*.crt",".npmrc",".pypirc",".netrc"]),av=new Map,lv=__name(async t=>{const n=e.resolve(t);try{return await v.realpath(n)}catch{return n}},"canonicalize"),cv=__name(async t=>{let n=e.resolve(t);for(;;){try{const t=await v.stat(e.join(n,".git"));if(t.isDirectory()||t.isFile())return n}catch{}const t=e.dirname(n);if(t===n)return null;n=t}},"findWorkingTreeRoot"),uv=__name(t=>{const n=e.basename(t);return!!n&&iv.ignores(n)},"hasSensitiveBasename"),dv=__name(async(e,t)=>{const n=new Map;return 0===t.length?n:new Promise(r=>{const o=[];let s=!1,i=!1;const a=__name(e=>{if(!i){i=!0;for(const r of t)n.set(r,e.has(r));r(n)}},"settle");try{const n=be("git",["check-ignore","--stdin","-z"],{cwd:e,stdio:["pipe","pipe","ignore"]}),r=setTimeout(()=>{s=!0;try{n.kill()}catch{}a(new Set)},2e3);n.stdin.on("error",()=>{}),n.stdout.on("data",e=>{o.push(e)}),n.on("error",()=>{clearTimeout(r),a(new Set)}),n.on("close",e=>{if(clearTimeout(r),s||0!==e&&1!==e)return void a(new Set);const t=Buffer.concat(o).toString("utf8");a(new Set(t.split("\0").filter(Boolean)))});try{n.stdin.write(t.join("\0")+"\0"),n.stdin.end()}catch{}}catch{a(new Set)}})},"checkGitIgnoredBatch"),mv=__name(async e=>{const t=Date.now(),n=av.get(e);if(n&&n.expiresAt>t)return n;const r=await cv(e)??e,o={results:new Map,workingTreeRoot:r,expiresAt:t+3e4};if(av.size>=64){const e=av.keys().next().value;void 0!==e&&av.delete(e)}return av.set(e,o),o},"getOrCreateWorkspaceCache"),pv=__name(async(t,n)=>(await Promise.all(t.map(async t=>{if(!t)return null;const r=await lv(t),o=e.relative(n,r);if(".."===o||o.startsWith(`..${e.sep}`)||e.isAbsolute(o)||""===o)return null;const s=o.split(e.sep).join("/");return iv.ignores(s)||uv(t)?null:{originalPath:t,canonPath:r}}))).filter(e=>null!==e),"classifyCandidates"),gv=__name(async(e,t)=>{const n=new Set;if(!t||0===e.length)return n;const r=await lv(t),o=await pv(e,r);if(0===o.length)return n;const s=await mv(r),i=[];for(const e of o){const t=s.results.get(e.canonPath);void 0!==t?t||n.add(e.originalPath):i.push(e)}if(i.length>0){const e=await dv(s.workingTreeRoot,i.map(e=>e.canonPath));for(const t of i){const r=e.get(t.canonPath)??!1;s.results.set(t.canonPath,r),r||n.add(t.originalPath)}}return n},"getSafePathSet"),hv=__name(async e=>{const t=e.workspace.rootPath;if(!t){const t=!e.activeFile||!uv(e.activeFile.path);return{...e,activeFile:t?e.activeFile:null,selection:t?e.selection:null,openFiles:e.openFiles.filter(e=>!uv(e.path))}}const n=[...e.activeFile?[e.activeFile.path]:[],...e.openFiles.map(e=>e.path)],r=await gv(n,t),o=!e.activeFile||r.has(e.activeFile.path);return{...e,activeFile:o?e.activeFile:null,selection:o?e.selection:null,openFiles:e.openFiles.filter(e=>r.has(e.path))}},"filterIdeContext"),fv=t.join(S.homedir(),".commandcode","ide"),yv=f.object({socketPath:f.string().min(1),workspaceFolders:f.array(f.string()),pid:f.number().int().positive().finite(),ideName:f.string().min(1),timestamp:f.number()}),wv=__name(e=>{if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)},"errMsg"),Sv=__name(e=>{const n=t.resolve(e);let r=n;try{r=$.realpathSync(n)}catch{}return"win32"===process.platform?r.toLowerCase():r},"normalizePathForComparison"),Ev=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),bv=__name(e=>{if("win32"===process.platform)return null;try{const t=Ce("ps",["-o","ppid=","-p",String(e)],{encoding:"utf-8",timeout:1e3}),n=parseInt(t.trim(),10);return Number.isNaN(n)||n<=1?null:n}catch{return null}},"getParentPid"),Cv=__name((e,t,n=bv)=>{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"),vv=__name(()=>{if("vscode"!==process.env.TERM_PROGRAM)return null;if(process.env.CURSOR_TRACE_ID)return"cursor";if(process.env.WINDSURF_SESSION_ID)return"windsurf";const e=(process.env.__CFBundleIdentifier??"").toLowerCase();if(e){if(e.includes("todesktop")||e.includes("cursor"))return"cursor";if(e.includes("windsurf"))return"windsurf";if(e.includes("vscode"))return"code"}const t=[process.env.VSCODE_GIT_ASKPASS_NODE,process.env.VSCODE_GIT_ASKPASS_MAIN,process.env.GIT_ASKPASS];for(const e of t){if(!e)continue;const t=e.toLowerCase();if(t.includes("cursor"))return"cursor";if(t.includes("windsurf"))return"windsurf"}return"code"},"detectIDE"),kv=__name((e,n)=>{try{$.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{$.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Tv=__name((e,n={})=>{const{sessionDir:r=fv,parentPidFn:o=bv,startPid:s=process.ppid}=n;try{if(!$.existsSync(r))return null;const n=`${e}-`,i=$.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),a=[];for(const e of i)try{const n=t.join(r,e),o=JSON.parse($.readFileSync(n,"utf-8")),s=yv.safeParse(o);if(!s.success)continue;const i=s.data;if(t.dirname(i.socketPath)!==r)continue;if(!Ev(i.pid)){kv(n,r);continue}a.push({session:i,file:e})}catch{continue}if(0===a.length)return null;const l=Cv(a,s,o);if(l)return dlog(`[VSCode:IPC] Discovered session via PID ancestry: ${t.basename(l.session.socketPath)} (${l.session.ideName})`),l.session.socketPath;const u=Sv(process.cwd());let d=null,m=0;for(const{session:e}of a)for(const n of e.workspaceFolders){const r=Sv(n);(u===r||u.startsWith(r+t.sep))&&r.length>m&&(d=e,m=r.length)}return d&&dlog(`[VSCode:IPC] Discovered session via workspace match: ${t.basename(d.socketPath)} (${d.ideName})`),d?.socketPath??null}catch{return null}},"discoverSocketPath"),_v=__name(()=>{const e=vv();return e?Tv(e):null},"resolveSocketPath"),xv=__name(()=>({type:"request",id:M(),payload:{action:"getContext"}}),"createContextRequest"),Av=__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"),Pv=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!Av(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"),Iv=!1,Nv=__name(()=>{Iv||(dlog("[VSCode:IPC] No socket path resolved"),Iv=!0)},"logNoSocketPathOnce"),Rv=__name(()=>{Iv=!1},"resetNoSocketPathLogDedup"),Mv=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??_v()}get isConnected(){return this.connected}async connect(e=2e3){if(!this.socketPath)return Nv(),!1;const n=this.socketPath;dlog(`[VSCode:IPC] Connecting: ${t.basename(n)} (timeout ${e}ms)`);try{return await new Promise(t=>{try{const r=Le.connect(n);this.socket=r;const o=__name(()=>{r.off("error",s)},"cleanup"),s=__name(e=>{clearTimeout(i),o(),this.connected=!1,dlog(`[VSCode:IPC] Connection error: ${e.message}`),t(!1)},"handleError"),i=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),o(),r.destroy(),t(!1)},e);r.on("connect",()=>{try{if(clearTimeout(i),o(),this.socket!==r)return r.destroy(),void t(!1);this.connected=!0,Rv(),dlog("[VSCode:IPC] Connected successfully"),r.on("close",()=>{this.connected=!1}),r.on("error",()=>{this.connected=!1}),t(!0)}catch(e){dlog(`[VSCode:IPC] Error in connect handler: ${wv(e)}`),r.destroy(),t(!1)}}),r.on("error",s)}catch(e){dlog(`[VSCode:IPC] Connection exception: ${wv(e)}`),t(!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=xv(),r=await new Promise(r=>{const o=__name(()=>{t.off("data",a),t.off("error",l)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),o(),r(null)},e);let i="";const a=__name(e=>{try{i+=e.toString();const t=i.indexOf("\n");if(-1===t)return;clearTimeout(s),o();const a=i.slice(0,t),l=Pv(Buffer.from(a),n.id);l||dlog("[VSCode:IPC] Invalid response received"),r(l)}catch(e){clearTimeout(s),o(),dlog(`[VSCode:IPC] Error processing response: ${wv(e)}`),r(null)}},"handleData"),l=__name(e=>{clearTimeout(s),o(),dlog(`[VSCode:IPC] Socket error during request: ${e.message}`),r(null)},"handleError");t.on("data",a),t.on("error",l);try{t.write(JSON.stringify(n)+"\n")}catch(e){clearTimeout(s),o(),dlog(`[VSCode:IPC] Failed to send request: ${wv(e)}`),r(null)}});if(!r)return null;try{return await hv(r)}catch(e){return dlog(`[VSCode:IPC] Filter error, dropping context: ${wv(e)}`),null}}catch{return null}}async getDiagnostics(e={}){const{filePaths:t,timeout:n=5e3}=e,r=this.socket;if(!r||!this.connected)return dlog("[VSCode:IPC] Cannot get diagnostics - not connected"),null;const o={type:"request",id:M(),payload:{action:"getDiagnostics",filePaths:t}};return new Promise(e=>{const t=__name(()=>{r.off("data",a),r.off("error",l)},"cleanup"),s=setTimeout(()=>{dlog("[VSCode:IPC] Diagnostics request timeout"),t(),e(null)},n);let i="";const a=__name(n=>{for(i+=n.toString();;){const n=i.indexOf("\n");if(-1===n)return;const r=i.slice(0,n);if(i=i.slice(n+1),r.trim())try{const n=JSON.parse(r);if(n.id!==o.id){dlog("[VSCode:IPC] Ignoring diagnostics response for different request id");continue}return clearTimeout(s),t(),void("response"===n.type&&n.payload?.diagnostics?e(n.payload.diagnostics):"error"===n.type?(dlog(`[VSCode:IPC] Diagnostics error response: ${n.payload?.message??"(no message)"} [code: ${n.payload?.code??"n/a"}]`),e(null)):(dlog("[VSCode:IPC] Invalid diagnostics response"),e(null)))}catch(e){dlog(`[VSCode:IPC] Failed to parse diagnostics response line: ${wv(e)}`)}}},"handleData"),l=__name(n=>{clearTimeout(s),t(),dlog(`[VSCode:IPC] Socket error during diagnostics request: ${n.message}`),e(null)},"handleError");r.on("data",a),r.on("error",l);try{r.write(JSON.stringify(o)+"\n")}catch(n){clearTimeout(s),t(),dlog(`[VSCode:IPC] Failed to send diagnostics request: ${wv(n)}`),e(null)}})}disconnect(){if(this.socket){dlog("[VSCode:IPC] Disconnecting");try{this.socket.end()}catch{}this.socket=null,this.connected=!1}}static async isAvailable(e=1e3){try{const t=new _VSCodeIPCClient;if(!t.socketPath)return dlog("[VSCode:IPC] Availability check: unavailable (no socket path)"),!1;const n=await t.connect(e);return t.disconnect(),dlog("[VSCode:IPC] Availability check: "+(n?"available":"unavailable")),n}catch{return!1}}};Ot();var Lv=__name(async(e,t)=>{if(!t)return e.filter(e=>!uv(e.file));const n=await gv(e.map(e=>e.file),t);return e.filter(e=>n.has(e.file))},"filterDiagnostics");async function fetchDiagnostics(e){if(!vv())throw new Error("Not running inside an IDE terminal. The diagnostics tool requires the Command Code VS Code extension.");const n=e?.map(e=>t.resolve(e)),r=new Mv;try{if(!await r.connect())throw new Error("Could not connect to IDE extension. Make sure the Command Code extension is installed and active.");const e=await r.getDiagnostics({filePaths:n,timeout:5e3});if(null===e)throw new Error("Failed to get diagnostics from IDE.");const t=await cv(process.cwd())??process.cwd(),o=await Lv(e,t);return dlog("[diagnostics] Fetched diagnostics",{fileCount:o.length,droppedCount:e.length-o.length,total:o.reduce((e,t)=>e+t.diagnostics.length,0)}),o}finally{r.disconnect()}}Kn(),__name(fetchDiagnostics,"fetchDiagnostics"),Ot();var $v=__name(e=>String(e??"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\r\n]+/g," ").replace(/```/g,"` ` `"),"sanitize");function formatDiagnostics(e){if(0===e.length)return"No diagnostics found. All files are clean.";const t=[];let n=0,r=0,o=0,s=0;for(const i of e){t.push(`${$v(i.relativePath)}:`);for(const e of i.diagnostics){const i=`L${e.range.startLine}:${e.range.startCol}`,a=e.code?` ${$v(e.code)}`:"",l=e.source?` [${$v(e.source)}]`:"";switch(t.push(` ${i} ${e.severity}${a}: ${$v(e.message)}${l}`),e.severity){case"error":n++;break;case"warning":r++;break;case"information":o++;break;case"hint":s++}}t.push("")}const i=[];n>0&&i.push(`${n} error${1!==n?"s":""}`),r>0&&i.push(`${r} warning${1!==r?"s":""}`),o>0&&i.push(`${o} info`),s>0&&i.push(`${s} hint${1!==s?"s":""}`);const a=`${e.length} file${1!==e.length?"s":""}`;return t.push(`Summary: ${i.join(", ")} across ${a}`),t.join("\n")}__name(formatDiagnostics,"formatDiagnostics");var Dv={name:"diagnostics",description:"Get LSP diagnostics (errors, warnings, hints) from the IDE. Returns type errors, lint warnings, and other language server diagnostics reported by all active language servers (TypeScript, ESLint, Python, etc.). Only available when connected to an IDE with the Command Code extension. Pass specific file paths when you know which files are relevant. Only omit filePaths to scan the entire workspace when the user explicitly asks for all workspace diagnostics.",input_schema:{type:"object",properties:{filePaths:{type:"array",items:{type:"string"},description:'Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.'}},required:[]},execute:__name(async e=>{const t=parseRepairedToolInput({toolName:"diagnostics",schema:sv,input:e});return t.ok?formatDiagnostics(await fetchDiagnostics(t.data.filePaths)):t.message},"execute")};Ot(),Ot(),Ot(),wn();var Ov="Coding agent that continuously learns your taste of writing code.",Fv=34,qv="Connect IDE to share your open file and selected lines",jv=[{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"},{key:"Alt+P",description:"Quick model switch (Option+P on macOS)"},{key:"Ctrl+G",description:"Open input in external editor ($EDITOR)"},{key:"Press Esc twice",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Uv=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume [name]",description:"Resume a conversation by name (use quotes for multi-word names), or pick from history"},{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:"--auto-accept",description:"Start in auto-accept mode"},{key:"--yolo",description:"Bypass all permission prompts (alias for --dangerously-skip-permissions)"},{key:"--add-dir <directory>",description:"Add directory to workspace context"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"--ide-setup",description:qv},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],Bv=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rename [name]",description:"Rename the current session"},{key:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/mcp",description:"Manage MCP server connections"},{key:"/model",description:"Switch between Command Code models"},{key:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{key:"/compact",description:"Compact the conversation history"},{key:"/compact-mode",description:"Select a compact mode to compact sessions"},{key:"/context",description:"Show context window usage and breakdown"},{key:"/ide",description:qv},{key:"/login",description:"Log in to Command Code"},{key:"/logout",description:"Log out of Command Code"},{key:"/courses",description:"Open Command Code courses in your browser"},{key:"/feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"/review [pr]",description:"Review a pull request (optional PR number)"},{key:"/pr-comments",description:"Fetch all PR comments for current branch"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/status",description:"Show comprehensive environment status"},{key:"/usage",description:"Display credits, plan, and usage metrics"},{key:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],zv=[{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 taste learn <source>",description:"Learn taste from a local repository or GitHub repo"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd skills",description:"Manage skills from GitHub repositories"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Log out of Command Code"}],Hv=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Wv=[{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 --resume "auth refactor"',description:"Resume a named session"},{key:'cmd -p "your query"',description:"Run non-interactive query"},{key:"cmd taste learn .",description:"Learn taste from the current repository"},{key:"cmd taste learn owner/repo",description:"Learn taste from a GitHub repository"},{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"}],Gv='Start with a prompt: cmd "fix the login bug"';function formatHelpItems(e){return e.map(e=>`- ${e.key}: ${e.description}`).join("\n")}function getSelfKnowledge(){return`# Command Code — Product Knowledge\n\n## KEYBOARD SHORTCUTS\n${formatHelpItems(jv)}\n\n## SLASH COMMANDS (type these in the chat input)\n${formatHelpItems(Bv)}\n\n## CLI SUBCOMMANDS\n${formatHelpItems(zv)}\n\n## CLI EXAMPLES\n${formatHelpItems(Wv)}\n\n## CLI OPTIONS (flags when launching cmd)\n${formatHelpItems(Uv)}\n\n## TASTE SYSTEM\nTaste is powered by the meta neuro-symbolic AI model taste-1 with continuous reinforcement learning (RL). It combines reasoning with neural intuition to learn your coding preferences.\n\nHow taste works:\n- Learns from you — every accept, reject, and edit becomes a signal\n- Thinks like you — learns patterns and micro-decisions you'd never document\n- Grows with you — continuous learning loop that never goes stale\n\nEnable taste: Use /taste in a session or run npx taste from the command line.\n\nTaste packages (three types):\n- Project: Stored in .commandcode/taste/ — learnings unique to this codebase\n- Global: Stored in ~/.commandcode/taste/ — personal taste across all projects (use -g flag)\n- Remote: Stored at commandcode.ai/username/taste — team sharing, backup, sync across machines\n\nFile structure:\n .commandcode/taste/\n ├── taste.md (main taste file)\n ├── cli/taste.md\n ├── typescript/taste.md\n └── architecture/taste.md\n\nKey commands:\n- npx taste push --all — push entire project taste to remote\n- npx taste pull username/project-name — pull taste from remote\n- npx taste push cli -g — push package to global\n- npx taste pull cli -g — pull package from global\n- npx taste list — list available packages\n- npx taste lint — validate package format\n- npx taste open — open packages in editor\n\nPrivacy: Taste processing runs on your codebase and stores learning data locally only.\n\n## KEY FEATURES\n- Taste System: Automatically learns coding preferences from interactions and applies them consistently\n- Skills: User-defined knowledge modules for specialized tasks (stored in .commandcode/skills/ or .agents/skills/)\n- Agents: Custom agent configurations for different workflows (stored in .commandcode/agents/)\n- Memory: Project-specific instructions via COMMANDCODE.md files\n- MCP: Model Context Protocol server connections for extended tool capabilities\n- Plan Mode: Structured exploration and planning before implementation [Shift+Tab to toggle]\n- Conversation Management: Resume, continue, share, and rewind conversations\n- PR Review: Built-in pull request review capabilities (/review command)\n- Learning Feed: View what taste is learning in real-time [Ctrl+T to toggle]\n- Model Switching: Switch between models with Alt+P (Option+P on macOS)\n\n## FREQUENTLY ASKED QUESTIONS\nQ: What is Command Code?\nA: Command Code is the first coding agent that automatically learns your taste of writing great code.\n\nQ: What is taste-1?\nA: taste-1 is our meta neuro-symbolic AI model with continuous reinforcement learning (RL).\n\nQ: Is Command Code free?\nA: Command Code offers both free and premium plans. Check https://commandcode.ai/pricing for details.\n\nQ: How do I install Command Code?\nA: Run npm i -g command-code, then cmd login, then cmd to start.\n\nQ: What are Agent Skills?\nA: Reusable instructions that teach Command Code how to handle specific tasks like code reviews, testing, or commit messages. Use /skills to browse them.\n\nQ: What are MCP servers?\nA: MCP (Model Context Protocol) servers let Command Code connect to external tools and data sources like GitHub, Notion, databases, and more. Use /mcp to manage them.\n\nQ: What is plan mode?\nA: Plan mode lets you review and approve Command Code's approach before it writes any code. Press Shift+Tab to toggle it.\n\nQ: What is headless mode?\nA: Headless mode lets you run Command Code non-interactively in scripts, CI/CD pipelines, and automation workflows. Use cmd -p "query" to run.\n\nQ: How do I fix "command not found" after installing?\nA: Ensure your global npm bin directory is in your PATH. Run npm config get prefix to find it, then add <prefix>/bin to your PATH.\n\nQ: Why am I getting unauthorized errors?\nA: Run cmd logout followed by cmd login to refresh your session. If the issue persists, check your account at https://commandcode.ai/studio.\n\nQ: How do I check my usage limits?\nA: Visit the billing page in Command Code Studio at https://commandcode.ai/studio.\n\nQ: My MCP server won't connect. What should I do?\nA: Check the server config with cmd mcp get <name> and use /mcp inside a session to see the error. For stdio servers, ensure the command is installed and in your PATH.\n\nQ: Where can I get help?\nA: Join our Discord at https://commandcode.ai/discord, report issues on GitHub, or email support@commandcode.ai.\n\n## TROUBLESHOOTING\n\n### Installation\n- "command not found" after install: Ensure global npm bin directory is in PATH. Run npm config get prefix, add <prefix>/bin to PATH, restart terminal.\n\n### Authentication\n- Login fails or session expired: Run cmd logout then cmd login. If still failing, delete ~/.commandcode/auth.json and retry.\n- API key or provider issues: Verify provider config, check API key validity, check usage limits.\n- Chrome Local Network Access prompt during login: Click "Allow" — this is expected and safe. Command Code runs a temporary local server for OAuth callback.\n\n### MCP Servers\n- Server won't connect: Check config with cmd mcp get <name>, verify command is in PATH, use /mcp in session for error details.\n- Authentication issues: Re-authenticate with cmd mcp auth <server>, or clear and retry with cmd mcp auth --clear <server>.\n\n### Skills\n- Not appearing in /skills menu: Check directory structure (.commandcode/skills/ or .agents/skills/), verify SKILL.md exists with valid frontmatter.\n- Editor not opening: Check $EDITOR is set and the editor is in PATH.\n- Skill not being used: Make description more specific with keywords, ask Command Code explicitly to use the skill.\n\n### Performance\n- Slow responses: Check internet connection, disconnect unneeded MCP servers, keep prompts focused and specific.\n- High token usage: Review usage in Studio, use headless mode for scripted tasks, use plan mode to agree on approach first.\n\n### Support\n- Discord: https://commandcode.ai/discord\n- GitHub: https://github.com/commandcode/command-code\n- Email: support@commandcode.ai\n\n## PRICING & LIMITS\nHow it works:\n- Monthly reset: Request limits reset at the start of each billing cycle.\n- Auto top-up: Buy extra credits at model cost. Credits roll over and never expire.\n- No AI training: Command Code does not train on your code or store your code snippets.\n\nManage your plan:\n- Purchase credits or subscribe: Studio > Billing at https://commandcode.ai/settings/billing\n- Track usage: https://commandcode.ai/usage\n- Manage payment methods: Access billing portal from Studio > Billing\n\nPremium requests: Any request that uses a premium model (like taste-1) during your coding session.\nWhen you hit your limit: Continue with auto top-up enabled. Extra credits are purchased at model cost and roll over.\nSwitch plans: Upgrade or downgrade anytime from Studio > Billing. Changes take effect next billing cycle.\nTeam billing: Billed per seat. Credits are pooled at the team level.\n\nEnterprise: Enhanced security, compliance, and control. Contact support@commandcode.ai for Enterprise edition.\n\n## PRIVACY & LEGAL\n- Command Code does not train on your code or store your code snippets.\n- Taste processing runs on your codebase and stores learning data in your project and on your local machine only.\n- Privacy Policy: https://commandcode.ai/privacy\n- Terms of Service: https://commandcode.ai/terms\n\n## HELPFUL LINKS\n${formatHelpItems(Hv)}`}__name(formatHelpItems,"formatHelpItems"),__name(getSelfKnowledge,"getSelfKnowledge");var Vv={name:"get_self_knowledge",description:"Retrieve Command Code product documentation — features, shortcuts, commands, options, taste, FAQs, troubleshooting, pricing, or privacy. Call this whenever the user asks about Command Code capabilities or needs help. Authoritative source — do NOT search the codebase. Call once per conversation. After the first call, the information is already in your context — do not call again.",input_schema:{type:"object",properties:{},required:[]},execute:__name(async()=>getSelfKnowledge(),"execute")};yS(),zS(),BS(),Ot(),Ot(),Ot(),wn(),Ot(),Ot();var Qv=["explore","plan","review","general"],Kv=[{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\n5. Stay inside the current workspace. Do not read sibling projects, parent directories, or unrelated paths to draw inspiration — even if structurally similar code exists nearby. The user\'s project is its own context.\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&&Qv.includes(e.toLowerCase())}function getRootAgentDir(){return t.join(S.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=Ke(s),l=i.name||r.replace(".md","");if(isReservedAgentName(l))return null;let u=i.tools||"";return"*"!==u&&'"*"'!==u||(u="*"),{name:l,description:i.description||"",tools:u,systemPrompt:a.trim(),location:n,filePath: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"),Ot(),wn(),ao(),sS(),fS(),Lo(),Rs(),Ot(),Ot();var Yv={"\n":"\\n","\r":"\\r","\t":"\\t"},Jv=['"}','"}}',"}",'": ""}'];function isPlainObject(e){return"object"==typeof e&&null!==e}function escapeControlCharsInJsonStrings(e){const t=[];let n=!1,r=0;for(;r<e.length;){const o=e[r];if(!n){'"'===o&&(n=!0),t.push(o),r++;continue}if("\\"===o){t.push(o,e[r+1]??""),r+=2;continue}if('"'===o){n=!1,t.push(o),r++;continue}const s=o.charCodeAt(0);s>=32?(t.push(o),r++):(t.push(Yv[o]??`\\u${s.toString(16).padStart(4,"0")}`),r++)}return t.join("")}function repairTruncatedJson(e){if(!e.startsWith("{"))return null;for(const t of Jv)try{const n=JSON.parse(e+t);if(isPlainObject(n))return n}catch{}return null}function tryParseDirectly(e){try{const t=JSON.parse(e);if(isPlainObject(t))return t;if("string"==typeof t)return parseToolArgs(t)}catch{}return null}function tryParseAfterEscaping(e){try{const t=JSON.parse(escapeControlCharsInJsonStrings(e));if(isPlainObject(t))return t}catch{}return null}function parseToolArgs(e){return tryParseDirectly(e)??tryParseAfterEscaping(e)??repairTruncatedJson(e)??repairTruncatedJson(escapeControlCharsInJsonStrings(e))}function normalizeToolInput(e){return"string"!=typeof e?e:parseToolArgs(e)??e}__name(isPlainObject,"isPlainObject"),__name(escapeControlCharsInJsonStrings,"escapeControlCharsInJsonStrings"),__name(repairTruncatedJson,"repairTruncatedJson"),__name(tryParseDirectly,"tryParseDirectly"),__name(tryParseAfterEscaping,"tryParseAfterEscaping"),__name(parseToolArgs,"parseToolArgs"),__name(normalizeToolInput,"normalizeToolInput"),Ot(),Kn();var Xv=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${Pe.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${Pe.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${Pe.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${Pe.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}},Zv=new Xv("SSEStreamConsumer");function formatToolResultOutput(e){if(e.output&&"object"==typeof e.output)return e.output;const t=e.result??e.output??"",n="string"==typeof t?t:JSON.stringify(t);return!0===e.isError?{type:"error-text",value:n}:{type:"text",value:n}}async function consumeSSEStream(e,t){const n=e.getReader(),r=new TextDecoder,o=[];let s=null,i="",a=0,l=0,u=0,d=0,m=null,g="";try{for(;;){const{done:e,value:h}=await n.read();if(e)break;g+=r.decode(h,{stream:!0});const f=g.split("\n");g=f.pop()||"";for(const e of f){const n=e.trim();if(!n)continue;let r;try{r=JSON.parse(n)}catch{continue}if("text-delta"!==r.type)if("reasoning-delta"!==r.type)if("reasoning-end"!==r.type)if("tool-call"!==r.type)if("tool-result"!==r.type){if("finish"===r.type){const e=r.totalUsage;e&&(a=e.inputTokens||0,l=e.outputTokens||0,u=e.inputTokenDetails?.cacheReadTokens||0,d=e.inputTokenDetails?.cacheWriteTokens||0),m="tool-calls"===r.finishReason?"tool_calls":"end_turn";continue}if("error"===r.type){const e=r.error,t=e?.message||r.error||"Stream error",n=new Error("string"==typeof t?t:String(t));throw null!=e?.statusCode&&(n.statusCode=e.statusCode),null!=e?.isRetryable&&(n.isRetryable=e.isRetryable),n}}else s=null,o.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:formatToolResultOutput(r),providerExecuted:!0===r.providerExecuted||void 0});else s=null,Zv.debug(`[SSE] tool-call: name=${r.toolName}, id=${r.toolCallId}`),o.push({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:normalizeToolInput(r.input??r.args??{}),providerExecuted:!0===r.providerExecuted||void 0});else i&&(o.push({type:"reasoning",text:i}),i="");else i+=r.text??"";else s||(s={type:"text",text:""},o.push(s)),s.text+=r.text,t?.onText?.(r.text)}}}finally{n.releaseLock()}i&&o.push({type:"reasoning",text:i});const h=o.filter(e=>"tool-call"===e.type).length;return h>0&&Zv.debug(`[SSE] Stream complete: ${o.length} blocks, ${h} tool calls, stop_reason=${m}`),{content:o,usage:{input_tokens:a,output_tokens:l,cache_read_input_tokens:u||void 0,cache_creation_input_tokens:d||void 0},stop_reason:m}}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),i=await readFileContent({absolutePath:t});if("binary"===i.contentType)continue;const a=String(i.content),l=e.relative(process.cwd(),t),u=1e5;if(a.length>u){n.push({token:o,resolvedPath:t,content:"",tooLarge:!0});const e=`${l}`;r=r.replace(o,e);continue}n.push({token:o,resolvedPath:t,content:a});const d=`{${l}: ${a}}`;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(formatToolResultOutput,"formatToolResultOutput"),__name(consumeSSEStream,"consumeSSEStream"),Ot(),wn(),Kn(),sS(),fS(),Ot(),xE(),Ot(),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),wn(),hs(),Kn(),Ot(),Ot(),Ot(),Ot();var ek="command-message",tk="command-name",nk="command-args";function extractCommandTag({text:e,tagName:t}){const n=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),r=e.match(n);return r?r[1]?.trim()??null:null}function parseCommandTags({text:e}){return{commandMessage:extractCommandTag({text:e,tagName:ek}),commandName:extractCommandTag({text:e,tagName:tk}),commandArgs:extractCommandTag({text:e,tagName:nk})}}function renderCommandTagMessage({text:e}){const t=parseCommandTags({text:e}),{commandMessage:n,commandName:r,commandArgs:o}=t;if(!n&&!r)return null;if(n){const e=`/${n}`;return o?`${e} ${o}`:e}if(!r)return null;const s=r.startsWith("/")?r:`/${r}`;return o?`${s} ${o}`:s}__name(extractCommandTag,"extractCommandTag"),__name(parseCommandTags,"parseCommandTags"),__name(renderCommandTagMessage,"renderCommandTagMessage"),Ot();var rk=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext");function isHiddenTranscriptMessage({message:e}){return!0===e.meta.isMeta}function extractTextFromMessageContent({content:e}){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e)"text"===n.type&&"string"==typeof n.text&&(t+=n.text);return t}function renderVisibleUserMessageText({content:e}){const t=rk(extractTextFromMessageContent({content:e})).trim();return renderCommandTagMessage({text:t})||t}__name(isHiddenTranscriptMessage,"isHiddenTranscriptMessage"),__name(extractTextFromMessageContent,"extractTextFromMessageContent"),__name(renderVisibleUserMessageText,"renderVisibleUserMessageText"),Gf();var ok=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(S.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Fe(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=Se("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await k.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:cs.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await k.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,version:2,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await k.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 k.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let o=0;const s=[];for(const t of e)try{s.push(JSON.parse(t))}catch(e){o++,console.error("Error parsing session line:",e)}if(s.some(e=>isLegacyFormat(e))){const e=legacyAnthropicToSession(s.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))),o=s.filter(e=>"user"===e.role||"assistant"===e.role);let i=0;for(const n of e){const e=o[Math.min(i,o.length-1)];"tool"!==n.role&&"user"!==n.role||i++,t.push({message:n,meta:{timestamp:e?.timestamp??(new Date).toISOString(),source:"cli",...e?.metadata||{}}})}dlog(`[Session] Migrating v1 session to v2: ${r} (${t.length} messages)`);const a=t.map(e=>JSON.stringify({id:crypto.randomUUID(),timestamp:e.meta.timestamp,sessionId:n,parentId:null,role:e.message.role,content:e.message.content,gitBranch:this.gitBranch,metadata:{...e.meta,version:2}}));await k.writeFile(r,a.join("\n")+"\n").catch(()=>{})}else for(const e of s)"user"!==e.role&&"assistant"!==e.role&&"tool"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}});return{messages:t,corruptedLines:o,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){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message,r=Date.now(),o=crypto.randomUUID();if("tool"!==e.role)if("user"===e.role){const n=renderVisibleUserMessageText({content:e.content});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-call"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=CE(r.toolName,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.toolName,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 k.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 k.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await k.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 k.access(n)}catch{return[]}const e=(await k.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 k.stat(s),o=(await k.readFile(s,"utf-8")).trim().split("\n").filter(e=>e.trim());if(o.length>0){let s="",i="";const a=JSON.parse(o[0]);a.gitBranch&&(i=a.gitBranch);let l=0;for(const e of o){const t=JSON.parse(e);!0!==t.metadata?.isMeta&&(l++,s||"user"!==t.role||(s=renderVisibleUserMessageText({content:t.content}),!s&&"object"==typeof t.content&&null!==t.content&&"input"in t.content&&"string"==typeof t.content.input&&(s=t.content.input)))}s=rk(s);const u=await _SessionManager.loadSessionMetaForId(e,n),d=u?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:s||"No messages",title:d||void 0,messageCount:l,projectPath:n,gitBranch:i||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const n=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await k.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 k.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 k.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await k.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};return await k.writeFile(this.getMetaFilePath(),JSON.stringify(t,null,2)),!0}catch(e){return dlog("Session",`Failed to save session meta: ${e}`),!1}}async saveSessionTitle(e){return await this.saveSessionMeta({title:e})}async loadSessionTitle(){const e=await this.loadSessionMeta();return e?.title||null}async loadUserRenamedTitle(){const e=await this.loadSessionMeta();return e?.userRenamed&&e.title?e.title:null}static async loadProjectMetaFiles(){const e=_SessionManager.getCurrentProjectDirName(),n=t.join(_SessionManager.getProjectsBasePath(),e);try{await k.access(n)}catch{return[]}const r=(await k.readdir(n)).filter(e=>e.endsWith(".meta.json"));return Promise.all(r.map(async e=>{const t=e.slice(0,-10);return{sessionId:t,meta:await _SessionManager.loadSessionMetaForId(t,n)}}))}static async isSessionNameTaken({name:e,excludeSessionId:t}){const n=e.trim().toLowerCase();return!!n&&(await _SessionManager.loadProjectMetaFiles()).some(({sessionId:e,meta:r})=>(!t||e!==t)&&r?.title?.trim().toLowerCase()===n)}static async findSessionByName(e){const t=e.trim().toLowerCase();if(!t)return null;const n=(await _SessionManager.loadProjectMetaFiles()).find(({meta:e})=>e?.title?.trim().toLowerCase()===t);return n?{id:n.sessionId}:null}static async loadSessionMetaForId(e,n){const r=t.join(n,`${e}.meta.json`);try{const e=await k.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 k.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 k.writeFile(r,s)}else await k.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 k.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 k.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 k.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=rk(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}};Lo(),Jr(),ao();var sk=new Map,ik=sn.MINIMAX_M2_5.id;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)}`}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=sk.get(n);if(r)return sk.delete(n),sk.set(n,r),dlog("[ToolDescription] cache hit",{toolName:e,description:r}),r;const o=Date.now();try{const r=createPrompt(t),o=await getConfiguredProvider(),s=await isOAuthEnforced(),i={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:s.toString()},{token:a,oauthProvider:l}=await getOAuthCredentials({provider:o});a&&(i[Ut.OAUTH_TOKEN]=`Bearer ${a}`,l&&(i[Ut.OAUTH_PROVIDER]=l));const u={config:getEnvironmentContext(),memory:"",taste:"",skills:"",mode:"tool-desc",params:{tools:[],messages:[{role:"user",content:r}],model:ik,system:'Precisely describe what a shell 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\nOutput the description only — no preamble, no explanation, no quotes.',max_tokens:500,temperature:1,stream:!0},threadId:crypto.randomUUID()},d=getApiBaseUrl(),m=new jw({baseUrl:d}).post({endpoint:Bt.ALPHA.GENERATE,body:u,headers:i,stream:!0}).then(e=>consumeSSEStream(e)),g=await Promise.race([m,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),1e4))]);if(!g)return dlog("[ToolDescription] empty",{toolName:e,model:ik}),null;const h=g.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("").trim(),f=cleanDescription(h);if(f){if(sk.size>=100){const e=sk.keys().next().value;void 0!==e&&sk.delete(e)}sk.set(n,f),dlog("[ToolDescription] done",{toolName:e,model:ik,description:f,tokensIn:g.usage.input_tokens,tokensOut:g.usage.output_tokens,cached:g.usage.cache_read_input_tokens??0})}else dlog("[ToolDescription] rejected",{toolName:e,raw:h});return f}catch(t){return dlog("[ToolDescription] error",{toolName:e,durationMs:Date.now()-o,error:t instanceof Error?t.message:String(t)}),null}}function sanitize2(e){return String(e).replace(/[\r\n\t\f\v]+/g," ").replace(/\s+/g," ").trim().slice(0,4e3)}function createPrompt(e){return`Command: ${`${sanitize2(e.command||"")} ${sanitize2(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}__name(stableStringify,"stableStringify"),__name(generateCacheKey,"generateCacheKey"),__name(generateToolDescription,"generateToolDescription"),__name(sanitize2,"sanitize"),__name(createPrompt,"createPrompt"),__name(cleanDescription,"cleanDescription"),yS(),Ot(),xo(),zS();var ak,lk=["edit_file","delete_file","shell_command","todo_write","kill_shell"],ck=["exit_plan_mode"],uk=["enter_plan_mode"];function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n||"bypass"===n?t.filter(e=>!ck.includes(e.name)):"plan"===n?t.filter(e=>!lk.includes(e.name)&&!uk.includes(e.name)):t.filter(e=>!ck.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||"bypass"===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 lk.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.`}}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})})}function setBenchmarkOutput(e){ak=e}function createBenchmarkCollector(){return ak?{startTime:Date.now(),turnDetails:[],agents:[],maxTurnsReached:!1}:null}__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode"),Ot(),__name(sleep,"sleep"),xE(),Jr(),yS(),Ot(),__name(setBenchmarkOutput,"setBenchmarkOutput"),__name(createBenchmarkCollector,"createBenchmarkCollector");var dk="\x3c!-- BENCHMARK_AGENT_METRICS:",mk=" --\x3e";function buildAgentMetricsMarker(e){return`\n${dk}${JSON.stringify(e)}${mk}`}function extractAgentMetrics(e){const t=e.indexOf(dk);if(-1===t)return{cleanContent:e,metrics:null};const n=t+29,r=e.indexOf(mk,n);if(-1===r)return{cleanContent:e,metrics:null};try{const o=e.substring(n,r),s=JSON.parse(o);return{cleanContent:e.substring(0,t).trimEnd()+e.substring(r+4),metrics:s}}catch{return{cleanContent:e,metrics:null}}}function createAgentBenchmarkTracker(){return ak?{turns:0,toolCalls:{},toolErrors:0}:null}function trackAgentTurn(e){e&&e.turns++}function trackAgentToolCall(e){const{tracker:t,toolName:n,isError:r}=e;t&&(t.toolCalls[n]=(t.toolCalls[n]??0)+1,r&&t.toolErrors++)}function buildAgentResult(e){const{result:t,tracker:n,agentName:r,startTime:o,tokens:s}=e;return n?t+buildAgentMetricsMarker({name:r,turns:n.turns,toolCalls:n.toolCalls,toolErrors:n.toolErrors,tokens:s,durationMs:Date.now()-o}):t}function writeBenchmarkMetrics(e){if(!ak)return;const t=Date.now()-e.startTime,n=e.turnDetails.length,r={};let o=0,s=0,i=0,a=0;for(const t of e.turnDetails){for(const e of t.toolCalls)o++,r[e.name]=(r[e.name]??0)+1,e.isError&&s++;i+=t.inputTokens,a+=t.outputTokens}const l={wallTimeMs:t,turns:n,turnDetails:e.turnDetails,toolCalls:{total:o,byType:r,errors:s},tokens:{input:i,output:a},maxTurnsReached:e.maxTurnsReached,agents:e.agents};try{L.writeFileSync(ak,JSON.stringify(l,null,2))}catch{}}__name(buildAgentMetricsMarker,"buildAgentMetricsMarker"),__name(extractAgentMetrics,"extractAgentMetrics"),__name(createAgentBenchmarkTracker,"createAgentBenchmarkTracker"),__name(trackAgentTurn,"trackAgentTurn"),__name(trackAgentToolCall,"trackAgentToolCall"),__name(buildAgentResult,"buildAgentResult"),__name(writeBenchmarkMetrics,"writeBenchmarkMetrics");var pk=new Xv("AgentExecutor");function agentToTool(t,n){const{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:i}=n;return{name:t.name,description:t.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object",properties:{content:{type:"string",description:"The text content of the message"}},required:["content"]}}},required:["messages"]},execute:__name(async(n,a)=>{let l=null;const u=Date.now();let d=null;try{const m=a?.permissionMode||"standard",g=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:o,toolsMap:s,displayNameToToolName:i}),clientTools:r,serverTools:o,mode:m});let h=Date.now();const f=10,y=[];if(a?.onFeedUpdate){const e=CE(t.name,n);l=pE({name:t.name,input:e}),a.onFeedUpdate(l)}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3);const w=createAgentBenchmarkTracker(),S=await getConfiguredProvider(),E=await isOAuthEnforced(),{token:C,oauthProvider:v}=await getOAuthCredentials({provider:S});validateOAuthToken({token:C,provider:S});const k=getApiBaseUrl(),T=new jw({baseUrl:k});let _=0;const x=[];let A=n?.messages;if("string"==typeof A)try{A=JSON.parse(A)}catch(e){A=[]}if(Array.isArray(A)&&A.length>0)for(const e of A)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&x.push({role:"user",content:t})}const P={stream:!0,messages:x,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:g,model:getConfiguredModel()},I=await isTasteLearningEnabled(),N={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.TASTE_LEARNING]:I.toString(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:E.toString(),...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};C&&(N[Ut.OAUTH_TOKEN]=`Bearer ${C}`,v&&(N[Ut.OAUTH_PROVIDER]=v));const R=getEnvironmentContext(),M=await getMemoryContent([]),L=crypto.randomUUID();let $="",D=!0;const O=__name(()=>{pk.debug("[Agent] Abort signal triggered, stopping immediately"),D=!1,d&&(clearInterval(d),d=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",O);try{for(;D;){if(a?.abortSignal?.aborted)throw pk.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:T,body:{mode:"custom-agent",config:R,memory:M,threadId:L,params:{...P,messages:x}},headers:N,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{_+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&l&&t-h>=f){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:_,elapsedSeconds:e}},a.onFeedUpdate(l),h=t}},"onTextDelta")});if(trackAgentTurn(w),a?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(_=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool-call"===e.type&&!e.providerExecuted);if($=t.content.filter(e=>"tool-call"===e.type&&!!e.providerExecuted).length>0?processServerToolBlocks(t,a):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===n.length){const e=t.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);e.length>0&&x.push({role:"assistant",content:e}),D=!1;break}const r=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);r.length>0&&x.push({role:"assistant",content:r});const o=[],s=new Set;let i=!1;for(const t of n){if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{const r=dS.includes(t.toolName),g="auto-accept"!==m&&"bypass"!==m&&mS.includes(t.toolName)?Promise.race([generateToolDescription(t.toolName,n).catch(()=>null),new Promise(e=>setTimeout(()=>e(null),5e3))]):Promise.resolve(null);if(r&&a?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await g;if(!await a.onPermissionRequest(t.toolName,n,e)){pk.debug(`Permission denied for tool: ${t.toolName}`),i=!0;break}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let 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,pk.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,pk.debug(`Resolved input for ${t.toolName}: ${CE(t.toolName,n)}`)):pk.debug(`No path resolution needed for ${t.toolName}: ${CE(t.toolName,n)}`)}if(a?.onFeedUpdate&&l){const e=CE(t.toolName,n);y.push({name:t.toolName,input:e}),y.length>3&&y.shift();const r=Date.now(),o=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:_,elapsedSeconds:o,recentTools:[...y]}},pk.debug(`Updating agent with recentTools (${y.length} tools): ${JSON.stringify(y)}`),a.onFeedUpdate(l)}const h=await executeTool(t.toolName,n,{abortSignal:a?.abortSignal,permissionMode:m});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const f=checkToolOutputTokensLimit(h);if(o.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:{type:"text",value:f}}),s.add(t.toolCallId),trackAgentToolCall({tracker:w,toolName:t.toolName,isError:!1}),a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:_,elapsedSeconds:t,recentTools:[...y]}},a.onFeedUpdate(l)}pk.debug(`Tool executed successfully: ${t.toolName}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";o.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:{type:"error-text",value:`Error: ${n}`}}),s.add(t.toolCallId),trackAgentToolCall({tracker:w,toolName:t.toolName,isError:!0}),pk.error(`Tool execution failed: ${t.toolName} - ${n}`)}}if(i){const e=x[x.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool-call"===e.type?s.has(e.toolCallId):"text"===e.type);t.length>0?e.content=t:x.pop()}D=!1;break}x.push({role:"tool",content:o})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",O)}if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:$||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:_,elapsedSeconds:t}},a.onFeedUpdate(l)}return buildAgentResult({result:$||"DONE",tracker:w,agentName:t.name,startTime:u,tokens:_})}catch(e){if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const t=Date.now(),n=(t-u)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||a?.abortSignal?.aborted;l={...l,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:u,endTime:t,tokensUsed:l?.metadata?.tokensUsed||0,elapsedSeconds:n}},a.onFeedUpdate(l)}throw e}},"execute")}}function filterToolsForMode(e){const{tools:t,clientTools:n,serverTools:r,mode:o}=e;if("standard"===o||"auto-accept"===o||"bypass"===o)return t;const s=t.filter(e=>n.includes(e)),i=t.filter(e=>r.includes(e));return[...getToolsForMode({allTools:s,mode:o}),...i]}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let i=[];if("*"===e.tools)i=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)i.push(e);else{const e=r.find(e=>e.name===t);e&&i.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)i.push(t);else{const t=r.find(t=>t.name===e);t&&i.push(t)}}}return i}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let i=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:Bt.ALPHA.GENERATE,signal:o,headers:r});return await consumeSSEStream(e,{onText:s})}catch(t){if(i=t,pk.debug(`[callAPIWithRetry] Error on attempt ${e+1}/5: ${t.message||t}, status=${t.status}, code=${t.code}, retryable=${isRetryableError(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);pk.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw i||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof bs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof vs||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","fetch failed","ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","network error","socket hang up","UND_ERR_CONNECT_TIMEOUT"].some(t=>e.message.includes(t))||e?.status>=500&&e?.status<600)}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 bs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof vs||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=>"tool-call"===e.type&&e.providerExecuted).length)return"";let n="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("tool-call"===e.type&&e.providerExecuted&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:o}=uS({serverToolBlock:e,contentBlocks:r}),s=CE(e.toolName,e.input),i={id:`${e.toolName}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.toolName,input:s,output:o?hE(n):n};t.onFeedUpdate(i)}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 gk=new Map,hk=null;function initializeAgentManager(e){hk=e}async function loadAgentTools(){if(!hk)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");gk.clear();for(const e of Kv){const t=agentToTool(e,hk);gk.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,hk);gk.set(t.name,t)}}async function getAgentTools(){return 0===gk.size&&await loadAgentTools(),Array.from(gk.values())}async function getAgentTool(e){return 0===gk.size&&await loadAgentTools(),gk.get(e)}function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,o=e.join(r,".commandcode","taste"),s=e.normalize(e.resolve(r,n)),i=e.normalize(o);return s.startsWith(i)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),o=e.normalize(e.join(w.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 i=e.relative(s,n).split(e.sep);return 1===i.length?{isTaste:!0}:2===i.length?{isTaste:!0,category:i[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),Ot(),wn(),__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"),hs(),Ao();var fk=[kC,RC,$C,DC,UC,WC,QC,KC,YC,JC,XC,tv,nv,rv,Dv,Vv],yk=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],wk=new Map(fk.map(e=>[e.name,e])),Sk=new Set([...fk.map(e=>e.name),...yk.map(e=>e.name)]);function isAgentTool(e){return!Sk.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";setCurrentPermissionMode(r);const 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=wk.get(e);if(s||(s=await getAgentTool(e)),!s){const t=await getAgentTools(),n=[...Array.from(wk.keys()),...t.map(e=>e.name)];throw new Error(`Tool "${e}" not found. Available tools: ${n.join(", ")}`)}if(("write_file"===e||"edit_file"===e)&&!0!==n?.allowTasteWrite){const e=t.filePath,n=isPathInTasteDirectory({filePath:e,projectRoot:process.cwd()});if(e&&n)throw new Error("Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system.".replace("Error: ",""))}const i=trackToolStart({toolName:e});try{let r;return r=(!wk.has(e)||!0===s.acceptsCallbacks)&&n?await s.execute(t,n):await s.execute(t),i.end({status:"success"}),r}catch(t){if(t instanceof Error&&"Interrupted by user"===t.message){const e=sanitizeErrorForTelemetry({error:t,label:"tool_interrupted"});throw i.end({status:"error",error:e}),t}if(t instanceof y){const n=sanitizeErrorForTelemetry({error:t,label:`tool_input_invalid:${e}`});return i.end({status:"error",error:n}),formatZodErrorForModel(e,t)}if(t instanceof Error){const e=sanitizeErrorForTelemetry({error:t,label:"tool_error"});return i.end({status:"error",error:e}),`Error: ${t.message}`}return i.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(e){const t=e?.mode||"standard",n=null!==vv()?[...fk]:fk.filter(e=>e.name!==iS.DIAGNOSTICS),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 i=[];return"plan"!==t&&getMcpConnectionManager().isInitialized&&(i=getAllMcpToolSchemas()),[...o,...s,...i,...yk]}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 Ek={};fk.forEach(e=>{Ek[e.name]=toPascalCase(e.name)}),yk.forEach(e=>{Ek[e.name]=toPascalCase(e.name)});var bk={};Object.entries(Ek).forEach(([e,t])=>{bk[t]=e}),initializeAgentManager({clientTools:fk,serverTools:yk,toolsMap:wk,displayNameToToolName:bk}),Rs();var Ck=null,vk=!1,kk=new Set([iS.EDIT_FILE,iS.WRITE_FILE,iS.SHELL_COMMAND]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(vk)return;vk=!0;const e=__name(e=>{Ck?.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(),Ck=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{e.model&&setModelOverride(e.model),e.benchmarkOutput&&setBenchmarkOutput(e.benchmarkOutput);const n=await processQuery({query:t,signal:Ck.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions,maxTurns:e.maxTurns??Tk,verbose:e.verbose??!1});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 Cs&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof vs&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof xs&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Es&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof As&&(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 Tk=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced(),{token:r,oauthProvider:o}=await getOAuthCredentials({provider:t});validateOAuthToken({token:r,provider:t});const s=getEnvironmentContext(),i=await getMemoryContent([]),a=await getTasteContent(),l=generateSkillsXML(await loadAllSkillSummaries())||null,u=crypto.randomUUID(),d=await isTasteLearningEnabled(),m={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.TASTE_LEARNING]:d.toString(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:n.toString(),...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};return r&&(m[Ut.OAUTH_TOKEN]=`Bearer ${r}`,o&&(m[Ut.OAUTH_PROVIDER]=o)),{tools:e,config:s,memory:i,taste:a,skills:l,headers:m,sessionId:u}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:getConfiguredModel()},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId};return consumeSSEStream(await e.post({body:s,stream:!0,endpoint:Bt.ALPHA.GENERATE,headers:t.headers,signal:r}))}async function executeToolCall(e,t,n){if(kk.has(e.toolName)&&!n)return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: Tool "${e.toolName}" requires permissions. Use --yolo (or --dangerously-skip-permissions) to enable file writes and shell commands in print mode.`}};try{const n=await executeTool(e.toolName,e.input,{abortSignal:t});return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:n}}}catch(t){if(t instanceof Cs||t instanceof vs||t instanceof xs||t instanceof Es||t instanceof As)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: ${n}`}}}}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall");var _k=80;function truncate(e){return e.length<=_k?e:e.slice(0,_k)+"..."}function formatToolLabel(e){const t=e.input,n=__name(e=>truncate(String(t[e]??"")),"param");switch(e.toolName){case"shell_command":return`Shell: ${n("command")}`;case"read_file":return`Read: ${n("absolutePath")}`;case"edit_file":return`Edit: ${n("filePath")}`;case"write_file":return`Write: ${n("filePath")}`;case"grep":return`Search: ${n("pattern")}`;case"glob":return`Glob: ${n("pattern")}`;case"read_directory":return`List: ${n("path")}`;case"read_multiple_files":return`Read: ${truncate(String(t.include??""))}`;case"think":return"Thinking";case"explore":return"Exploring";case"todo_write":return"Updating todos";case"ask_user_question":return`Question: ${n("question")}`;case"kill_shell":return`Kill: ${n("processId")}`;case"web_search":return`Search: ${n("query")}`;case"web_fetch":return`Fetch: ${n("url")}`;case"get_diagnostics":return"Diagnostics";default:return e.toolName}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1,maxTurns:o,verbose:s}=e,i=getApiBaseUrl(),a=new jw({baseUrl:i}),l=[{role:"user",content:t}],u=await setupConversationContext(),d=createBenchmarkCollector();let m=0,g="";const h={stream:process.stderr,color:"cyan"},f=s?Re(h):null;try{for(;m<o;){if(m++,n.aborted)throw new Error("Cancelled");f?.start();const e=d?Date.now():0,t=await callApi(a,u,l,n),o=d?Date.now()-e:0;f?.stop();const i=t.usage,y=d?{turnNumber:m,apiDurationMs:o,toolCalls:[],toolDurationMs:0,inputTokens:i?.input_tokens??0,outputTokens:i?.output_tokens??0,cacheReadTokens:i?.cache_read_input_tokens??0,cacheCreationTokens:i?.cache_creation_input_tokens??0}:null,w=t.content.filter(e=>"text"===e.type),S=t.content.filter(e=>"tool-call"===e.type),E=w.map(e=>e.text).join("");if(E&&(g+=E),0===S.length){d&&y&&d.turnDetails.push(y);break}const C=[],v=d?Date.now():0;for(const e of S){if(n.aborted)throw new Error("Cancelled");let t=null;if(s){const n=formatToolLabel(e);t=Re({...h,text:n}).start()}const o=await executeToolCall(e,n,r);if(t){const e="error-text"===o.output.type?Pe.cross:Pe.tick;t.stopAndPersist({symbol:e})}const i="string"==typeof o.output?o.output:"value"in o.output?o.output.value:"";if(d&&"string"==typeof i){const{cleanContent:e,metrics:t}=extractAgentMetrics(i);t&&(d.agents.push(t),o.output={type:"text",value:e})}y&&y.toolCalls.push({name:e.toolName,isError:"error-text"===o.output.type}),C.push(o)}d&&y&&(y.toolDurationMs=Date.now()-v,d.turnDetails.push(y));const k=t.content.filter(e=>"tool-result"!==e.type);l.push({role:"assistant",content:k}),l.push({role:"tool",content:C})}m>=o&&(d&&(d.maxTurnsReached=!0),process.stderr.write(`Warning: Reached maximum conversation turns (${o}). The response may be incomplete. Use --max-turns to increase the limit.\n`))}finally{d&&writeBenchmarkMetrics(d)}return g}__name(truncate,"truncate"),__name(formatToolLabel,"formatToolLabel"),__name(processQuery,"processQuery"),Ot(),Ot(),Ot(),Ot(),wn(),yb(),Rs(),sS(),fS();var xk=Object.keys(Yt).sort((e,t)=>t.length-e.length),Ak={NOT_AUTHENTICATED:"Not authenticated",SESSION_EXPIRED:"Session expired"},Pk=new Set(Object.values(Ak));function isAuthErrorMessage(e){return Pk.has(e)}function formatCredits(e){return`$${e.toFixed(2)}`}function getPlanInfo({planId:e}){if(!e)return null;const t=e.toLowerCase().replace(/_/g,"-"),n=xk.find(e=>t.startsWith(e));if(!n)return null;const r=Yt[n];return r?{name:Jt[n]??n,monthlyCredits:r.total}:null}function getUsagePercent({used:e,total:t}){return t<=0?0:Math.min(e/t*100,100)}function getDaysRemaining(e){const t=new Date(e);return Number.isNaN(t.getTime())?null:Math.max(0,Math.ceil((t.getTime()-Date.now())/864e5))}async function safeFetch({request:e,endpoint:t}){try{return{data:await e.get({endpoint:t}),error:null}}catch(e){return e instanceof Es?{data:null,error:"Network error: unable to reach API"}:e instanceof Cs?{data:null,error:Ak.SESSION_EXPIRED}:{data:null,error:`${t}: ${e instanceof Error?e.message:"Unknown error"}`}}}function buildEndpoint({endpoint:e,params:t}){if(!t)return e;const n=new URLSearchParams;for(const[e,r]of Object.entries(t))null!=r&&n.set(e,r);const r=n.toString();return r?`${e}?${r}`:e}async function fetchCredits({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/credits",params:{orgId:t}})})}async function fetchSubscription({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/subscriptions",params:{orgId:t}})})}async function fetchWhoami({request:e}){return safeFetch({request:e,endpoint:"/alpha/whoami"})}async function fetchUsageSummary({request:e,orgId:t,since:n}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/usage/summary",params:{orgId:t,since:n}})})}async function fetchUsageData(){if(!await getAuthKey())return{whoami:null,credits:null,subscription:null,summary:null,modelBreakdown:null,errors:[Ak.NOT_AUTHENTICATED]};const e=getApiBaseUrl(),t=new jw({baseUrl:e}),n=await fetchWhoami({request:t}),r=n.data?.org?.id??null,[o,s]=await Promise.all([fetchCredits({request:t,orgId:r}),fetchSubscription({request:t,orgId:r})]),i=s.data?.data?.currentPeriodStart??null,a=await fetchUsageSummary({request:t,orgId:r,since:i}),l=[n.error,o.error,s.error,a.error].filter(e=>null!==e);return{whoami:n.data,credits:o.data,subscription:s.data,summary:a.data,modelBreakdown:a.data?.models??null,errors:l}}__name(isAuthErrorMessage,"isAuthErrorMessage"),__name(formatCredits,"formatCredits"),__name(getPlanInfo,"getPlanInfo"),__name(getUsagePercent,"getUsagePercent"),__name(getDaysRemaining,"getDaysRemaining"),__name(safeFetch,"safeFetch"),__name(buildEndpoint,"buildEndpoint"),__name(fetchCredits,"fetchCredits"),__name(fetchSubscription,"fetchSubscription"),__name(fetchWhoami,"fetchWhoami"),__name(fetchUsageSummary,"fetchUsageSummary"),__name(fetchUsageData,"fetchUsageData"),sS(),fS();var Ik={orgId:null,planId:null,purchasedCredits:0,freeCredits:0,fetchFailed:!0},Nk=null,Rk=null;function getCachedBillingContext(){return Nk}function getBillingContext(){return Nk&&!Nk.fetchFailed?Promise.resolve(Nk):Rk||(Rk=(async()=>{try{const e=new jw({baseUrl:getApiBaseUrl()}),t=await fetchWhoami({request:e}),n=t.data?.org?.id??null,[r,o]=await Promise.all([fetchSubscription({request:e,orgId:n}),fetchCredits({request:e,orgId:n})]);if(!t.data||!r.data||!o.data)return Ik;let s=null;if(r.data.success&&r.data.data){const{planId:e,status:t}=r.data.data;"active"!==t&&"past_due"!==t||(s=e)}const i={orgId:n,planId:s,purchasedCredits:o.data.credits.purchasedCredits??0,freeCredits:o.data.credits.freeCredits??0,fetchFailed:!1};return Nk=i,i}catch{return Ik}finally{Rk=null}})())}function prefetchBillingContext(){getBillingContext().catch(()=>{})}function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}__name(getCachedBillingContext,"getCachedBillingContext"),__name(getBillingContext,"getBillingContext"),__name(prefetchBillingContext,"prefetchBillingContext"),Ot(),Ot(),as(),Ot(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var Mk=["no job control","cannot set terminal process group"],Lk=null;function getShellInfo(){return Lk||(Lk=detectUserShell()),Lk}__name(getShellInfo,"getShellInfo");var $k=__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 i=__name(e=>{s||(s=!0,t(e))},"doResolve"),a=getShellInfo(),l="bash"===a.type||"zsh"===a.type,u=l?a.path:"/bin/bash",d=be(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="",h=null;n>0&&(h=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({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>ts){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:HC,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>ns)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=>{h&&clearTimeout(h);const n=l?g.split("\n").filter(e=>!Mk.some(t=>e.includes(t))).join("\n"):g;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{h&&clearTimeout(h),i({stdout:m,stderr:g+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),Dk=__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");xE();var Ok=__name(()=>{const[e,t]=Y({isExecuting:!1,currentCommand:null});return{executeBash:ee(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await $k(e,{timeout:3e4,cwd:process.cwd()}),o=Dk(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]=gE(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]=gE(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=Y(!1),[n,r]=Y(!1),[o,s]=Y(!1),[i,a]=Y(!1),[l,u]=Y(!1),[d,m]=Y(!1),[g,h]=Y(!1),[f,y]=Y(!1),[w,S]=Y(!1),[E,C]=Y(!1),[v,k]=Y(!1),[T,_]=Y(!1),[x,A]=Y(!1),[P,I]=Y(!1),[N,R]=Y(!1),[M,L]=Y(!1),[$,D]=Y(!1),[O,F]=Y(0),[q,j]=Y(!1),[U,B]=Y("off");return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:o,setShowTasteConfig:s,showSkillsConfig:i,setShowSkillsConfig:a,showProviderSelector:l,setShowProviderSelector:u,showModelSelector:d,setShowModelSelector:m,showMemorySelector:g,setShowMemorySelector:h,showMcpManager:f,setShowMcpManager:y,showLearningFeed:w,setShowLearningFeed:S,showSessionSelector:E,setShowSessionSelector:C,showAddDirModal:v,setShowAddDirModal:k,showRewindSelector:T,setShowRewindSelector:_,showLoginOverlay:x,setShowLoginOverlay:A,showCompactModeSelector:P,setShowCompactModeSelector:I,showContextView:N,setShowContextView:R,showStatusView:M,setShowStatusView:L,showUsageOverlay:$,setShowUsageOverlay:D,staticKey:O,setStaticKey:F,showTasteSkipBanner:q,setShowTasteSkipBanner:j,transcriptMode:U,setTranscriptMode:B,expandedToolOutput:"off"!==U}}Ot(),__name(useUiOverlays,"useUiOverlays"),Ot(),xE();var Fk="1"===process.env.CMD_TEST_INJECT_LIVE_ENTRY;function makeInjectedShellEntry(e,t,n,r={}){return{...iE("shell_command",t,{status:n}),id:e,...r}}function buildInjectedLiveEntry(){return Fk?makeInjectedShellEntry("cmd-test-injected-live-entry",process.env.CMD_TEST_INJECT_INPUT??"sleep 60","running"):null}function buildInjectedFeed(){const e=Number.parseInt(process.env.CMD_TEST_INJECT_FEED_ITEMS??"0",10);return!Number.isFinite(e)||e<=0?[]:Array.from({length:e},(e,t)=>makeInjectedShellEntry(`cmd-test-feed-${t}`,`echo item ${t}`,"completed",{output:`item ${t}`}))}function useFeed(){const[e,t]=Y(()=>buildInjectedFeed()),[n,r]=Y(()=>{const e=buildInjectedLiveEntry();return e?[e]:[]}),[o,s]=Y([]),[i,a]=Y(Fk),l=J([]);return X(()=>{l.current=o},[o]),{feed:e,setFeed:t,liveEntries:n,setLiveEntries:r,queuedMessages:o,setQueuedMessages:s,isCmdCodeBusy:i,setIsCmdCodeBusy:a,queuedMessagesRef:l}}function useSession(){const[e,t]=Y(crypto.randomUUID()),[n,r]=Y(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:J(null)}}function useStatus(e){const[t,n]=Y("Ready..."),r=J(!1),[o,s]=Y(""),i=J(null),[a,l]=Y(null),u=J(a),[d,m]=Y(null),[g,h]=Y(!1),[f,y]=Y(""),[w,S]=Y(null),[E,C]=Y(0),[v,k]=Y(null),[T,_]=Y(!1),[x,A]=Y(e??null);X(()=>{u.current=a},[a]),X(()=>{if(x){const e=setTimeout(()=>{A(null)},3e4);return()=>clearTimeout(e)}},[x]);const P=__name(e=>{i.current&&clearTimeout(i.current),s(e),i.current=setTimeout(()=>{s(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:o,setHintMessage:s,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:u,billingLink:d,setBillingLink:m,showShareNotification:g,setShowShareNotification:h,unshareNotificationMessage:f,setUnshareNotificationMessage:y,retryAttempt:w,setRetryAttempt:S,interactionTokens:E,setInteractionTokens:C,contextUsage:v,setContextUsage:k,tasteLearningEnabled:T,setTasteLearningEnabled:_,updateStatus:x,setUpdateStatus:A,showHintMessage:P}}function useAuth(){const[e,t]=Y(null),[n,r]=Y(getConfiguredModel()),[o,s]=Y(!1),[i,a]=Y(null),[l,u]=Y(!1),[d,m]=Y(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:o,setIsOAuthMode:s,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,premiumCreditsExhausted:d,setPremiumCreditsExhausted:m,providerNotificationTimer:J(null),modelNotificationTimer:J(null)}}__name(makeInjectedShellEntry,"makeInjectedShellEntry"),__name(buildInjectedLiveEntry,"buildInjectedLiveEntry"),__name(buildInjectedFeed,"buildInjectedFeed"),__name(useFeed,"useFeed"),Ot(),__name(useSession,"useSession"),Ot(),__name(useStatus,"useStatus"),Ot(),Jr(),__name(useAuth,"useAuth"),Ot(),Ot(),Ot(),wn(),xo();var qk=new Set(["-exec","-execdir","-ok","-okdir","-delete","-fprint","-fprint0","-fprintf","-fls"]);function hasDangerousFindFlag(e){return e.some(e=>qk.has(e))}function isDangerousFindCall({command:e,args:t}){if("find"!==e&&!e.startsWith("find "))return!1;const n=Array.isArray(t)?t.join(" "):t??"",r=et(`${e} ${n}`),o=[];for(const e of r){if("string"==typeof e){o.push(e);continue}const t=e?.pattern;if("string"!=typeof t)return!0;o.push(t)}return hasDangerousFindFlag(o)}__name(hasDangerousFindFlag,"hasDangerousFindFlag"),__name(isDangerousFindCall,"isDangerousFindCall");var jk=class extends qe{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 k.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,t){if(!this.config.enabled)return{allowed:!0};const n=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)||"plan"===t&&isPlanPath({filePath:e.filePath})?{allowed:!0}:this.config.sessionPermissions.has(n)?{allowed:this.config.sessionPermissions.get(n)||!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)?{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.trim()}:${e.args?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand({command:e,args:t}){return["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))?!isDangerousFindCall({command:e,args: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 k.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await k.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 k.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 k.mkdir(n,{recursive:!0});try{const t=await k.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 k.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},Uk=__name((e={})=>{const[t,n]=Y(null),[r,o]=Y(null),[s,i]=Y(!1);return X(()=>{const t=e.projectRoot||process.cwd(),r=new jk(t);return r.on("permission-request",(t,n)=>{o(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:ee(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:ee(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:ee(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),i(!1)}},[t]),clearSessionPermissions:ee(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:ee(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:ee((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:ee(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="boolean"==typeof t?t?"auto-accept":"standard":t,o="auto-accept"===r||"bypass"===r,s=["create","edit","delete","execute","shellCommands"];for(const e of s)n.setAutoApprove(e,o)}function usePermissionMode({initialPermissionMode:e,dangerouslySkipPermissions:t=!1,setPendingPermission:n,setStatus:r,contextEngineRef:o}){const[s,i]=Y(()=>e||(t?"bypass":"standard")),a=J(s);X(()=>{a.current=s},[s]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:g}=Uk({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{n({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),o.current&&r("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{n({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),o.current&&r("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?r("Permission granted"):r("Permission denied")},"onPermissionResponse")});return X(()=>{u&&applyAutoAcceptMode({enabled:s,service:u})},[s,u]),{permissionMode:s,setPermissionMode:i,permissionModeRef:a,permissionsService:u,respondToPrompt:d,clearSessionPermissions:m,dangerouslySkipPermissions:t}}function usePendingOps(){const[e,t]=Y(null),[n,r]=Y(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=Y(!1),[n,r]=Y(!1),[o,s]=Y(!0),[i,a]=Y(!1),[l,u]=Y(!1),[d,m]=Y(null),[g,h]=Y(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:o,setCheckingProject:s,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:u,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:m,autoLearnTaste:g,setAutoLearnTaste:h,tasteOnboardingCheckedRef:J(!1)}}function useExit(){const[e,t]=Y(!1),[n,r]=Y(null),o=J(null),s=J(0),i=J(null),a=ee(()=>{o.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:o,lastExitKeyTimeRef:s,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}async function resolveEditStartLine({filePath:e,oldContent:t}){const n=await O.readFile(e,"utf-8"),r=n.indexOf(t);if(-1!==r)return n.substring(0,r).split("\n").length}function isDirectoryEmpty(){try{return 0===B(process.cwd()).length}catch{return!1}}Ot(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Ot(),__name(usePendingOps,"usePendingOps"),Ot(),__name(useOnboarding,"useOnboarding"),Ot(),__name(useExit,"useExit"),Ot(),Ot(),Ot(),Ot(),__name(resolveEditStartLine,"resolveEditStartLine"),__name(isDirectoryEmpty,"isDirectoryEmpty"),Ot();var Bk=/(?<=[\s(\[{])\/([a-z0-9-]+)(?=[\s,.:;!?)\]}]|$)/g,zk=/(?<=[\s(\[{])\/[a-z0-9-]+(?=[\s,.:;!?)\]}]|$)/;function hasInlineSkillToken(e){return zk.test(e)}function tagSkillContent(e,t){return`<${tk}>${e}</${tk}>\n\n${t}`}function buildSlashCommandMessage(e){const{commandName:t,skillName:n,rawArguments:r}=e,o=[`<${ek}>${n}</${ek}>`,`<${tk}>${t}</${tk}>`];return 0===r.trim().length?o.join("\n"):[...o,`<${nk}>${r}</${nk}>`].join("\n")}function applySkillArguments({rawArguments:e,skillContent:t,positionalArgs:n}){let r=t.replace(/\$ARGUMENTS\[(\d+)\]|\$\{(\d+)\}/g,(e,t,r)=>{const o=t??r;if(!o)return"";const s=Number.parseInt(o,10);return Number.isNaN(s)?"":n[s]??""});return r=r.replace(/\$ARGUMENTS/g,e),0===e.trim().length||r!==t?r.trim():`${t.trimEnd()}\n\nARGUMENTS: ${e}`}function buildSlashCommandSkillContextMessage(e){const{rawArguments:t,skillContent:n,skillDirectory:r,positionalArgs:o}=e,s=`Base directory for this skill: ${r}`,i=applySkillArguments({rawArguments:t,skillContent:n,positionalArgs:o});return 0===i.length?s:`${s}\n\n${i}`}async function processSkillReferences(e){const n=await loadAllSkillSummaries(),{names:r}=await loadDisabledSkills(),o=new Map(deduplicateSkills(n).filter(e=>!r.has(e.name)).map(e=>[e.name,e]));if(0===o.size)return[];const s=[...e.matchAll(Bk)];if(0===s.length)return[];const i=[],a=new Set;for(const e of s){const n=e[1];if(!n)continue;if(a.has(n))continue;const r=o.get(n);if(r)try{const e=await loadSkill({filePath:r.filePath});i.push({skillName:n,content:e.content.trim(),skillDirectory:t.dirname(r.filePath)}),a.add(n)}catch{}}return i}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}__name(hasInlineSkillToken,"hasInlineSkillToken"),__name(tagSkillContent,"tagSkillContent"),__name(buildSlashCommandMessage,"buildSlashCommandMessage"),__name(applySkillArguments,"applySkillArguments"),__name(buildSlashCommandSkillContextMessage,"buildSlashCommandSkillContextMessage"),__name(processSkillReferences,"processSkillReferences"),Rs(),xE(),yS(),Ot(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),Ot(),GE(),Kn(),Jr();var Hk=null;async function hasFirstMessageBeenTracked(){try{return!0===(await loadUserConfig()).firstMessageSent}catch{return!1}}async function markFirstMessageTracked(){try{await updateUserConfig({firstMessageSent:!0})}catch(e){dlog("[detect-first-message] failed to mark as tracked",{error:e})}}async function detectAndTrackFirstMessage(){if(!await hasFirstMessageBeenTracked())return Hk||(Hk=(async()=>{try{await trackLifecycleEvent({eventType:"cli_first_message"}),await markFirstMessageTracked(),dlog("[detect-first-message] tracked first message")}catch(e){dlog("[detect-first-message] failed to track",{error:e})}finally{Hk=null}})())}function computePayloadHealth(e){let t=0,n=0,r=0,o=0,s=0,i=0;const a=new Set,l=new Set,u=new Set;for(const d of e)if("user"!==d.role){if("assistant"===d.role){if(n++,!Array.isArray(d.content))continue;let e=!1;for(const t of d.content)"tool-call"!==t.type||t.providerExecuted||(e=!0,s++,a.add(t.toolCallId));e&&o++;continue}if("tool"===d.role){if(r++,!Array.isArray(d.content))continue;for(const e of d.content)"tool-result"===e.type&&(i++,u.add(e.toolCallId),a.has(e.toolCallId)&&l.add(e.toolCallId))}}else t++;const d=a.size-l.size;let m=0;for(const e of u)a.has(e)||m++;const g=0===e.length?"none":e[e.length-1].role;return{messageCount:e.length,userMessageCount:t,assistantMessageCount:n,toolMessageCount:r,assistantWithToolUseCount:o,toolUseCount:s,toolResultCount:i,orphanToolUseCount:d,orphanToolResultCount:m,lastMessageRole:g}}function firstLine(e){const t=e.trim(),n=t.indexOf("\n"),r=-1===n?t:t.slice(0,n);return r.length>200?r.slice(0,200)+"…":r}function payloadHealthAttributes(e){return{[Mt.PAYLOAD_MESSAGE_COUNT]:e.messageCount,[Mt.PAYLOAD_USER_MESSAGE_COUNT]:e.userMessageCount,[Mt.PAYLOAD_ASSISTANT_MESSAGE_COUNT]:e.assistantMessageCount,[Mt.PAYLOAD_TOOL_MESSAGE_COUNT]:e.toolMessageCount,[Mt.PAYLOAD_ASSISTANT_WITH_TOOL_USE_COUNT]:e.assistantWithToolUseCount,[Mt.PAYLOAD_TOOL_USE_COUNT]:e.toolUseCount,[Mt.PAYLOAD_TOOL_RESULT_COUNT]:e.toolResultCount,[Mt.PAYLOAD_ORPHAN_TOOL_USE_COUNT]:e.orphanToolUseCount,[Mt.PAYLOAD_ORPHAN_TOOL_RESULT_COUNT]:e.orphanToolResultCount,[Mt.PAYLOAD_LAST_MESSAGE_ROLE]:e.lastMessageRole}}function attemptAttributes(e){const t={[Mt.API_ATTEMPT_NUMBER]:e.attempt,[Mt.API_ATTEMPT_DELAY_MS_BEFORE]:e.delayMsBefore,[Mt.API_ATTEMPT_STATUS]:e.status};return e.errorType&&(t[Mt.API_ATTEMPT_ERROR_TYPE]=e.errorType),e.errorMessage&&(t[Mt.API_ATTEMPT_ERROR_MESSAGE]=firstLine(e.errorMessage)),"number"==typeof e.httpStatus&&(t[Mt.API_ATTEMPT_HTTP_STATUS]=e.httpStatus),"boolean"==typeof e.isRetryable&&(t[Mt.API_ATTEMPT_IS_RETRYABLE]=e.isRetryable),t}function startIterationSpan(e){const t=getSessionId(),n=getActiveIterationSpanContext(),r={[Mt.ITERATION_NUMBER]:e.iteration,[Rt.REQUEST_MODEL]:e.model,[Rt.STEP_NAME]:`iteration_${e.iteration}`};e.capability&&(r[Rt.CAPABILITY_NAME]=e.capability),t&&(r["session.id"]=t,r[Rt.CONVERSATION_ID]=t),"number"==typeof e.initialMessageCount&&(r[Mt.ITERATION_INITIAL_MESSAGE_COUNT]=e.initialMessageCount);const o=ke.getTracer(_t),s=ke.deleteSpan(Te.active()),i=n?[{context:n,attributes:{"cmd.iteration.link_kind":"previous_iteration"}}]:void 0,a=o.startSpan("context:iteration",{attributes:r,kind:_e.INTERNAL,links:i,root:!0},s),l=a.spanContext();setActiveIterationSpanContext(l);let u=!1;return{span:a,spanContext:l,recordPayloadHealth(e){u||a.addEvent("context.payload_health",payloadHealthAttributes(e))},recordAttempt(e){u||a.addEvent("context.api_attempt",attemptAttributes(e))},setAttribute(e,t){u||a.setAttribute(e,t)},end({outcome:e,error:t}){if(u)return;u=!0,a.setAttribute(Mt.ITERATION_OUTCOME,e),t&&(a.setAttribute(Mt.ITERATION_TERMINAL_ERROR_TYPE,t.name),a.setAttribute(Mt.ITERATION_TERMINAL_ERROR_MESSAGE,firstLine(t.message)),a.recordException(t));const n="non_retryable_error"===e||"max_retries_exceeded"===e||"error"===e;a.setStatus({code:n?xe.ERROR:xe.OK,message:t?firstLine(t.message):void 0}),a.end(),setActiveIterationSpanContext(l)}}}function toToolDisplayName(e){return uC[e.toolName]||toRegexSafeAlias(e.toolName)}function toRegexSafeAlias(e){const t=e.replace(/[^A-Za-z0-9_]/g,"_").toUpperCase().replace(/^_+|_+$/g,"");return t?/^[A-Z]/.test(t)?t:`T_${t}`:"TOOL"}function getHookMatcherTarget(e){return toToolDisplayName({toolName:e.toolName})}__name(hasFirstMessageBeenTracked,"hasFirstMessageBeenTracked"),__name(markFirstMessageTracked,"markFirstMessageTracked"),__name(detectAndTrackFirstMessage,"detectAndTrackFirstMessage"),hs(),Ot(),__name(computePayloadHealth,"computePayloadHealth"),Ot(),fn(),Oo(),__name(firstLine,"firstLine"),__name(payloadHealthAttributes,"payloadHealthAttributes"),__name(attemptAttributes,"attemptAttributes"),__name(startIterationSpan,"startIterationSpan"),fS(),sS(),Of(),wn(),Lo(),Ot(),Ot(),Ot(),Ot(),Kn(),Ot(),yS(),__name(toToolDisplayName,"toToolDisplayName"),__name(toRegexSafeAlias,"toRegexSafeAlias"),__name(getHookMatcherTarget,"getHookMatcherTarget");var Wk=new Set([iS.WRITE_FILE,iS.EDIT_FILE,iS.READ_FILE,iS.READ_MULTIPLE_FILES,iS.READ_DIRECTORY,iS.DIAGNOSTICS]);function camelToSnake(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function toHookWireInput(e,t){if(!Wk.has(e))return t;const n={};for(const[e,r]of Object.entries(t))n[camelToSnake(e)]=r;return n}function normalizeEventName(e){return Object.values(Hb).includes(e)?e:null}function createHookRegistry(){const e=[],t=new Map,n=[];return{initialize:__name(async r=>{const{projectRoot:o}=r,s=[{path:getProjectLocalPath(o),source:"project-local"},{path:getProjectSharedPath(o),source:"project-shared"},{path:getUserSettingsPath(),source:"user"}],i=new Set;for(const{path:r,source:o}of s){const s=await loadSettingsFile(r);s&&(s.warning?(dlog(`[Hook] ${s.warning}`),n.push(s.warning)):s.settings&&loadHooksFromSource({settingsPath:r,source:o,settings:s.settings,seenCommands:i,entries:e,matcherCache:t,validationWarnings:n,normalizeEventName:normalizeEventName}))}e.length>0&&dlog(`[Hook] Loaded ${e.length} hook(s)`)},"initialize"),normalizeEventName:normalizeEventName,getHooksForEvent:__name(n=>{const{eventName:r,toolName:o}=n;return e.filter(e=>{if(e.eventName!==r)return!1;if(e.matcher){if(!o)return!1;const n=getOrCompileRegex({cache:t,pattern:e.matcher});if(!n)return!1;if(!n.test(getHookMatcherTarget({toolName:o})))return!1}return!0})},"getHooksForEvent"),getAllHooks:__name(()=>[...e],"getAllHooks"),getHookCount:__name(()=>e.length,"getHookCount"),getValidationWarnings:__name(()=>[...n],"getValidationWarnings")}}function getTrustFilePath(){return e.join(w.homedir(),".commandcode","trusted-hooks.json")}function computeFingerprint(e){return N.createHash("sha256").update(e.command).digest("hex").slice(0,16)}function createTrustManager(){let t={},n=!1;return{load:__name(async()=>{if(!n){try{const e=await v.readFile(getTrustFilePath(),"utf-8");t=JSON.parse(e)}catch{t={}}n=!0}},"load"),checkTrust:__name(e=>{const{hookConfig:n,source:r,projectRoot:o}=e;if("user"===r)return"trusted";const s=computeFingerprint(n);return(t[o]||[]).find(e=>e.fingerprint===s)?"trusted":"new"},"checkTrust"),trust:__name(e=>{const{hookConfig:n,projectRoot:r}=e,o=computeFingerprint(n);t[r]||(t[r]=[]);const s=t[r];s.some(e=>e.fingerprint===o)||s.push({fingerprint:o,trustedAt:(new Date).toISOString()})},"trust"),save:__name(async()=>{const n=getTrustFilePath(),r=e.dirname(n);await v.mkdir(r,{recursive:!0}),await v.writeFile(n,JSON.stringify(t,null,2))},"save"),getTrustedHooks:__name(e=>t[e]||[],"getTrustedHooks")}}function collectTrustWarnings(e){const{registry:t,trustManager:n,projectRoot:r}=e,o=[];let s=0;for(const e of t.getAllHooks()){const t=n.checkTrust({hookConfig:e.config,source:e.source,projectRoot:r});"trusted"!==t&&("new"===t&&s++,n.trust({hookConfig:e.config,projectRoot:r}))}s>0&&dlog(`[Hook] ${s} new hook(s) trusted on first execution`);for(const e of t.getValidationWarnings())o.push(e);return o}function auditLogPath(t){const n=t.sessionId?`hooks-audit-${t.sessionId}.jsonl`:"hooks-audit.jsonl";return e.join(t.sessionDir,n)}function createAuditLogger(t){const n=auditLogPath(t);let r=null;const o=__name(()=>(r||(r=v.mkdir(e.dirname(n),{recursive:!0}).then(()=>{})),r),"ensureDir");let s=Promise.resolve();return{log:__name(e=>{const t=s.then(async()=>{try{await o();const t=JSON.stringify(e)+"\n";await v.appendFile(n,t)}catch(e){dlog(`[Hook] Audit log write failed: ${getErrorMessage(e)}`)}});return s=t,t},"log")}}__name(camelToSnake,"camelToSnake"),__name(toHookWireInput,"toHookWireInput"),__name(normalizeEventName,"normalizeEventName"),__name(createHookRegistry,"createHookRegistry"),Ot(),wn(),__name(getTrustFilePath,"getTrustFilePath"),__name(computeFingerprint,"computeFingerprint"),__name(createTrustManager,"createTrustManager"),Ot(),Kn(),__name(collectTrustWarnings,"collectTrustWarnings"),Ot(),Kn(),__name(auditLogPath,"auditLogPath"),__name(createAuditLogger,"createAuditLogger"),Ot(),Ot(),Ot();var Gk=[/API_KEY/i,/SECRET/i,/TOKEN/i,/PASSWORD/i,/ANTHROPIC_/i,/COMMANDCODE_API/i,/OAUTH/i,/CREDENTIAL/i,/PRIVATE_KEY/i,/(^|_)AUTH(_|$)/i,/(^|_)AUTHORIZATION(_|$)/i,/(^|_)BEARER(_|$)/i,/AWS_ACCESS_KEY/i,/AWS_SECRET/i,/AWS_SESSION_TOKEN/i];function sanitizeEnvironment(e){const{env:t,input:n}=e,r={};for(const[e,n]of Object.entries(t))void 0!==n&&(Gk.some(t=>t.test(e))||(r[e]=n));return r.COMMANDCODE_PROJECT_DIR=n.cwd,r.COMMANDCODE_SESSION_ID=n.session_id,r.COMMANDCODE_CWD=n.cwd,r.COMMANDCODE_HOOK_EVENT=n.hook_event_name,r}__name(sanitizeEnvironment,"sanitizeEnvironment"),Ot(),Kn(),Ot(),Ot();var Vk={cancel:{hint:'Use "continue": false to stop the session, or hookSpecificOutput.permissionDecision: "deny" (PreToolUse) to block the tool.'},blocked:{hint:'Use hookSpecificOutput.permissionDecision: "deny" (PreToolUse) to block.'},shouldContinue:{hint:'Use "continue": false with "stopReason" to halt the session.'},decision:{hint:'Use hookSpecificOutput.permissionDecision: "allow"|"deny" (PreToolUse). Top-level decision is PostToolUse-only.',suppressFor:["PostToolUse"]},reason:{hint:'Use hookSpecificOutput.permissionDecisionReason (PreToolUse) or "systemMessage" for user messaging. Top-level reason is PostToolUse-only.',suppressFor:["PostToolUse"]},message:{hint:'Use "systemMessage" for user messaging, or hookSpecificOutput.additionalContext for context injection.'},error:{hint:"Use hookSpecificOutput.permissionDecisionReason (PreToolUse) or exit with code 2 and write to stderr."},errorMessage:{hint:"Use hookSpecificOutput.permissionDecisionReason (PreToolUse) or exit with code 2 and write to stderr."},contextModification:{hint:"Use hookSpecificOutput.additionalContext instead."}},Qk=new Set(["continue","suppressOutput","stopReason","systemMessage","hookSpecificOutput"]),Kk=new Set(["decision","reason"]);function getValidFieldsForEvent(e){return"PostToolUse"===e?new Set([...Qk,...Kk]):Qk}function validateHookOutput(e){const{stdout:t,hookName:n,eventName:r}=e,o=[],s=getValidFieldsForEvent(r),i=[...s].join(", "),a=t.trim();if(!a)return{status:"empty",warnings:o};let l;try{l=JSON.parse(a),"string"==typeof l&&(l=JSON.parse(l))}catch{const e="non-JSON stdout";return o.push(`Hook "${n}" wrote non-JSON to stdout. Output was ignored. Expected JSON object with optional fields: ${i}.`),{status:"parse-error",reason:e,warnings:o}}if("object"!=typeof l||null===l||Array.isArray(l)){const e=Array.isArray(l)?"an array":typeof l;return o.push(`Hook "${n}" returned ${e}. Expected JSON object.`),{status:"parse-error",reason:`expected object, got ${e}`,warnings:o}}const u=l;for(const[e,t]of Object.entries(Vk))e in u&&(t.suppressFor?.includes(r)||o.push(`Hook "${n}": unexpected field "${e}". ${t.hint}`));for(const e of Object.keys(u))s.has(e)||e in Vk||o.push(`Hook "${n}": unknown field "${e}". Valid fields: ${i}`);const d=("PreToolUse"===r?hC:fC).safeParse(u);if(!d.success){const e=d.error.issues.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ");return o.push(`Hook "${n}": validation error: ${e}`),{status:"schema-error",reason:e,warnings:o}}const m=d.data;return m.hookSpecificOutput?.hookEventName&&m.hookSpecificOutput.hookEventName!==r&&o.push(`Hook "${n}": hookSpecificOutput.hookEventName "${m.hookSpecificOutput.hookEventName}" does not match "${r}".`),{status:"valid",output:m,warnings:o}}function resolveProcessExit(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,processOutput:s}=e,{exitCode:i,stdout:a,stderr:l,duration:u,toolName:d,toolUseId:m}=s,g=validateHookOutput({stdout:a,hookName:n,eventName:o});for(const e of g.warnings)dlog(`[Hook] ${e}`);const h="valid"===g.status?g.output:void 0,f={hookName:n,displayLabel:r,eventName:o,exitCode:i,duration:u,stdout:a,stderr:l,scriptPath:deriveScriptPath(t.command),stderrFirstLine:firstNonEmptyLine(l),toolName:d,toolUseId:m};if(2===i){const e=h?.hookSpecificOutput?.permissionDecisionReason??h?.reason;return{...f,success:!0,output:h,blocked:!0,blockReason:resolveBlockReason({reason:e,stderr:l.trim(),fallback:`Hook "${r}" exited with code 2`})}}if(t.failClosed&&0!==i)return{...f,success:!1,output:h,blocked:!0,blockReason:`Security hook "${r}" failed (exit code ${i}). Action blocked (failClosed). Error: ${l.trim()||"unknown"}`};if(t.failClosed&&0===i&&a.trim().length>0&&("parse-error"===g.status||"schema-error"===g.status))return{...f,success:!1,output:h,blocked:!0,blockReason:`Security hook "${r}" returned invalid output (failClosed). ${g.reason??"invalid output"}`};if(0!==i)return{...f,success:!1,output:h,blocked:!1};const y=h?deriveBlockFromOutput({eventName:o,output:h,displayLabel:r}):{blocked:!1,blockReason:void 0};return{...f,success:!0,output:h,blocked:y.blocked,blockReason:y.blockReason}}function deriveBlockFromOutput(e){if("PreToolUse"===e.eventName){const t=e.output.hookSpecificOutput;return"deny"===t?.permissionDecision?{blocked:!0,blockReason:t.permissionDecisionReason??`Blocked by hook "${e.displayLabel}"`}:{blocked:!1}}return"PostToolUse"===e.eventName&&"block"===e.output.decision?{blocked:!0,blockReason:e.output.reason??`PostToolUse hook "${e.displayLabel}" requested retry`}:{blocked:!1}}function failClosedBlockReason(e){return`Hook "${e.displayLabel}" failed (failClosed): ${e.cause}`}function buildSpawnThrowResult(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,error:s,toolName:i,toolUseId:a,startTime:l}=e,u=s instanceof Error?s:new Error(String(s)),d=Boolean(t.failClosed);return{hookName:n,displayLabel:r,eventName:o,success:!1,error:u,blocked:d,blockReason:d?failClosedBlockReason({displayLabel:r,cause:`Failed to spawn: ${u.message}`}):void 0,duration:Date.now()-l,scriptPath:deriveScriptPath(t.command),toolName:i,toolUseId:a}}function buildChildErrorResult(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,error:s,stderr:i,toolName:a,toolUseId:l,startTime:u}=e,d=Boolean(t.failClosed);return{hookName:n,displayLabel:r,eventName:o,success:!1,error:s,blocked:d,blockReason:d?failClosedBlockReason({displayLabel:r,cause:`Failed to start: ${s.message}`}):void 0,duration:Date.now()-u,stderr:i,scriptPath:deriveScriptPath(t.command),stderrFirstLine:firstNonEmptyLine(i),toolName:a,toolUseId:l}}function buildTimeoutResult(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,timeoutMs:s,stdout:i,stderr:a,toolName:l,toolUseId:u,startTime:d}=e,m=Boolean(t.failClosed);return{hookName:n,displayLabel:r,eventName:o,success:!1,error:new Error(`Hook "${r}" timed out after ${s}ms`),blocked:m,blockReason:m?failClosedBlockReason({displayLabel:r,cause:`Timed out after ${s}ms`}):void 0,duration:Date.now()-d,stdout:i,stderr:a,scriptPath:deriveScriptPath(t.command),stderrFirstLine:firstNonEmptyLine(a),toolName:l,toolUseId:u}}function getShellConfig(){return"win32"===process.platform?{executable:"cmd.exe",args:["/c"]}:{executable:"/bin/bash",args:["--norc","--noprofile","-c"]}}function collectStream(e){e.stream?.on("data",t=>{e.buffer.value.length>=zb||(e.buffer.value+=t.toString(),e.buffer.value.length>zb&&(e.buffer.value=e.buffer.value.slice(0,zb)))})}function extractToolMeta(e){let t,n;return"tool_name"in e&&"string"==typeof e.tool_name&&(t=e.tool_name),"tool_use_id"in e&&"string"==typeof e.tool_use_id&&(n=e.tool_use_id),{toolName:t,toolUseId:n}}function scheduleKillEscalation(e){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}async function executeCommandHook(e){const{config:t,hookLabel:n,displayLabel:r,eventName:o,input:s}=e,i=t.timeout?Math.round(1e3*t.timeout):3e4,a=Date.now(),{toolName:l,toolUseId:u}=extractToolMeta(s),d=sanitizeEnvironment({env:process.env,input:s}),m=getShellConfig(),g={config:t,hookLabel:n,displayLabel:r,eventName:o,toolName:l,toolUseId:u,startTime:a};return new Promise(e=>{const h={value:""},f={value:""};let y=!1,w=null;const S=__name(t=>{y||(y=!0,w&&clearTimeout(w),e(t))},"finish");let E;try{E=be(m.executable,[...m.args,t.command],{env:d,cwd:s.cwd,stdio:["pipe","pipe","pipe"]})}catch(e){return void S(buildSpawnThrowResult({...g,error:e}))}E.stdin?.on("error",()=>{});try{E.stdin?.write(JSON.stringify(s)),E.stdin?.end()}catch{}collectStream({stream:E.stdout,buffer:h}),collectStream({stream:E.stderr,buffer:f}),E.on("close",e=>{S(resolveProcessExit({config:t,hookLabel:n,displayLabel:r,eventName:o,processOutput:{exitCode:e??1,stdout:h.value,stderr:f.value,duration:Date.now()-a,toolName:l,toolUseId:u}}))}),E.on("error",e=>{S(buildChildErrorResult({...g,error:e,stderr:f.value}))}),w=setTimeout(()=>{scheduleKillEscalation(E),S(buildTimeoutResult({...g,timeoutMs:i,stdout:h.value,stderr:f.value}))},i)})}function labelFor(e){return buildHookLabel({source:e.source,eventName:e.eventName,definitionIndex:e.definitionIndex,hookIndex:e.hookIndex,command:e.config.command})}function displayLabelFor(e){return buildHookDisplayLabel(e.config.command)}function buildAuditEntry(e){const{eventName:t,result:n}=e,r=!0===n.output?.suppressOutput;return{timestamp:(new Date).toISOString(),eventName:t,hookName:n.hookName,hookType:"command",exitCode:n.exitCode,duration:n.duration,blocked:n.blocked,output:r?void 0:n.output,error:n.error?.message,...n.toolName?{toolName:n.toolName}:{},...n.toolUseId?{toolUseId:n.toolUseId}:{}}}async function executeSingle(e){const{entry:t,eventName:n,input:r}=e,o=labelFor(t),s=displayLabelFor(t);try{return await executeCommandHook({config:t.config,hookLabel:o,displayLabel:s,eventName:n,input:r})}catch(e){const r=Boolean(t.config.failClosed);return{hookName:o,displayLabel:s,eventName:n,success:!1,error:e instanceof Error?e:new Error(getErrorMessage(e)),blocked:r,blockReason:r?`Hook "${s}" failed (failClosed): ${getErrorMessage(e)}`:void 0,duration:0}}}function fireAsync(e){const{entry:t,eventName:n,input:r,auditLogger:o}=e,s=labelFor(t),i=displayLabelFor(t);logFireAndForget(executeCommandHook({config:t.config,hookLabel:s,displayLabel:i,eventName:n,input:r}).then(e=>{logFireAndForget(o.log(buildAuditEntry({eventName:n,result:e})))},e=>{const t={hookName:s,displayLabel:i,eventName:n,success:!1,error:e instanceof Error?e:new Error(getErrorMessage(e)),blocked:!1,duration:0};logFireAndForget(o.log(buildAuditEntry({eventName:n,result:t})))}))}async function executeSequential(e){const{entries:t,eventName:n,input:r,auditLogger:o}=e,s=[];for(const e of t){if(e.config.async){fireAsync({entry:e,eventName:n,input:r,auditLogger:o});continue}const t=await executeSingle({entry:e,eventName:n,input:r});if(s.push(t),t.blocked)break}return s}async function executeParallel(e){const{entries:t,eventName:n,input:r,auditLogger:o}=e,s=t.filter(e=>!e.config.async),i=t.filter(e=>e.config.async);for(const e of i)fireAsync({entry:e,eventName:n,input:r,auditLogger:o});return(await Promise.allSettled(s.map(e=>executeSingle({entry:e,eventName:n,input:r})))).map((e,t)=>"fulfilled"===e.status?e.value:{hookName:labelFor(s[t]),displayLabel:displayLabelFor(s[t]),eventName:n,success:!1,error:e.reason instanceof Error?e.reason:new Error(getErrorMessage(e.reason)),blocked:!1,duration:0})}function aggregateResults(e){const{results:t,eventName:n}=e,r=Wb.has(n);let o,s,i=!1,a=!1;const l=[],u=[];let d=0;for(const e of t){if(d+=e.duration,r&&e.blocked&&!i&&(i=!0,o=e.blockReason??`Blocked by hook "${e.displayLabel}"`),!e.success)continue;const t=e.output;t&&(t.hookSpecificOutput?.additionalContext&&l.push(t.hookSpecificOutput.additionalContext),t.systemMessage&&u.push(t.systemMessage),!1!==t.continue||a||(a=!0,s=t.stopReason))}return{blocked:i,blockReason:o,stop:a,stopReason:s,additionalContext:l.length>0?truncateHookContext({additionalContext:l.join("\n")}):void 0,systemMessages:u,results:t,totalDuration:d}}function truncateHookContext(e){return e.additionalContext.length<=4e3?e.additionalContext:e.additionalContext.slice(0,4e3)+"\n[Hook context truncated to 4000 characters]"}__name(getValidFieldsForEvent,"getValidFieldsForEvent"),__name(validateHookOutput,"validateHookOutput"),__name(resolveProcessExit,"resolveProcessExit"),__name(deriveBlockFromOutput,"deriveBlockFromOutput"),Ot(),__name(failClosedBlockReason,"failClosedBlockReason"),__name(buildSpawnThrowResult,"buildSpawnThrowResult"),__name(buildChildErrorResult,"buildChildErrorResult"),__name(buildTimeoutResult,"buildTimeoutResult"),__name(getShellConfig,"getShellConfig"),__name(collectStream,"collectStream"),__name(extractToolMeta,"extractToolMeta"),__name(scheduleKillEscalation,"scheduleKillEscalation"),__name(executeCommandHook,"executeCommandHook"),__name(labelFor,"labelFor"),__name(displayLabelFor,"displayLabelFor"),__name(buildAuditEntry,"buildAuditEntry"),__name(executeSingle,"executeSingle"),__name(fireAsync,"fireAsync"),__name(executeSequential,"executeSequential"),__name(executeParallel,"executeParallel"),Ot(),__name(aggregateResults,"aggregateResults"),__name(truncateHookContext,"truncateHookContext"),Kn(),Ot(),Kn(),Ot();var Yk=new class extends qe{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;_authResolve=null;_authReject=null;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:i,promptCount:a,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:i,promptCount:a,learningCount:l,categories:u,storage:d};this.events.unshift(m),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",m)}emitStepStart(e){this.addEvent({type:"step_start",...e})}emitProgress(e){this.addEvent({type:"progress",...e})}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}waitForAuth(){return new Promise((e,t)=>{this._authResolve=e,this._authReject=t})}resolveAuth(){this._authResolve?.(),this._authResolve=null,this._authReject=null}rejectAuth(e){this._authReject?.(new Error(e??"Login cancelled")),this._authResolve=null,this._authReject=null}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this._authReject?.(new Error("Reset during auth")),this._authResolve=null,this._authReject=null,this.emit("reset")}};function getGlobalProjectSettingsDir(t=process.cwd()){const n=Fe(t);return e.join(S.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 v.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 v.mkdir(o,{recursive:!0}),await v.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),Yk.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 v.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}function createHookSystem(e){const t=createHookRegistry(),n=createTrustManager(),r=createAuditLogger({sessionDir:getGlobalProjectSettingsDir(e.projectRoot),sessionId:e.sessionId});let o=!1,s=null,i=[];const a=__name(async()=>{if(!o)return s||(s=__name(async()=>{await t.initialize({projectRoot:e.projectRoot}),await n.load(),i=collectTrustWarnings({registry:t,trustManager:n,projectRoot:e.projectRoot});try{await n.save()}catch(e){dlog(`[Hook] Trust save failed during init: ${getErrorMessage(e)}`)}o=!0;const r=t.getHookCount();r>0&&dlog(`[Hook] Initialized with ${r} hook(s)`)},"doInit")().catch(e=>{throw s=null,e}),void await s)},"initialize"),l=__name(async n=>{const o={blocked:!1,stop:!1,systemMessages:[],results:[],totalDuration:0};if("plan"===e.runMode||"plan"===n.input.permission_mode)return o;try{await a()}catch(e){return dlog(`[Hook] Hook initialization failed: ${getErrorMessage(e)}`),o}const s=t.normalizeEventName(n.eventName);if(!s)return dlog(`[Hook] Unknown event name: ${n.eventName}`),o;const i=t.getHooksForEvent({eventName:s,toolName:n.toolName});if(0===i.length)return o;const l=Wb.has(s),u={entries:i,eventName:s,input:n.input,auditLogger:r},d=l?await executeSequential(u):await executeParallel(u);for(const e of d)logFireAndForget(r.log(buildAuditEntry({eventName:s,result:e})));return aggregateResults({results:d,eventName:s})},"fireEvent");return{initialize:a,fireEvent:l,drainTrustWarnings:__name(()=>{const e=[...i];return i=[],e},"drainTrustWarnings"),getRegistry:__name(()=>t,"getRegistry"),shutdown:__name(async()=>{try{await n.save()}catch(e){dlog(`[Hook] Trust save failed during shutdown: ${getErrorMessage(e)}`)}},"shutdown")}}function getProjectsBasePath(){return t.join(S.homedir(),".commandcode","projects")}function getProjectDirName(e){return Fe(e.cwd)}function getTranscriptPath(e){return t.join(getProjectsBasePath(),getProjectDirName({cwd:e.cwd}),`${e.sessionId}.jsonl`)}function baseInput(e){return{session_id:e.sessionId,transcript_path:getTranscriptPath({cwd:e.cwd,sessionId:e.sessionId}),cwd:e.cwd,hook_event_name:e.eventName,permission_mode:e.permissionMode}}function buildPreToolUseInput(e){return{...baseInput({...e,eventName:"PreToolUse"}),tool_use_id:e.toolUseId,tool_name:e.toolName,tool_display_name:toToolDisplayName({toolName:e.toolName}),tool_input:toHookWireInput(e.toolName,e.toolInput)}}function buildPostToolUseInput(e){return{...baseInput({...e,eventName:"PostToolUse"}),tool_use_id:e.toolUseId,tool_name:e.toolName,tool_display_name:toToolDisplayName({toolName:e.toolName}),tool_input:toHookWireInput(e.toolName,e.toolInput),tool_response:e.toolResponse}}function formatHookSaysLine(e,t){return`${e}: ${t}`}function formatHookBlock(e,t,n){return`${e}:${t} blocked: ${n}`}function formatHookError(e,t,n,r){const o=`${e}:${t} hook error:`;return n?`${o} [${n}]: ${r}`:`${o} ${r}`}function formatHookStop(e,t,n){return`${e}:${t} hook stopped continuation: ${n??"session halt requested"}`}function formatHookDenyMessage(e){return`${e}\n\n(Blocked by hook policy. Do not retry this tool — choose another approach or ask the user.)`}async function firePreToolUseHook(e){const{hookSystem:t,baseParams:n,toolBlock:r}=e,o=EE(r.toolName),s=await t.fireEvent({eventName:"PreToolUse",input:buildPreToolUseInput({...n,toolUseId:r.toolCallId,toolName:r.toolName,toolInput:r.input}),toolName:r.toolName}),i=buildHookLines("PreToolUse",s);if(s.blocked){const e=s.blockReason||"PreToolUse hook denied execution",t=buildBlockOrErrorOutcome({event:"PreToolUse",toolDisplayName:o,aggregate:s,fallbackReason:e});return{blocked:!0,denyReason:formatHookDenyMessage(e),stopSession:s.stop,sessionStopReason:s.stopReason,hookLines:i,hookOutcome:t}}return{blocked:!1,additionalContext:s.additionalContext,stopSession:s.stop,sessionStopReason:s.stopReason,hookLines:i,hookOutcome:s.stop?{kind:"stop",text:formatHookStop("PreToolUse",o,s.stopReason)}:void 0}}async function firePostToolUseHook(e){const{hookSystem:t,baseParams:n,toolBlock:r,toolResponse:o}=e,s=EE(r.toolName);try{const e=await t.fireEvent({eventName:"PostToolUse",input:buildPostToolUseInput({...n,toolUseId:r.toolCallId,toolName:r.toolName,toolInput:r.input,toolResponse:o}),toolName:r.toolName}),i=buildHookLines("PostToolUse",e),a=resolvePostHookOutcome({toolDisplayName:s,aggregate:e});return{additionalContext:e.additionalContext,stopSession:e.stop,sessionStopReason:e.stopReason,hookLines:i,hookOutcome:a}}catch(e){return dlog(`[Hook] PostToolUse dispatch failed: ${getErrorMessage(e)}`),{hookLines:[]}}}function wrapHookContextChunk(e){const t=e.context.replaceAll("</hook_context>","</hook_context>");return`<hook_context source="${e.source}" tool="${e.toolName}">${t}</hook_context>`}function buildHookLines(e,t){const n=[];for(const r of t.results)n.push(...linesForResult(e,r));return n}function linesForResult(e,t){const n=t.output?.systemMessage;if(n){const t=n.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(t.length>0){const n=[formatHookSaysLine(e,t[0])];for(let e=1;e<t.length;e++)n.push(t[e]);return n}}const r=t.output?.hookSpecificOutput?.additionalContext;return r?[formatHookSaysLine(e,`${t.displayLabel} added context`)]:[]}function buildBlockOrErrorOutcome(e){const{event:t,toolDisplayName:n,aggregate:r,fallbackReason:o}=e,s=r.results.find(e=>e.blocked);return 2===s?.exitCode?{kind:"hook-error",text:formatHookError(t,n,s.scriptPath,s.stderrFirstLine??s.blockReason??o)}:{kind:"block",text:formatHookBlock(t,n,o)}}function resolvePostHookOutcome(e){const{toolDisplayName:t,aggregate:n}=e,r=n.results.find(e=>e.blocked);if(r){const e=r.blockReason??"PostToolUse hook requested retry";return 2===r.exitCode?{kind:"hook-error",text:formatHookError("PostToolUse",t,r.scriptPath,r.stderrFirstLine??e)}:{kind:"block",text:formatHookBlock("PostToolUse",t,e)}}if(n.stop)return{kind:"stop",text:formatHookStop("PostToolUse",t,n.stopReason)}}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])),i=[],a=[],l=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?i.push(e):e.confidence>t?a.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&l.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:i,upgraded:a,downgraded:l}}wn(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),__name(createHookSystem,"createHookSystem"),Ot(),Ot(),wn(),__name(getProjectsBasePath,"getProjectsBasePath"),__name(getProjectDirName,"getProjectDirName"),__name(getTranscriptPath,"getTranscriptPath"),__name(baseInput,"baseInput"),__name(buildPreToolUseInput,"buildPreToolUseInput"),__name(buildPostToolUseInput,"buildPostToolUseInput"),Ot(),__name(formatHookSaysLine,"formatHookSaysLine"),__name(formatHookBlock,"formatHookBlock"),__name(formatHookError,"formatHookError"),__name(formatHookStop,"formatHookStop"),xE(),Kn(),__name(formatHookDenyMessage,"formatHookDenyMessage"),__name(firePreToolUseHook,"firePreToolUseHook"),__name(firePostToolUseHook,"firePostToolUseHook"),__name(wrapHookContextChunk,"wrapHookContextChunk"),__name(buildHookLines,"buildHookLines"),__name(linesForResult,"linesForResult"),__name(buildBlockOrErrorOutcome,"buildBlockOrErrorOutcome"),__name(resolvePostHookOutcome,"resolvePostHookOutcome"),Jr(),ao(),Ot(),wn(),Kn(),Ot(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings"),Jr(),ao(),hs();var Jk=new Xv("LearningAgent"),Xk=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:cs.LEARNING_AGENT,heading:"Learning pass failed"}}),Yk.addEvent({type:"error",message:n||"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)];Yk.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,i=Math.max(20,s),a=Math.max(0,t.length-i),l=t.slice(a);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.toolName).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:"tool",content:n}),u++}u>=this.maxTurns&&Jk.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Yk.addEvent({type:"no_learnings",message:"no changes to taste"}),Yk.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool-call"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.toolName,input:e.input});const t=this.adjustPathsForTaste({toolName:e.toolName,input:e.input});let o="",s="";if("write_file"===e.toolName||"edit_file"===e.toolName){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await L.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.toolName||"edit_file"===e.toolName){const e=t.filePath;e&&this.validateFinalTastePath(e)}const i=await executeTool(e.toolName,t,{allowTasteWrite:!0});let a="";if(("write_file"===e.toolName||"edit_file"===e.toolName)&&s)try{a=await L.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.toolName||"edit_file"===e.toolName){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:a});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{Yk.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Yk.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Yk.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:i}})}catch(t){n.push({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value: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 i=e.normalize(s);if(i.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${s}`);const a=e.resolve(e.join(this.tasteDir,i));if(!this.isPathInsideTasteDir(a))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 i="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)){const n=e.resolve(t);if(!this.isPathInsideTasteDir(n))throw new Error(`Security: Absolute path outside taste directory: ${t}`);if(i&&!this.isValidTasteFilePath(n))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=n}else{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.resolve(r),!this.isPathInsideTasteDir(r))throw new Error(`Security: Resolved path escapes taste directory: ${t} -> ${r}`);if(i&&!this.isValidTasteFilePath(r))throw new Error(`Invalid adjusted path: ${r}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}o[s]=r}return o}isPathInsideTasteDir(t){const n=e.resolve(this.tasteDir),r=e.resolve(t);if(r===n)return!0;const o=e.relative(n,r);return""!==o&&!o.startsWith("..")&&!e.isAbsolute(o)}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isPathInsideTasteDir(e))throw new Error(`Security: Resolved path escapes taste directory: ${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(!L.existsSync(this.tasteDir)){L.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");L.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!L.existsSync(t))return!1;const n=L.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");L.mkdirSync(r,{recursive:!0}),Yk.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const i=`# ${t.name}\n${t.learnings.join("\n")}\n`;L.writeFileSync(s,i,"utf-8");const a=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;o=o.replace(t.fullSection,a)}return L.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 L.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=L.readdirSync(n,{withFileTypes:!0});let s="";for(let t=0;t<o.length;t++){const i=o[t],a=t===o.length-1,l=a?"└── ":"├── ";if(i.isDirectory()){s+=`${r}${l}${i.name}/\n`;const t=r+(a?" ":"│ ");s+=await this.buildTree({dir:e.join(n,i.name),prefix:t})}else if("taste.md"===i.name){const t=(L.readFileSync(e.join(n,i.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;s+=`${r}${l}${i.name} (${t} learnings)\n`}else s+=`${r}${l}${i.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(),{token:o,oauthProvider:s}=await getOAuthCredentials({provider:n});validateOAuthToken({token:o,provider:n}),dlog(`[LearningAgent] callLearningAPI provider=${n} oauthProvider=${s} hasToken=${!!o}`);const i={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:r.toString(),[Ut.SESSION_ID]:`${this.sessionId}-learning`,...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};o&&(i[Ut.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Ut.OAUTH_PROVIDER]=s));const a=await this.getTasteTools(),l=getConfiguredModel();dlog(`[LearningAgent] calling ${Bt.ALPHA.TASTE.LEARN} (model: ${l})`);const u={conversation:t,tools:a,model:l,threadId:this.sessionId};let d=0,m=null;for(;d<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:Bt.ALPHA.TASTE.LEARN,body:u,headers:i,signal:this.abortSignal});if(!e)throw new Error("No response received");const t=e;return dlog(`[LearningAgent] API response received: ${t.content.length} blocks`),{role:"assistant",content:t.content}}catch(e){if(m=e instanceof Error?e:new Error(String(e)),d++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status||e?.statusCode;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${m.message}`),trackError({error:sanitizeErrorForTelemetry({error:m,label:"learning_api_client_error"}),context:{component:cs.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),m;if(d>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:m,label:"learning_api_max_retries"}),context:{component:cs.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":d}}),m;const n=1e3*Math.pow(2,d);dlog(`[LearningAgent] retrying API call (${d}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw m||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return L.existsSync(r)}};Ot(),wn(),Lo(),Jr(),ao(),Kn();var Zk="deepseek/deepseek-v4-pro",eT=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,n=Date.now();dlog("[CompactAgent] compacting",{messages:t.length,model:Zk});try{const e=await this.callCompactAPI({messages:t});return dlog("[CompactAgent] done",{model:Zk,durationMs:Date.now()-n,chars:e.summary.length,tokensIn:e.tokensUsed.input,tokensOut:e.tokensUsed.output,cached:e.tokensUsed.cached??0}),e}catch(e){throw dlog("[CompactAgent] error",{model:Zk,durationMs:Date.now()-n,error:e instanceof Error?e.message:String(e)}),e}}async callCompactAPI(e){const{messages:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced(),{token:o,oauthProvider:s}=await getOAuthCredentials({provider:n});validateOAuthToken({token:o,provider:n});const i={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};o&&(i[Ut.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Ut.OAUTH_PROVIDER]=s));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"),l={config:getEnvironmentContext(),memory:"",taste:"",skills:"",mode:"compact",params:{tools:[],system:"You compress a Command Code conversation into a handoff brief so a fresh assistant can pick up the work without rereading the original transcript.\n\nThe summary is the next assistant's only memory. Be precise. Prefer concrete artifacts (paths, function names, exact strings) over paraphrase. When code is mid-edit, include the snippet verbatim — losing it loses the work.\n\nCover these areas, in this order:\n\n**Goal**\nWhat the user is trying to accomplish across the whole conversation, with extra weight on the most recent ask. Include any constraints or success criteria the user has stated.\n\n**User turns**\nWalk through every user message that is not a tool result, in order. For each, capture the gist in one line — instructions, questions, corrections, reactions, \"no, not that\". Paraphrase is fine, but do not merge two turns into one and do not skip turns that look like noise; tone shifts and abandoned threads are signal. Quote verbatim when wording matters (e.g. precise rules the user laid down).\n\n**In-flight work**\nThe single task that was active immediately before this summary, in enough detail that the next assistant can resume without rediscovering anything. Name the file(s), the function(s), and the specific change being attempted.\n\n**Pending tasks**\nAnything the user has explicitly asked for that is not yet started or not yet finished, beyond the in-flight task. One bullet per item, in the order the user raised them. Omit work the user has since dropped or superseded. If nothing is queued, say \"None\".\n\n**Files touched**\nEvery file read or modified during the conversation. For each: path, what changed (or what was learned by reading it), and a code snippet where it helps the next assistant pick up — always for unfinished edits, and for finished edits when the snippet captures non-obvious context. Skip files that turned out to be irrelevant.\n\n**Decisions and constraints**\nDesign choices, library or pattern selections, and trade-offs that have already been settled. Include the reasoning so the next assistant doesn't relitigate them. Also capture user preferences picked up along the way (style rules, things to avoid, things to repeat).\n\n**Errors and feedback**\nFailures hit during the conversation, what fixed each one, and any course-correction the user gave. If the user told you to do something differently, capture that instruction in their words.\n\n**Resume point**\nThe exact next action to take. Only fill this in if the in-flight work has a clear continuation aligned with the user's latest ask — do not invent follow-ups, do not resurrect older threads the user has already moved on from. If the task was concluded, say so and stop. When you do fill it in, paste the user's most recent instruction word-for-word in quotes so the next assistant anchors on the actual ask instead of your paraphrase.\n\nWrite the summary directly. No preamble, no scratchpad, no wrapping tags.",messages:[{role:"user",content:`Please summarize the following conversation.\n\n${a}`}],model:Zk,max_tokens:16e3,stream:!0},threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:Bt.ALPHA.GENERATE,body:l,headers:i,stream:!0});if(!e)throw new Error("No response stream received");const t=await consumeSSEStream(e);return{summary:t.content.filter(e=>"text"===e.type).map(e=>e.text||"").join(""),tokensUsed:{input:t.usage.input_tokens,output:t.usage.output_tokens,cached:t.usage.cache_read_input_tokens??0}}}catch(e){d=e instanceof Error?e:new Error(String(e)),u++;const t=e?.status;if(t&&t>=400&&t<500)throw d;if(u>this.maxApiRetries)throw dlog("[CompactAgent] retries exhausted",{attempts:this.maxApiRetries,error:d.message}),d;dlog("[CompactAgent] retry",{attempt:u,max:this.maxApiRetries,error:d.message})}throw d||new Error("Compact API call failed")}};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={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:t.toString(),...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}},{token:r,oauthProvider:o}=await getOAuthCredentials({provider:e});return r&&(n[Ut.OAUTH_TOKEN]=`Bearer ${r}`,o&&(n[Ut.OAUTH_PROVIDER]=o)),n}function hasUserAndAssistantMessage(e){let t=!1,n=!1;for(const r of e)if(!isHiddenTranscriptMessage({message:r})&&("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}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let r="",o="";for(const e of t)if(!isHiddenTranscriptMessage({message:e})&&(r||"user"!==e.message.role||(r=extractMessageText(e.message.content).slice(0,os)),o||"assistant"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,os)),r&&o))break;if(!r||!o)return;const s=`Session description:\n<description>User: ${r}\n\n---\n\nAssistant: ${o}</description>\n\nGenerate the session title now.`,i=sn.MINIMAX_M2_5.id,a=await buildAuthHeaders(),l={config:getEnvironmentContext(),memory:"",taste:"",skills:"",mode:"title-gen",params:{tools:[],messages:[{role:"user",content:s}],model:i,system:"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. Don't reason.\n\nExample titles:\nAdd retry logic to API\nSimplify error handling flow\nClean up unused components",max_tokens:500,temperature:1,stream:!0},threadId:n.getSessionId()},u=getApiBaseUrl(),d=new jw({baseUrl:u});try{const e=await d.post({endpoint:Bt.ALPHA.GENERATE,body:l,headers:a,stream:!0}),t=await consumeSSEStream(e),r=t.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("").trim();if(!r)return void dlog("[TitleGen] empty",{model:i});await n.saveSessionTitle(r),dlog("[TitleGen] done",{model:i,title:r,tokensIn:t.usage.input_tokens,tokensOut:t.usage.output_tokens,cached:t.usage.cache_read_input_tokens??0})}catch(e){dlog("[TitleGen] error",{model:i,error:e instanceof Error?e.message:String(e)})}}async function callServerAPI(e){const t=await getConfiguredProvider(),n=await isOAuthEnforced(),{token:r,oauthProvider:o}=await getOAuthCredentials({provider:t});validateOAuthToken({token:r,provider:t});const s=await isTasteLearningEnabled(),i={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.TASTE_LEARNING]:s.toString(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:n.toString(),[Ut.SESSION_ID]:e.sessionId,...process.env.OSS_PRIMARY_PROVIDER?{[Ut.OSS_PRIMARY_PROVIDER]:process.env.OSS_PRIMARY_PROVIDER}:{}};r&&(i[Ut.OAUTH_TOKEN]=`Bearer ${r}`,o&&(i[Ut.OAUTH_PROVIDER]=o));const a=e.permissionMode??"standard",l="bypass"===a?"auto-accept":a,u={config:e.config,memory:e.memory,taste:e.taste??null,skills:e.skills??null,permissionMode:l,params:{model:e.model,messages:e.messages,tools:e.tools,system:e.system,max_tokens:e.maxOutputTokens??64e3,stream:!0,...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{}}};dlog(`[AISDKBridge] POST ${Bt.ALPHA.GENERATE} model=${e.model} msgs=${e.messages.length} tools=${e.tools.length}`);const d=getApiBaseUrl(),m=new jw({baseUrl:d}),g=ke.getTracer(_t),h=getSessionId(),f=getSessionContext(),y=g.startSpan(`chat ${e.model}`,{attributes:{[Rt.PROVIDER_NAME]:t??"unknown",[Rt.OPERATION_NAME]:"chat",[Rt.REQUEST_MODEL]:e.model,[Rt.RESPONSE_MODEL]:e.model,...h?{[Rt.CONVERSATION_ID]:h}:{},...void 0!==e.iteration?{[Rt.STEP_NAME]:`iteration_${e.iteration}`}:{},[Rt.CAPABILITY_NAME]:e.capability??"chat","cmd.tool_count":e.tools.length,"cmd.telemetry.content_capture":isContentCaptureEnabled()}},f),w=ke.setSpan(f,y);try{const t=await Te.with(w,()=>m.post({body:u,stream:!0,endpoint:Bt.ALPHA.GENERATE,signal:e.signal,headers:i,onHeaders:e.onSystemPromptBreakdown?t=>{const n=t.get(Ut.SYSTEM_PROMPT_BREAKDOWN);if(n)try{const t=JSON.parse(n);e.onSystemPromptBreakdown(t)}catch{}}:void 0})),n=await consumeSSEStream(t,{onText:e.onTextDelta});return n.usage&&(y.setAttribute(Rt.USAGE_INPUT_TOKENS,n.usage.input_tokens),y.setAttribute(Rt.USAGE_OUTPUT_TOKENS,n.usage.output_tokens),n.usage.cache_read_input_tokens&&y.setAttribute(Rt.USAGE_CACHED_INPUT_TOKENS,n.usage.cache_read_input_tokens)),y.setStatus({code:xe.OK}),y.end(),n}catch(e){throw e instanceof Error&&y.recordException(e),y.setStatus({code:xe.ERROR,message:e instanceof Error?e.message:String(e)}),y.end(),e}}Kn(),Ot(),sS(),Lo(),Jr(),ao(),Kn(),wn(),fS(),as(),__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle"),as(),Ot(),sS(),fS(),wn(),Jr(),ao(),Kn(),Oo(),fn(),__name(callServerAPI,"callServerAPI");var tT=new Xv("ContextEngine"),nT=200;function applyHookContextToMessage(e){const t=e.meta.hookContexts;if(!t||0===Object.keys(t).length)return e.message;const n=e.message;if("tool"!==n.role)return n;const r=n.content.map(e=>{const n=t[e.toolCallId];if(!n)return e;const r=[];if(n.preToolUse&&r.push(wrapHookContextChunk({context:n.preToolUse,source:"PreToolUse",toolName:e.toolName})),n.postToolUse&&r.push(wrapHookContextChunk({context:n.postToolUse,source:"PostToolUse",toolName:e.toolName})),0===r.length)return e;if("text"!==e.output.type)return e;const o="string"==typeof e.output.value?e.output.value:"";return{...e,output:{...e.output,value:`${o}\n\n${r.join("\n\n")}`}}});return{...n,content:r}}__name(applyHookContextToMessage,"applyHookContextToMessage");var rT=class{static{__name(this,"ContextEngine")}request;messages=[];callbacks;sessionManager;abortController=null;requestInterrupted=!1;contextTokensUsed=0;systemPromptBreakdown=null;currentInteractionTokens=0;compactionCount=0;modelChangeInFlight=!1;syncQueue=Promise.resolve();lastFileContexts=[];titleGenerationInFlight=!1;healedOrphanIds=new Set;learningAgent;compactAgent;checkpointManager;hookSystem=null;constructor(e,t,n){const r=getApiBaseUrl();this.request=new jw({baseUrl:r}),this.callbacks=e,this.sessionManager=new ok(t),this.learningAgent=new Xk({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new eT({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore(),n?.hookSystem&&(this.hookSystem=n.hookSystem)}getHookBaseParams(){return{sessionId:this.sessionManager.getSessionId(),cwd:process.cwd(),permissionMode:this.callbacks.getPermissionMode?.()||"standard"}}async firePreToolUseHook(e){return this.hookSystem?firePreToolUseHook({hookSystem:this.hookSystem,baseParams:this.getHookBaseParams(),toolBlock:e}):null}async firePostToolUseHook(e,t){return this.hookSystem?firePostToolUseHook({hookSystem:this.hookSystem,baseParams:this.getHookBaseParams(),toolBlock:e,toolResponse:t.toolResponse}):null}refreshRequest(){const e=getApiBaseUrl();this.request=new jw({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()})}async interrupt(e=!1){if(this.requestInterrupted=!0,this.abortController){this.abortController.abort(),this.abortController=null,tT.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-call"===e.type);if(n.length>0){const e=n.map(e=>({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:"Interrupted by user"}}));this.addMessageAndSync(this.createMessageWithMeta({role:"tool",content:e})),tT.debug(`Added tool-result parts for ${e.length} interrupted tool calls`)}e&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[{type:"text",text:"Interrupted by user"}]},{isAutomated:!0}))}if(e){const e=rE("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>tT.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n,r,o,s){let i=e,a=[];if(null===parseCommandTags({text:e}).commandMessage&&hasInlineSkillToken(i))try{a=await processSkillReferences(i)}catch(e){tT.error(`Skill reference processing failed: ${e}`)}let l=[];try{const t=await processFileReferences(e);if(i=t.processedContent,l=t.fileReferences,l.length>0){const e=l.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(i=`${n}\n\n${i}`);const u=rE(r??e);t&&t.length>0&&(u.metadata={...u.metadata,images:t}),l&&l.length>0&&(u.metadata={...u.metadata,fileReferences:l}),s&&(u.metadata={...u.metadata,ideHint:s}),this.callbacks.onFeedUpdate(u);const d=[];t&&t.length>0&&t.forEach(e=>{d.push({type:"image",image:`data:${e.mediaType};base64,${e.data}`})}),i.trim()&&d.push({type:"text",text:i});const m={role:"user",content:d},g=crypto.randomUUID(),h={messageId:g};this.getAutomatedMessageMeta({input:e,displayMessage:r,isAutomated:o?.isAutomated}).isAutomated&&(h.isAutomated=!0);const f=this.createMessageWithMeta(m,h);detectAndTrackFirstMessage().catch(()=>{}),this.addMessageAndSync(f),this.injectHiddenSkillMessages({hiddenMessages:o?.hiddenMessages}),a.length>0&&this.injectHiddenSkillMessages({hiddenMessages:a.map(e=>{const t=`Base directory for this skill: ${e.skillDirectory}\n\nThe content of SKILL.md is:\n${e.content}`;return{role:"user",content:tagSkillContent(e.skillName,t)}})}),this.checkpointManager.createSnapshot({messageId:g}).catch(e=>tT.error(`Failed to create checkpoint snapshot: ${e}`));const{ideHint:y,...w}=u.metadata??{},S={...u,metadata:w};this.sessionManager.saveMessages(this.messages,S).catch(e=>tT.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const E=await this.processMessages();return this.triggerTitleGeneration(),E}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.messages.filter(e=>!e.meta.isAutomated&&!this.messageContainsToolResult(e.message)).map(e=>e.message),t=this.sanitizeMessagesForAPI(e);await this.learningAgent.checkAndProcess({messages:t})}catch(e){tT.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager}).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;const t=new AbortController;this.abortController=t,this.learningAgent.setAbortSignal(t.signal);let n=!1,r=0;try{for(;;){r++;const t=startIterationSpan({iteration:r,model:getConfiguredModel(),initialMessageCount:this.messages.length});let o,s="continued";try{this.checkIfInterrupted(),n||(this.initializeInteractionTokens(),n=!0);const o=await this.callAPIWithRetry({iterationSpan:t,iterationNumber:r});this.checkIfInterrupted(),this.updateContextUsage(o),await this.checkAndCompactIfNeeded();const i=o.content.filter(e=>"tool-call"===e.type&&!e.providerExecuted),a=o.content.filter(e=>"tool-call"===e.type&&e.providerExecuted);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===i.length){const t=o.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===a.length){const t=sE(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>tT.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>tT.error(`Failed to save messages: ${e}`)),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0){let t=!1;for(const n of e){const e=rE(n.displayMessage??n.input);this.callbacks.onFeedUpdate(e);const r=this.getAutomatedMessageMeta(n);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:n.input},r)),t=!0}this.sessionManager.saveMessages(this.messages).catch(e=>tT.error(`Failed to save messages: ${e}`)),t&&this.triggerLearningAgent();continue}}s="completed";break}const l=o.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);if(l.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:l})),e.trim()){const t=sE(e);this.callbacks.onFeedUpdate(t)}const u=await this.executeToolBlocks({toolBlocks:i}),{toolResults:d,executedToolIds:m,permissionDenied:g,hookContextsByToolCallId:h,sessionStop:f}=u;if(g){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-call"===e.type?m.has(e.toolCallId):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}s="completed";break}let y=!1,w=!1;if(d.length>0){const e=Object.keys(h).length>0;this.addMessageAndSync(this.createMessageWithMeta({role:"tool",content:d},e?{hookContexts:h}:{})),y=!0}if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){const e=rE(t.displayMessage??t.input);this.callbacks.onFeedUpdate(e);const n=this.getAutomatedMessageMeta(t);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t.input},n)),y=!0,w=!0}}if(y&&this.sessionManager.saveMessages(this.messages).catch(e=>tT.error(`Failed to save messages: ${e}`)),w&&this.triggerLearningAgent(),f){s="completed";break}}catch(e){throw this.isNonRetryableError(e)&&tT.debug("Request interrupted or insufficient credits"),o=e instanceof Error?e:new Error(String(e)),s=this.classifyIterationOutcome(e),e}finally{t.end({outcome:s,error:o})}}}finally{this.abortController===t&&(this.abortController=null)}return 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){tT.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return tT.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){const e=this.messages.map(e=>applyHookContextToMessage(e));return this.sanitizeMessagesForAPI(e)}sanitizeMessagesForAPI(e){const t=[];for(const n of e){if("tool"===n.role){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-call"===t.type&&r.add(t.toolCallId);const o=n.content.filter(e=>"tool-result"!==e.type||r.has(e.toolCallId));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 this.healOrphanToolUses(t)}healOrphanToolUses(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(t.push(r),"assistant"!==r.role)continue;if(!Array.isArray(r.content))continue;const o=[];for(const e of r.content)"tool-call"===e.type&&o.push({id:e.toolCallId,name:e.toolName});if(0===o.length)continue;const s=e[n+1],i="tool"===s?.role&&Array.isArray(s.content),a=new Set;if(i)for(const e of s.content)"tool-result"===e.type&&a.add(e.toolCallId);const l=o.filter(e=>!a.has(e.id));if(0===l.length)continue;const u=l.map(e=>({type:"tool-result",toolCallId:e.id,toolName:e.name,output:{type:"error-text",value:`Tool ${e.name} did not complete`}})),d=l.filter(e=>!this.healedOrphanIds.has(e.id));for(const e of d)this.healedOrphanIds.add(e.id);d.length>0&&endSpan({span:createSpan({name:"sanitize:healed_orphan_tool_use",attributes:{"cmd.sanitize.unmatched_count":d.length,"cmd.sanitize.tool_names":d.map(e=>e.name).join(","),"cmd.sanitize.next_message_role":s?.role??"none"}}),status:"success"}),dlog(`[sanitizeMessages] healed ${l.length} orphan tool_use(s) (${d.length} new): ${l.map(e=>`${e.name}#${e.id}`).join(", ")}`),i?(t.push({...s,content:[...s.content,...u]}),n++):t.push({role:"tool",content:u})}return t}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getHookSystem(){return this.hookSystem}getContextTokensUsed(){return this.contextTokensUsed}getContextLimit(){return getContextLimit(getConfiguredModel())}async onModelChanged(e){const t=this.getContextLimit(),n=this.contextTokensUsed;if(this.modelChangeInFlight)return this.callbacks.onContextUsageUpdate?.({current:n,limit:t}),{overflowed:!1,tokensUsed:n,newLimit:t,tokensSaved:0};this.modelChangeInFlight=!0;try{if(this.callbacks.onContextUsageUpdate?.({current:n,limit:t}),void 0!==e&&t>=e)return{overflowed:!1,tokensUsed:n,newLimit:t,tokensSaved:0};if(n<=Math.floor(t*hn.TIER_3_THRESHOLD))return{overflowed:!1,tokensUsed:n,newLimit:t,tokensSaved:0};const r=this.contextTokensUsed;try{await this.summarizeAndCompact()}catch(e){tT.debug(`Failed to auto-compact after model switch: ${String(e)}`)}const o=Math.max(0,r-this.contextTokensUsed);return o>0&&this.compactionCount++,this.callbacks.onContextUsageUpdate?.({current:this.contextTokensUsed,limit:t}),{overflowed:!0,tokensUsed:n,newLimit:t,tokensSaved:o}}finally{this.modelChangeInFlight=!1}}getSystemPromptBreakdown(){return this.systemPromptBreakdown}getCompactionCount(){return this.compactionCount}isRequestInProgress(){return null!==this.abortController}async manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};tT.debug(`Manual compact: ${this.messages.length} messages`);const e=this.contextTokensUsed;await this.summarizeAndCompact();const t=Math.max(0,e-this.contextTokensUsed);return this.compactionCount++,{tokensSaved:t,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],i=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===i){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"===i){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool-call"===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"!==i&&"assistant"!==i&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,n-o);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:this.getContextLimit()}),{messagesRemoved:t-s.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}injectHiddenSkillMessages(e){const{hiddenMessages:t}=e;if(t&&0!==t.length)for(const e of t)this.addMessageAndSync(this.createMessageWithMeta(e,{isMeta:!0,messageId:crypto.randomUUID()}))}isAutomatedSlashCommandPrompt(e){const{input:t,displayMessage:n}=e;return!!n&&!!n.trim().startsWith("/")&&n.trim()!==t.trim()}getAutomatedMessageMeta(e){return e.isAutomated||this.isAutomatedSlashCommandPrompt(e)?{isAutomated:!0}:{}}messageContainsToolResult(e){if("user"!==e.role)return!1;const t=e.content;return!!Array.isArray(t)&&t.some(e=>{if("object"!=typeof e||null===e||!("type"in e))return!1;const t=e.type;return"tool_result"===t||"tool-result"===t})}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){if(!t.meta.isMeta)try{const n=Nf.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Bt.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 prepareServerCall(){const e=this.callbacks.getPermissionMode?.()||"standard",t=await getToolSchemas({mode:e}),n=await getConfiguredProvider();n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n);const r=getConfiguredModel(),o=modelSupportsReasoningEffort(r)?getReasoningEffort(r):void 0,s=this.getRawMessages(),i=getEnvironmentContext(),a=await getMemoryContent(this.lastFileContexts),l=await getTasteContent(),u=await loadAllSkillSummaries(),{names:d}=await loadDisabledSkills(),m=generateSkillsXML(0===d.size?u:{global:u.global.filter(e=>!d.has(e.name)),project:u.project.filter(e=>!d.has(e.name))});return tT.debug(`prepareServerCall (${r}, ${s.length} msgs, ${t.length} tools)`),{model:r,messages:s,tools:t,config:i,memory:a||null,taste:l||null,skills:m||null,permissionMode:e,reasoningEffort:o}}async callAPIWithRetry(e){const{iterationSpan:t,iterationNumber:n}=e;let r=null,o=0;const{model:s,messages:i,tools:a,config:l,memory:u,taste:d,skills:m,permissionMode:g,reasoningEffort:h}=await this.prepareServerCall();t?.recordPayloadHealth(computePayloadHealth(i));for(let e=0;e<10;e++)try{const r=await callServerAPI({model:s,messages:i,tools:a,config:l,memory:u,taste:d,skills:m,permissionMode:g,maxOutputTokens:64e3,sessionId:this.sessionManager.getSessionId(),iteration:n,reasoningEffort:h,signal:this.abortController?.signal,onTextDelta:__name(e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)},"onTextDelta"),onSystemPromptBreakdown:__name(e=>{this.systemPromptBreakdown=e},"onSystemPromptBreakdown"),onError:__name(e=>{tT.debug(`API stream error: ${e.message}`)},"onError")});return this.callbacks.onRetryUpdate?.(null),t?.recordAttempt({attempt:e+1,delayMsBefore:o,status:"ok"}),r}catch(n){r=n instanceof Error?n:new Error(String(n)),dlog(`[ContextEngine] API error (attempt ${e+1}/10): statusCode=${n?.statusCode} status=${n?.status} message=${n?.message} responseBody=${n?.responseBody?.substring?.(0,300)}`);const s=n?.statusCode??n?.status,i=!this.isNonRetryableError(n),a=this.classifyApiErrorLabel(n);if(t?.recordAttempt({attempt:e+1,delayMsBefore:o,status:"error",errorType:a,errorMessage:r.message,httpStatus:"number"==typeof s?s:void 0,isRetryable:i}),this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(n))throw trackError({error:sanitizeErrorForTelemetry({error:n instanceof Error?n:new Error(String(n)),label:"non_retryable_api_error"}),context:{component:cs.CONTEXT_ENGINE,heading:"Non-retryable AI SDK error",code:n?.status||n?.statusCode}}),this.formatAPIError(n);if(9===e)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:r,label:"api_max_retries_exceeded"}),context:{heading:"AI SDK max retries exceeded",component:cs.CONTEXT_ENGINE,"cmd.retry.attempts":10}}),this.formatAPIError(n);const l=Math.min(e,10),u=100*Math.pow(2,l),d=Math.max(u,1e3),m=Math.min(d,1e4);o=m,e>=2&&this.callbacks.onRetryUpdate?.(e+1),await sleep({delay:m,signal:this.abortController?.signal})}throw r||new Error("Failed to get response after retries")}classifyIterationOutcome(e){const t=e instanceof Error?e.message:"string"==typeof e?e:"",n=t.toLowerCase();return"Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")?"interrupted":this.isNonRetryableError(e)?"non_retryable_error":"max_retries_exceeded"}classifyApiErrorLabel(e){const t=e?.statusCode??e?.status,n=(e instanceof Error?e.message:"string"==typeof e?e:"").toLowerCase();return n.includes("connection error")?"connection_error":n.includes("tool result is missing")||n.includes("missing tool results")?"missing_tool_results":n.includes("rate limit")||429===t?"rate_limit":n.includes("overloaded")||529===t?"overloaded":401===t||403===t?"auth_error":"number"==typeof t&&t>=500?"server_error":"number"==typeof t&&t>=400?"client_error":e instanceof Error?e.name:"unknown_error"}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=t?.includes("PREMIUM_CREDITS_EXHAUSTED:"),i=t?.includes("MODEL_NOT_IN_PLAN:"),a="UPSTREAM_PROVIDER_UNAVAILABLE"===e?.code,l="CMD_ZDR_NO_PROVIDERS"===e?.code||"cmd_zdr_no_providers"===e?.type||"CMD_ZDR_NO_PROVIDERS"===e?.error?.code||"cmd_zdr_no_providers"===e?.error?.type,u=!1===e?.isRetryable;u&&dlog(`[ContextEngine] AI SDK isRetryable=false: status=${e?.statusCode??e?.status} message=${e?.message}`);const d=e?.status||e?.statusCode,m=e instanceof Cs||401===d||e instanceof vs||403===d,g=e?.type||e?.error?.type,h="rate_limit_error"===g||429===d||n.includes("rate limit"),f="overloaded_error"===g||529===d||n.includes("overloaded");return r||o||s||i||a||l||u||m||h||f}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.responseBody){const n=parseEmbeddedErrorJSON(e.responseBody);if(n)return{...n,status:n.status||t};try{const n=JSON.parse(e.responseBody);if(n?.error?.message)return{status:t,type:n.error.type||null,message:n.error.message}}catch{}}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,s=getSupportId(),i="unknown"!==s?`\nRequest ID: ${s}`:"",a='\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord';dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",o);const l=o?.toLowerCase().includes("insufficient credits");if(l)return new Error(`Insufficient credits\n\nUpgrade your plan or add credits: https://commandcode.ai/settings/billing${i}`);const u=o?.includes("PREMIUM_CREDITS_EXHAUSTED:");if(u)return new Error("Premium credits exhausted");const d=o?.includes("MODEL_NOT_IN_PLAN:");if(d)return new Error(`Model not in plan: ${o?.replace("MODEL_NOT_IN_PLAN:","").trim()}`);if("CMD_ZDR_NO_PROVIDERS"===e?.code||"cmd_zdr_no_providers"===e?.type||"CMD_ZDR_NO_PROVIDERS"===e?.error?.code||"cmd_zdr_no_providers"===e?.error?.type)return new Error(o||"This model has no zero-data-retention upstream. Disable CMD_ZDR or pick a different model.");const m=o?.toLowerCase().includes("oauth authentication required");if(m)return e;if(e instanceof Cs||401===(e?.status||e?.statusCode))return new Error(`Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.${a}${i}`);let g="";if(o)if(o.includes("Invalid 'Authorization' header"))g=`Error: Authentication failed. Run "cmd login" to sign in again.${a}${i}`;else{let e=o;for(;e.startsWith("Error: ");)e=e.substring(7);(e.includes("Unexpected event order")||e.includes("part")&&e.includes("not found")||e.includes("AI_")||e.includes("Invalid prompt"))&&(e="Something went wrong. Please try again or contact support if the issue persists.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>nT&&(t=t.substring(0,nT)+"..."),g=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const s=o.toLowerCase(),l="overloaded_error"===r||s.includes("overloaded"),u="rate_limit_error"===r||s.includes("rate limit");g+=l?"\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.':a,g+=i}else{const t=e?.toString?.()||"Unknown error occurred";g=t.length>nT?t.substring(0,nT)+"...":t,g+=a+i}return new Error(g)}async executeToolBlocks(e){const t=new Set;let n=!1;const r={};let o;const s=[],i=[];for(const r of e.toolBlocks){this.checkIfInterrupted();const e=crypto.randomUUID(),o=dS.includes(r.toolName),a=this.callbacks.getPermissionMode?.(),l="auto-accept"!==a&&"bypass"!==a&&mS.includes(r.toolName)?this.getToolDescription(r):Promise.resolve(null);let u=null;try{o&&this.callbacks.onPermissionRequest&&(u=await l);const t=await this.checkToolPermission(r,u);if(t.needsPermission&&!t.allowed){this.handlePermissionDenied(r,e),n=!0;break}}catch(n){const o=n instanceof Error?n.message:"Permission check failed";this.showToolError(r,o,e,u),i.push({toolBlock:r,toolResult:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:{type:"error-text",value:`Error: ${o}`}}}),t.add(r.toolCallId);continue}null===u&&(u=await l),s.push({toolBlock:r,entryId:e,description:u})}const a=[];for(const{toolBlock:e,toolResult:n}of i)a.push(n),t.add(e.toolCallId);if(s.length>0){const e=await Promise.allSettled(s.map(async({toolBlock:e,entryId:t,description:n})=>{this.checkIfInterrupted();const r="edit_file"===e.toolName?await resolveEditStartLine({filePath:e.input.filePath,oldContent:e.input.oldValue}).catch(()=>{}):void 0,o=!isAgentTool(e.toolName)&&e.toolName!==iS.GET_SELF_KNOWLEDGE,s=await this.firePreToolUseHook(e);if(s?.blocked)return o&&s.hookOutcome&&this.showToolBlockedByHook(e,t,n,{preHookLines:s.hookLines,hookOutcome:s.hookOutcome}),{toolBlock:e,toolResult:{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:s.denyReason}},hookContext:void 0,sessionStop:s.stopSession?{reason:s.sessionStopReason}:void 0};o&&this.showToolRunning(e,t,n,{preHookLines:s?.hookLines});const i=await this.executeSingleTool(e),a=await this.firePostToolUseHook(e,{toolResponse:i}),l=a?.additionalContext,u={};s?.additionalContext?.trim()&&(u.preToolUse=s.additionalContext.trim()),l?.trim()&&(u.postToolUse=l.trim());const d=Object.keys(u).length>0;o&&this.showToolSuccess(e,i,t,n,r,{preHookLines:s?.hookLines,postHookLines:a?.hookLines,hookOutcome:a?.hookOutcome??s?.hookOutcome});const m=s?.stopSession||a?.stopSession?{reason:s?.sessionStopReason??a?.sessionStopReason}:void 0;return{toolBlock:e,toolResult:{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:i}},hookContext:d?u:void 0,sessionStop:m}}));for(let n=0;n<e.length;n++){const i=e[n],{toolBlock:l,entryId:u,description:d}=s[n];if("fulfilled"===i.status)a.push(i.value.toolResult),i.value.hookContext&&(r[l.toolCallId]=i.value.hookContext),i.value.sessionStop&&!o&&(o=i.value.sessionStop),t.add(l.toolCallId);else{const e=i.reason instanceof Error?i.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(l.toolName)?t.add(l.toolCallId):(a.push({type:"tool-result",toolCallId:l.toolCallId,toolName:l.toolName,output:{type:"error-text",value:`Error: ${e}`}}),t.add(l.toolCallId),l.toolName!==iS.GET_SELF_KNOWLEDGE&&this.showToolError(l,e,u,d))}}}return{toolResults:a,executedToolIds:t,permissionDenied:n,hookContextsByToolCallId:r,sessionStop:o}}async getToolDescription(e){try{return await Promise.race([generateToolDescription(e.toolName,e.input),new Promise(e=>setTimeout(()=>e(null),5e3))])}catch(t){return tT.debug(`Failed to generate description for ${e.toolName}: ${t instanceof Error?t.message:"Unknown error"}`),this.callbacks.onToolDescriptionError&&this.callbacks.onToolDescriptionError(e.toolName,t),null}}async checkToolPermission(e,t){return dS.includes(e.toolName)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.toolName,e.input,t)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=this.callbacks.getPermissionMode?.()||"standard",n=await executeTool(e.toolName,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),o=estimateTokens(r);return this.currentInteractionTokens+=o,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=CE(e.toolName,e.input),r={..."edit_file"===e.toolName?e.input:{},permissionDenied:!0},o={...iE(e.toolName,n,r),id:t},s=gE(o,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(s)}buildToolMetadata({toolBlock:e,editStartLine:t}){if("edit_file"===e.toolName)return{...e.input,...void 0!==t?{startLine:t}:{}};if("write_file"===e.toolName){const t=e.input,n="string"==typeof t.content?t.content:"",r=n.split("\n"),o=r.length>Go?r.slice(0,Go).join("\n"):n;return{...t,content:o,totalLines:r.length}}}showToolRunning(e,t,n,r){const o=CE(e.toolName,e.input),s={...iE(e.toolName,o,{status:"running"}),id:t,...n?{description:n}:{}};r?.preHookLines?.length&&setPreHookLines(s,r.preHookLines),this.callbacks.onFeedUpdate(s)}showToolSuccess(e,t,n,r,o,s){let i=this.buildToolMetadata({toolBlock:e,editStartLine:o});if("read_file"===e.toolName){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(i={...i||{},isTasteFile:!0,tasteCategory:e.category})}}const a={...e.input,...i?.isTasteFile?{isTasteFile:i.isTasteFile}:{},...i?.tasteCategory?{tasteCategory:i.tasteCategory}:{}},l=CE(e.toolName,a),u={...iE(e.toolName,l,i),id:n,...r?{description:r}:{}},d=gE(u,t);s?.preHookLines?.length&&setPreHookLines(d,s.preHookLines),s?.postHookLines?.length&&setPostHookLines(d,s.postHookLines),s?.hookOutcome&&setHookOutcome(d,s.hookOutcome),this.callbacks.onFeedUpdate(d)}showToolBlockedByHook(e,t,n,r){const o=CE(e.toolName,e.input),s={...iE(e.toolName,o,{status:"hook-blocked"}),id:t,...n?{description:n}:{}};r.preHookLines?.length&&setPreHookLines(s,r.preHookLines),setHookOutcome(s,r.hookOutcome),this.callbacks.onFeedUpdate(s)}showToolError(e,t,n,r){const o=CE(e.toolName,e.input),s="edit_file"===e.toolName?{...e.input,permissionDenied:!0}:void 0,i={...iE(e.toolName,o,s),id:n,...r?{description:r}:{}},a=gE(i,hE(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"tool-call"===e.type&&e.providerExecuted).length)return"";let t="";const n=e.content;for(const e of n)if("text"===e.type)t+=e.text;else if("tool-call"===e.type&&e.providerExecuted){if(t.trim()){const e=sE(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:o}=uS({serverToolBlock:e,contentBlocks:n}),s=CE(e.toolName,e.input),i=iE(e.toolName,s),a=gE(i,o?hE(r):r);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=sE(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:this.getContextLimit()})}async checkAndCompactIfNeeded(){const e=this.getContextLimit(),t=Math.floor(e*hn.TIER_1_THRESHOLD),n=Math.floor(e*hn.TIER_2_THRESHOLD),r=Math.floor(e*hn.TIER_3_THRESHOLD),o=getCompactMode();try{if(this.contextTokensUsed>r){tT.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 3 threshold (${r}), 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("fast"!==o)return;if(this.contextTokensUsed>n){tT.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${n}), removing all except last ${hn.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(hn.TIER_2_KEEP_COUNT);return tT.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void this.emitAutoCompactInfo(e.tokensSaved)}if(this.contextTokensUsed>t){const e=this.countToolCalls(),n=hn.TIER_1_KEEP_COUNT;if(e>n){tT.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${t}), keeping last ${n} tool calls`);const e=await this.removeToolCallsExceptLast(n);tT.debug(`Tier 1 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),this.emitAutoCompactInfo(e.tokensSaved)}}}catch(e){tT.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){this.compactionCount++,e>0&&this.callbacks.onFeedUpdate(oE(`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-call"===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-call"===t[n].type&&r.push({id:t[n].toolCallId,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)),i=[];for(const e of this.messages){const t=e.message.role,r=e.message.content;if("tool"===t&&Array.isArray(r)){const t=r.filter(e=>"tool-result"!==e.type||!s.has(e.toolCallId)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool-call"!==e.type||!s.has(e.toolCallId)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}i.push(e)}this.messages=i,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,t-n);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:this.getContextLimit()}),{toolsRemoved:s.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return tT.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(hn.TIER_2_KEEP_COUNT);tT.debug(`Summarizing ${e.length} older messages, keeping ${t.length} recent messages`);const n=e.filter(e=>!isHiddenTranscriptMessage({message:e})).map(e=>e.message),r=await this.compactAgent.compactMessages({messages:n});tT.debug(`Summarization complete: ${r.summary.length} chars, tokensIn=${r.tokensUsed.input} tokensOut=${r.tokensUsed.output} cached=${r.tokensUsed.cached}`);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,i=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[o,...t],await this.sessionManager.saveMessages(this.messages);const a=estimateTokens(o.message),l=Math.max(0,s-i+a);this.contextTokensUsed=l,this.callbacks.onContextUsageUpdate?.({current:l,limit:this.getContextLimit()}),tT.debug(`Tier 3 summarization complete: reduced from ${s} to ~${l} tokens`)}catch(e){tT.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(hn.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=hn.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 i=o.message.content;Array.isArray(i)&&i.some(e=>"tool-result"===e.type)}n=Math.min(n,this.messages.length-3),n=Math.max(0,n);let r=0;this.messages[0]?.meta?.isSummary&&(r=1);for(let e=r;e<n;e++){const t=this.messages[e].message.content;if(Array.isArray(t)&&t.some(e=>"image"===e.type)){n=e;break}}for(;n>r&&"user"===this.messages[n].message.role;)n--;return{messagesToSummarize:this.messages.slice(r,n),messagesToKeep:this.messages.slice(n),keepStartIndex:n}}getCheckpointManager(){return this.checkpointManager}listCheckpoints(){return this.checkpointManager.listCheckpoints()}hasCheckpoints(){return this.checkpointManager.hasCheckpoints()}async restoreToCheckpoint(e){const{messageId:t,mode:n}=e;this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()});const r=this.sessionManager.getMessageIndexById({messageId:t,messages:this.messages});let 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:this.getContextLimit()})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots(),this.checkpointManager.runCleanup().catch(()=>{})}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}};Ot(),xE(),ro();var oT=createOSC8Link("https://commandcode.ai/docs/hooks","Docs ↗",!1),sT=["Invalid JSON","Failed to read","Invalid hooks structure"];function isFileLevelWarning(e){return sT.some(t=>e.startsWith(t))}__name(isFileLevelWarning,"isFileLevelWarning");var iT={unknown_event:{singular:"unknown event",plural:"unknown events"},invalid_matcher:{singular:"invalid matcher",plural:"invalid matchers"},invalid_hook:{singular:"invalid hook",plural:"invalid hooks"}},aT=["unknown_event","invalid_matcher","invalid_hook"],lT={singular:"hook config issue",plural:"hook config issues"};function categorizeHookLevelWarning(e){return e.startsWith("Unknown event")?"unknown_event":e.startsWith("Invalid matcher")?"invalid_matcher":"invalid_hook"}function pluralize(e,t){return`${e} ${1===e?t.singular:t.plural}`}function summarizeHookLevelWarnings(e){if(0===e.length)return null;const t={unknown_event:0,invalid_matcher:0,invalid_hook:0};for(const n of e)t[categorizeHookLevelWarning(n)]+=1;const n=aT.filter(e=>t[e]>0).map(e=>pluralize(t[e],iT[e])).join(", ");return`${pluralize(e.length,lT)}: ${n}.`}function buildHookStartupEntries(e){const t=[],n=[];for(const r of e)isFileLevelWarning(r)?t.push(r):n.push(r);const r=t.map(e=>({message:e,isHookWarning:!0})),o=summarizeHookLevelWarnings(n);if(o&&r.push({message:o,isHookWarning:!1}),0===r.length)return[];const s=r[r.length-1];return s.message=`${s.message} ${oT}`,r.map(e=>e.isHookWarning?oE(e.message,{isHookWarning:!0}):oE(e.message))}function createHookSystemStartupState(e){const t=createHookSystem(e),n=t.initialize().then(()=>buildHookStartupEntries(t.drainTrustWarnings())).catch(e=>[oE(`Hook system failed to initialize: ${getErrorMessage(e)}`,{isHookWarning:!0})]);return{hookSystem:t,startupEntriesPromise:n}}function bootstrapContextEngineWithHooks(e){const t=createHookSystemStartupState({projectRoot:e.projectRoot,sessionId:e.sessionId,runMode:e.runMode,permissionMode:e.permissionMode});return{contextEngine:new rT(e.callbacks,e.sessionId,{hookSystem:t.hookSystem}),startupEntriesPromise:t.startupEntriesPromise}}function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:t,description:`Terminate process on ${t}`}}function buildShellPermissionRequest(e,t){const n=e.args,r=Array.isArray(n)?n.join(" "):"string"==typeof n?n:"";return{command:"string"==typeof e.command?e.command:"",args:"string"==typeof n?n:Array.isArray(n)?n.join(" "):void 0,workingDirectory:"string"==typeof e.directory?e.directory:void 0,description:t??`Execute shell command: ${String(e.command??"")} ${r}`}}function getFileAction(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function buildFilePermissionRequest(e,t){const n="edit_file"===e?t.oldValue:void 0,r="edit_file"===e?t.newValue:void 0;return{action:getFileAction(e),filePath:String(t.filePath??t.file_path??t.path??t.absolutePath??"unknown"),description:"string"==typeof t.description?t.description:`${e} operation`,oldContent:"string"==typeof n?n:void 0,newContent:"string"==typeof r?r:void 0}}function useContextEngine({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:r,setFeed:o,setLiveEntries:s,setQueuedMessages:i,queuedMessagesRef:a,setStatus:l,pinnedStatusRef:u,setRetryAttempt:d,setInteractionTokens:m,setContextUsage:g,setCurrentProvider:h,shareInfoRef:f,permissionsService:y,permissionModeRef:w,setPendingQuestion:S,contextEngineRef:E}){const C=ee(t=>({onFeedUpdate:__name(e=>{const t=e.metadata?.status;"running"!==t?(s(t=>0===t.length?t:t.filter(t=>t.id!==e.id)),o(t=>[...t,e])):s(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]})},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...a.current];return a.current=[],i([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{m(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{g(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{h(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!y)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await y.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await y.requestShellPermission(e)).allowed}const o=buildFilePermissionRequest(e,r);return(await y.requestPermission(o,w.current)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{S({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=f.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>w.current,"getPermissionMode")}),[w,y,u,a,e,g,h,o,s,S,i,d,l,m,f]);return X(()=>{if(E.current||!r||n||t)return;let s=!1;const{contextEngine:i,startupEntriesPromise:a}=bootstrapContextEngineWithHooks({projectRoot:process.cwd(),sessionId:e,runMode:"interactive",permissionMode:w.current,callbacks:C()});a.then(e=>{s||0===e.length||o(t=>[...t,...e])}),E.current=i;const l=__name(async()=>{await(E.current?.getHookSystem()?.shutdown())},"onBeforeExit");return process.on("beforeExit",l),()=>{s=!0,process.removeListener("beforeExit",l)}},[e,n,t,r,C,E,w,o]),{createContextEngineCallbacks:C}}__name(categorizeHookLevelWarning,"categorizeHookLevelWarning"),__name(pluralize,"pluralize"),__name(summarizeHookLevelWarnings,"summarizeHookLevelWarnings"),__name(buildHookStartupEntries,"buildHookStartupEntries"),__name(createHookSystemStartupState,"createHookSystemStartupState"),__name(bootstrapContextEngineWithHooks,"bootstrapContextEngineWithHooks"),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Ot(),Ot(),Ot(),Kn();var cT=5242880,uT=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(w.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await v.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>5e4?e.slice(0,5e4)+"...":e;this.buffer[this.buffer.length-1]!==t&&(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 v.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await v.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 v.stat(this.filePath);if(e.size<=cT)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await v.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=Math.floor(2621440),r=[];let o=0;for(let e=t.length-1;e>=0;e--){const s=Buffer.byteLength(t[e],"utf-8")+1;if(o+s>n)break;o+=s,r.unshift(t[e])}await v.writeFile(this.filePath,r.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${r.length} of ${t.length} entries (${o} bytes)`)}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 uT}__name(createHistoryManager,"createHistoryManager"),BS(),Ot(),wn();var dT=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await v.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await v.access(r);const e=await v.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await v.writeFile(r,t,"utf-8")}catch{await v.writeFile(r,Ob+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await v.access(n),!0}catch{return!1}}};async function copyOrFallback(e,t){if(!isClipboardAvailable())return t(`Share URL: ${e} (clipboard unavailable, copy manually)`),!1;try{const t=await import("@crosscopy/clipboard");return await t.default.setText(e),!0}catch{return t(`Share URL: ${e} (clipboard unavailable, copy manually)`),!1}}async function loadShareInfo({contextEngineRef:e,setShareInfo:t}){const n=e.current?.getSessionManager();if(n){const e=await n.loadShareInfo();e&&t({url:e.url,secret:e.secret})}}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:o,contextEngineRef:s}){if(e){if(t)return void(await copyOrFallback(t.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},3e3)));try{r("Creating share link...");const t=s.current?.getMessages()||[],i=Nf.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new jw({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:Bt.ALPHA.SHARE.CREATE,body:{sessionId:e,messages:i}});n({url:l.url,secret:l.secret});const u=s.current?.getSessionManager();u&&await u.saveShareInfo({url:l.url,secret:l.secret}),await copyOrFallback(l.url,r)&&(r(""),o(!0),setTimeout(()=>{o(!1)},5e3))}catch(e){r(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else r("No active session to share")}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:o,contextEngineRef:s}){if(e){if(!t)return o("NOT SHARED: Session is not currently shared"),void setTimeout(()=>o(""),5e3);try{r("Removing share link...");const i=new jw({baseUrl:getApiBaseUrl()});await i.delete({endpoint:Bt.ALPHA.SHARE.DELETE,body:{sessionId:e,secret:t.secret}});const a=s.current?.getSessionManager();a&&await a.deleteShareInfo(),o("UNSHARED: Sharing has stopped"),r(""),n(null),setTimeout(()=>{o("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;r(t),setTimeout(()=>r(""),5e3)}}else r("No active session to unshare")}function getContextEngineCallbacks(e){const{createContextEngineCallbacks:t,sessionId:n}=e;return t(n)}async function handleSelectSession({selectedSessionId:e,sessionLoadIdRef:t,contextEngineRef:n,setFeed:r,setLiveEntries:o,setSessionId:s,setShowSessionSelector:i,setSessionLoaded:a,permissionModeRef:l,setStaticKey:u,setShareInfo:d,createContextEngineCallbacks:m}){const g=crypto.randomUUID();t.current=g;try{await(n.current?.getHookSystem()?.shutdown()),r([]),o([]),n.current=null,s(e),i(!1),a(!0);const h=getContextEngineCallbacks({createContextEngineCallbacks:m,sessionId:e}),{contextEngine:f,startupEntriesPromise:y}=bootstrapContextEngineWithHooks({projectRoot:process.cwd(),sessionId:e,runMode:"interactive",permissionMode:l.current,callbacks:h});n.current=f;const[{feedEntries:w,corruptedLines:S,totalLines:E},C]=await Promise.all([f.loadSession(e),y]);if(t.current!==g)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const v=[...C];if(0===w.length&&E>0&&v.push(cE(`Session could not be loaded. ${E} lines could not be parsed.`)),0===w.length&&0===E&&v.push(oE("Session loaded but contains no messages.")),w.length>0&&(S>0&&v.push(oE(`Warning: ${S} message(s) could not be loaded.`)),v.push(...w)),t.current!==g)return;r(v),wb(),u(e=>e+1)}catch(e){if(t.current!==g)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([cE(`Failed to load session: ${n}. Starting fresh session.`)]),i(!1),a(!1),s(crypto.randomUUID())}}async function handleNewSession({contextEngineRef:e,setFeed:t,setLiveEntries:n,setSessionId:r,setShowSessionSelector:o,setSessionLoaded:s,setPermissionMode:i}){t([]),n([]),e.current=null,i("standard"),r(crypto.randomUUID()),o(!1),s(!1)}function physicalLineCount(e,t){const n=t>0?t:80,r=e.split("\n");let o=0;for(const e of r){const t=st(e);o+=0===t?1:Math.ceil(t/n)}return o}function createPhysicalLogUpdate(e,t){let n="";const r=__name(r=>{const o=`${r}\n`;if(o===n)return;const s=t.getCols(),i=n.length>0?ot.eraseLines(physicalLineCount(n,s)):"";e.write(i+o),n=o},"render");return r.clear=()=>{if(n.length>0){const r=t.getCols();e.write(ot.eraseLines(physicalLineCount(n,r)))}n=""},r.sync=e=>{n=`${e}\n`},r.done=()=>{n=""},r}Jr(),ao(),Ot(),xE(),Eb(),Ot(),wn(),Of(),sS(),fS(),qr(),__name(copyOrFallback,"copyOrFallback"),__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),Ot(),__name(getContextEngineCallbacks,"getContextEngineCallbacks"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),kb(),Ot(),Sb(),Ot(),Sb(),Ot(),__name(physicalLineCount,"physicalLineCount"),__name(createPhysicalLogUpdate,"createPhysicalLogUpdate");var mT=null,pT=null,gT=null,hT=!1;async function resolveInkInstance(e){try{const n=rt(import.meta.url).resolve("ink"),r=t.join(t.dirname(n),"instances.js"),o=await import(m(r).href);return o.default?.get(e)}catch{return}}function warnPatchSkipped(e){hb.custom("INK_LOG_PATCH_SKIPPED",{reason:e}),hT||(hT=!0)}function registerInkControl(e){if(mT=e.clear,pT=e.stdout,!(gT=e.instance??null))return void warnPatchSkipped("no-instance");const t=gT.options?.stdout;if(!t)return void warnPatchSkipped("no-options.stdout");if("function"!=typeof gT.log||"function"!=typeof gT.throttledLog)return void warnPatchSkipped("log-shape-unexpected");const n=createPhysicalLogUpdate(t,{getCols:__name(()=>t.columns??80,"getCols")});gT.log=n,gT.throttledLog=n,hb.custom("INK_LOG_PATCHED",{})}function hardResetForResize(){if(pT)try{pT.write(ot.clearTerminal),mT?.(),gT&&(gT.lastOutput="",gT.fullStaticOutput=""),hb.custom("HARD_RESET",{clear:null!==mT,internals:null!==gT})}catch(e){hb.custom("HARD_RESET_ERROR",{message:e?.message??String(e)})}else hb.custom("HARD_RESET_SKIPPED",{reason:"no-stdout"})}function createResizeHandler(e){let t=e.getColumns();return()=>{const n=e.getColumns();e.isLearningFeedActive()?hb.resize({from:t,to:n,handler:"use-startup",skipped:!0}):n!==t?(hb.resize({from:t,to:n,handler:"use-startup"}),t=n,hardResetForResize(),e.bumpStaticKey()):hb.custom("RESIZE_NOOP",{width:n})}}async function submitInitialPrompt({initialPrompt:e,onCommand:t,submitAsUserMessage:n}){const r=e.trim();r.startsWith("/")&&t&&"handled"===(await t(r)).status||await n()}function useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:o,stdout:s,feedState:i,sessionState:a,statusState:l,authState:u,onboarding:d,uiOverlays:m,permissionState:g,contextEngineRef:h,isSubmittingRef:f,initialPromptSubmittedRef:y,historyManagerRef:w,executeBash:S,createContextEngineCallbacks:E,setInput:C,onCommand:v}){const k=ee(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningEnabled(e),e&&await dT.initializeProject()}catch{}},[l.setTasteLearningEnabled]),T=ee(async()=>{const e=await getConfiguredProvider();u.setCurrentProvider(e);const t=await isOAuthEnforced();u.setIsOAuthMode(t)},[u.setCurrentProvider,u.setIsOAuthMode]),_=ee(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),x=ee(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:a.sessionLoadIdRef,contextEngineRef:h,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,setSessionId:a.setSessionId,setShowSessionSelector:m.setShowSessionSelector,setSessionLoaded:a.setSessionLoaded,permissionModeRef:g.permissionModeRef,setStaticKey:m.setStaticKey,setShareInfo:l.setShareInfo,createContextEngineCallbacks:E})},[a,i,m,g,l,h,E]),A=ee(async()=>{if(n){const e=await ok.listSessions();return void(e.length>0&&x(e[0].id))}t?x(t):e&&m.setShowSessionSelector(!0)},[n,t,e,x,m]);X(()=>{(async()=>{await ok.isProjectInitialized()?(d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await A()):r?(await ok.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await A()):isDirectoryEmpty()?(await ok.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_()):(d.setShowTrustPrompt(!0),d.setCheckingProject(!1))})()},[e,n,r]),X(()=>{if(!d.projectTrusted)return;const e=createHistoryManager();return w.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted]);const P=J(m.showLearningFeed);P.current=m.showLearningFeed,X(()=>{if(!s)return;const e=createResizeHandler({getColumns:__name(()=>s.columns??0,"getColumns"),isLearningFeedActive:__name(()=>P.current,"isLearningFeedActive"),bumpStaticKey:__name(()=>m.setStaticKey(e=>e+1),"bumpStaticKey")});return s.prependListener("resize",e),()=>{s.off("resize",e)}},[s]),X(()=>{o&&d.projectTrusted&&!d.checkingProject&&h.current&&!m.showSessionSelector&&!y.current&&(y.current=!0,submitInitialPrompt({initialPrompt:o,onCommand:v,submitAsUserMessage:__name(()=>handleSubmit({role:"user",input:o,feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:u.currentModel,premiumCreditsExhausted:u.premiumCreditsExhausted,setPremiumCreditsExhausted:u.setPremiumCreditsExhausted,setCurrentModel:u.setCurrentModel,contextEngineRef:h,isSubmittingRef:f,setInput:C,setStaticKey:m.setStaticKey,executeBash:S}),"submitAsUserMessage")}))},[o,d.projectTrusted,d.checkingProject,m.showSessionSelector,v]);const I=J(null);I.current={feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,currentModel:u.currentModel,premiumCreditsExhausted:u.premiumCreditsExhausted,setPremiumCreditsExhausted:u.setPremiumCreditsExhausted,setCurrentModel:u.setCurrentModel,contextEngineRef:h,isSubmittingRef:f,setInput:C,setStaticKey:m.setStaticKey,executeBash:S,role:"",input:""};const N=ee(async({role:e,input:t,images:n,ideContext:r,ideHint:o,displayMessage:s,isAutomated:i})=>(m.setShowTasteSkipBanner(!1),handleSubmit({...I.current,role:e,input:t,images:n,ideContext:r,ideHint:o,displayMessage:s,isAutomated:i})),[]);return{loadTasteStatus:k,loadCurrentProvider:T,initializeMcpInBackground:_,onSubmit:N}}__name(resolveInkInstance,"resolveInkInstance"),__name(warnPatchSkipped,"warnPatchSkipped"),__name(registerInkControl,"registerInkControl"),__name(hardResetForResize,"hardResetForResize"),__name(createResizeHandler,"createResizeHandler"),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ot(),Wn(),xE(),Hn(),Ot(),wn(),Kn(),Ot();var fT={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return fT[e]||e}function getProjectDirName2(e){return e.replace(/\//g,"-")}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName2,"getProjectDirName"),Ot(),Kn();var yT=e.join(w.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=H(e,{encoding:"utf8"}),n=it.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 v.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const o=await v.readdir(t);for(const s of o){if(!/^\d{4}$/.test(s))continue;const o=e.join(t,s);if(!(await v.stat(o)).isDirectory())continue;const i=await v.readdir(o);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(o,t);if(!(await v.stat(i)).isDirectory())continue;const a=await v.readdir(i);for(const o of a){if(!/^\d{2}$/.test(o))continue;const a=e.join(i,o);if(!(await v.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${s}/${t}/${o}`});const l=(await v.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(a,t));r.push(...l)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const i=e.slice(s,s+n),a=await Promise.all(i.map(t));for(const e of a)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 i=await findAllSessionFiles(yT,n);if(0===i.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${i.length} session files to scan`),n?.({phase:"reading",totalFiles:i.length,processedFiles:0,matchedSessions:0});let a=0;const l=await processFilesInBatches(i,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===o)try{const r=await v.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)=>{a=s.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:a})});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:i.length,processedFiles:i.length,matchedSessions:u.length}),u.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await v.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}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),Ot(),Kn();var wT=e.join(w.homedir(),".cursor","projects");function getCursorProjectDirNames(e){const t=e.replace(/[/\\:]/g,"-"),n=t.replace(/^-+/,"");return[...new Set([n,t])].filter(Boolean)}async function findAgentTranscriptsDir(t){try{await v.access(wT)}catch{return dlog("[Cursor] projects directory not found"),null}const n=getCursorProjectDirNames(t);dlog(`[Cursor] looking for project dirs: ${n.join(", ")}`);try{const t=await v.readdir(wT);for(const r of n){if(!t.includes(r))continue;const n=e.join(wT,r,"agent-transcripts");try{if((await v.stat(n)).isDirectory())return dlog(`[Cursor] found agent-transcripts at: ${n}`),n}catch{}}}catch(e){dlog("[Cursor] error scanning projects",e)}return null}async function findCursorSessions(t,n=0){const r=t||process.cwd(),o=[];dlog(`[Cursor] scanning for project: ${r}`);const s=await findAgentTranscriptsDir(r);if(!s)return dlog("[Cursor] no agent-transcripts found"),[];try{const t=await v.readdir(s);for(const n of t){const t=e.join(s,n);try{if(!(await v.stat(t)).isDirectory())continue;const r=e.join(t,`${n}.jsonl`);try{const e=await v.stat(r);o.push({id:n,filePath:r,createdAt:e.birthtime,lastModified:e.mtime,messageCount:0,agent:"cursor"})}catch{}}catch{}}}catch(e){dlog("[Cursor] error reading agent-transcripts",e)}const i=o.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime()),a=n>0?i.slice(0,n):i;return dlog(`[Cursor] matched ${a.length} sessions for project`),a}async function findCursorSessionIds(e){return(await findCursorSessions(e)).map(e=>e.id)}async function extractCursorPrompts(e){const t=[];try{const n=(await v.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"!==n.role)continue;const r=n.message?.content;if(!Array.isArray(r))continue;for(const e of r)if("text"===e.type&&"string"==typeof e.text){const n=e.text.trim().replace(/^<user_query>\n?/,"").replace(/\n?<\/user_query>$/,"").trim();n&&t.push(n)}}catch{continue}t.length>0&&dlog(`[Cursor] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Cursor] 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;if(e?.newTasteLearningsBannerDismissedForever)return dlog("[Onboarding] dismissed forever for this project, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[]};const t=e?.learnedSessions||{},n=e?.skippedSessions||{},r={};for(const e of new Set([...Object.keys(t),...Object.keys(n)]))r[e]=[...t[e]||[],...n[e]||[]];const o=await findNewSessions(r),s=o["claude-code"]?.length||0,i=s+(o.codex?.length||0)+(o.cursor?.length||0);return i>0?(dlog(`[Onboarding] found ${i} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:i,hasTasteContent:!0,agentSessions:buildAgentSessionsList(o)}):(isOnboardingDone(e)?dlog(`[Onboarding] ${e?.skipped?"user skipped":"already completed"}, no new sessions`):dlog("[Onboarding] no sessions to learn from, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:isOnboardingDone(e),agentSessions:[]})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[]}}}async function getSessionFilesFromDir(e){try{return(await v.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||[],s=t.cursor||[];try{const t=e.join(w.homedir(),".claude","projects");await v.access(t);const o=getProjectDirName2(process.cwd()),s=(await v.readdir(t)).filter(e=>e===o);for(const o of s){const s=e.join(t,o);if((await v.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")}try{const e=await findCursorSessionIds();e.length>0&&(n.cursor=e.filter(e=>!s.includes(e)));dlog(`[Sessions] cursor: ${n.cursor?.length||0} new, ${s.length} learned`)}catch{dlog("[Sessions] cursor sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];if(n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.skippedSessions?.[e]){const r=new Set(t);n.tasteOnboarding.skippedSessions[e]=n.tasteOnboarding.skippedSessions[e].filter(e=>!r.has(e)),0===n.tasteOnboarding.skippedSessions[e].length&&delete n.tasteOnboarding.skippedSessions[e]}n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0;try{const t=e.tasteOnboarding.learnedSessions||{},n=await findNewSessions(t);e.tasteOnboarding.skippedSessions||(e.tasteOnboarding.skippedSessions={});for(const[t,r]of Object.entries(n))if(r.length>0){const n=e.tasteOnboarding.skippedSessions[t]||[];e.tasteOnboarding.skippedSessions[t]=Array.from(new Set([...n,...r]))}}catch{dlog("[Onboarding] failed to record skipped sessions, skip flag still set")}await saveProjectSettings(e)}async function dismissOnboardingForeverForProject(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.newTasteLearningsBannerDismissedForever=!0,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 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")}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:o,onboarding:s,uiOverlays:i,skipOnboarding:a,contextEngineRef:l,sessionTitleHolder:u}){X(()=>{if(!n.shouldExit)return;r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current);const t=l.current?.getSessionManager();u&&t&&(u.loadTitle=()=>t.loadUserRenamedTitle());try{e()}catch{process.exit(0)}},[n.shouldExit,e]),X(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),o.providerNotificationTimer.current&&clearTimeout(o.providerNotificationTimer.current),o.modelNotificationTimer.current&&clearTimeout(o.modelNotificationTimer.current)},[]),X(()=>{(async()=>{if("anthropic"===o.currentProvider&&o.isOAuthMode)try{await On.getValidAccessToken()||r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}catch{r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[o.currentProvider,o.isOAuthMode]),X(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(SE())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),X(()=>{a||triggerTasteOnboarding({projectTrusted:s.projectTrusted,onboardingComplete:s.onboardingComplete,isOnboardingMode:s.showTasteOnboarding,tasteOnboardingCheckedRef:s.tasteOnboardingCheckedRef,setIsOnboardingMode:s.setShowTasteOnboarding})},[s.projectTrusted,s.onboardingComplete,s.showTasteOnboarding,a]),X(()=>{if(s.showTasteOnboarding&&!s.tasteOnboardingEntryId){const e=uE();s.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!s.showTasteOnboarding&&s.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==s.tasteOnboardingEntryId)),s.setTasteOnboardingEntryId(null))},[s.showTasteOnboarding,s.tasteOnboardingEntryId])}__name(getCursorProjectDirNames,"getCursorProjectDirNames"),__name(findAgentTranscriptsDir,"findAgentTranscriptsDir"),__name(findCursorSessions,"findCursorSessions"),__name(findCursorSessionIds,"findCursorSessionIds"),__name(extractCursorPrompts,"extractCursorPrompts"),__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(dismissOnboardingForeverForProject,"dismissOnboardingForeverForProject"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),__name(useLifecycle,"useLifecycle"),Ot(),xE(),Ot(),Bn(),ao(),Eb(),wn(),Ot();var ST="└",ET="│",bT=" ",CT=`${bT}TASTE${bT}`;function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:o,showMcpManager:s,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showUsageOverlay:u,showAddDirModal:d,authComponentInfo:m,setShowLearningFeed:g,setShowModelSelector:h,setStaticKey:f,showTasteSkipBanner:y,setShowTasteSkipBanner:w,transcriptMode:S,setTranscriptMode:E,isCmdCodeBusy:C,liveEntries:v,queuedMessagesRef:k,setInput:T,setQueuedMessages:_,setFeed:x,setLiveEntries:A,setIsCmdCodeBusy:P,setRetryAttempt:I,setStatus:N,pendingExitKey:R,setPendingExitKey:M,pendingExitKeyRef:L,lastExitKeyTimeRef:$,exitConfirmationTimeoutRef:D,resetPendingExitKey:O,pendingPermission:F,setPendingPermission:q,pendingQuestion:j,setPendingQuestion:U,setShouldExit:B,contextEngineRef:z,handleToggleAutoAccept:H,handleDoubleEscapeEmpty:W,respondToPrompt:G,createErrorEntry:V}){const Q=__name(()=>{if(!z.current)return;z.current.interrupt(!0);const e=v.length>0;if(P(!1),I(null),A([]),N("Interrupted by user"),!e){const e=V("Interrupted by user");x(t=>[...t,e])}if(k.current.length>0){const e=k.current.map(e=>e.displayMessage??e.input).join("\n");T(t=>t?e+"\n"+t:e),_([]),k.current=[]}},"handleInterrupt");se((v,k)=>{if(k.shift&&k.tab||"[Z"===v)H();else if(y&&k.escape)w(!1);else if(e||t||n||r||o||s||m||i||a||l||u||d)R&&O();else{if(""===v||k.ctrl&&"c"===v){if(C&&z.current)return void Q();const e=Date.now(),t=e-$.current;return $.current=e,"ctrl-c"===L.current&&t<2e3?(D.current&&(clearTimeout(D.current),D.current=null),void B(!0)):(T(()=>""),L.current="ctrl-c",M("ctrl-c"),D.current&&clearTimeout(D.current),void(D.current=setTimeout(()=>{L.current=null,M(null),D.current=null},2e3)))}if(k.ctrl&&"t"===v)return wb(),g(!i),void f(e=>e+1);if(getIsExpandToolShortcut(k,v))return wb(),E("off"===S?"limited":"off"),void f(e=>e+1);if(k.ctrl&&"e"===v&&"off"!==S)return wb(),E("limited"===S?"full":"limited"),void f(e=>e+1);if(k.meta&&"p"===v||isAltP(v))h(!0);else if(k.escape){if(j)return j.reject(new Error("Question cancelled by user")),U(null),void N("Question cancelled");if(F)return G({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),F.resolve(!1),q(null),void N("Permission denied");C&&z.current&&Q()}}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:o,pendingOps:s,permissionState:i,statusState:a,authState:l,contextEngineRef:u,loadTasteStatus:d,loadCurrentProvider:m,setInput:g}){const h=ee(()=>{i.setPermissionMode(e=>{const t=i.dangerouslySkipPermissions;let n="standard";if("standard"===e?n="auto-accept":"auto-accept"===e?n="plan":"plan"===e&&t&&(n="bypass"),("auto-accept"===n||"bypass"===n)&&s.pendingPermission){const e={label:"Yes",value:"yes",description:"Allow this action",scope:void 0};i.respondToPrompt(e),s.pendingPermission.resolve(!0),s.setPendingPermission(null)}return"plan"===n&&s.pendingPermission&&(s.pendingPermission.resolve(!1),s.setPendingPermission(null)),n})},[i.setPermissionMode,i.respondToPrompt,i.dangerouslySkipPermissions,s.pendingPermission,s.setPendingPermission]),f=ee(()=>{const e=!t.isCmdCodeBusy&&!s.pendingPermission&&!s.pendingQuestion,n=u.current?.hasCheckpoints()??!1;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,s.pendingPermission,s.pendingQuestion,r.setShowRewindSelector]),y=ee(t=>{n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),t?.skipped&&r.setShowTasteSkipBanner(!0),e&&r.setShowSessionSelector(!0)},[e,n,r]),w=ee(async()=>{try{if(await ok.initializeProject(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void o.setShouldExit(!0);n.setProjectTrusted(!0),d(),m()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),o.setShouldExit(!0)}},[e,n,o,d,m]),S=ee(()=>{o.setShouldExit(!0)},[o.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showLearningFeed:r.showLearningFeed,showRewindSelector:r.showRewindSelector,showLoginOverlay:r.showLoginOverlay,showUsageOverlay:r.showUsageOverlay,showAddDirModal:r.showAddDirModal,authComponentInfo:l.authComponentInfo,setShowLearningFeed:r.setShowLearningFeed,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,showTasteSkipBanner:r.showTasteSkipBanner,setShowTasteSkipBanner:r.setShowTasteSkipBanner,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveEntries:t.liveEntries,queuedMessagesRef:t.queuedMessagesRef,setInput:g,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:o.pendingExitKey,setPendingExitKey:o.setPendingExitKey,pendingExitKeyRef:o.pendingExitKeyRef,lastExitKeyTimeRef:o.lastExitKeyTimeRef,exitConfirmationTimeoutRef:o.exitConfirmationTimeoutRef,resetPendingExitKey:o.resetPendingExitKey,pendingPermission:s.pendingPermission,setPendingPermission:s.setPendingPermission,pendingQuestion:s.pendingQuestion,setPendingQuestion:s.setPendingQuestion,setShouldExit:o.setShouldExit,contextEngineRef:u,handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,respondToPrompt:i.respondToPrompt,createErrorEntry:cE}),{handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,handleTasteOnboardingComplete:y,handleTrust:w,handleNoTrust:S}}function lastResponseHasComments(e){const t=e[e.length-1];if(!t||"assistant"!==t.message.role)return!1;const{content:n}=t.message;if("string"==typeof n)return n.includes("## Review Comments")||n.includes("## PR Comments");const r=n.filter(e=>"text"===e.type).map(e=>e.text).join("");return r.includes("## Review Comments")||r.includes("## PR Comments")}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 i=t[e];'"'!==i&&"'"!==i||o?i===s&&o?(o=!1,s=""):" "!==i||o?r+=i:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=i)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const 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(S.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,o=""){if($.existsSync(n))try{const s=$.readdirSync(n,{withFileTypes:!0});for(const i of s){const s=t.join(n,i.name);if(i.isDirectory())loadCommandsFromDirectory(s,r,o?`${o}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".md")){const n=t.basename(i.name,".md"),a=$.readFileSync(s,"utf-8").trim();e.push({name:n,source:r,content:a,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}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ot(),Ot(),wn(),Ot(),__name(lastResponseHasComments,"lastResponseHasComments"),xE(),Eb(),Ot(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),Ot(),wn(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),Ot(),Ot(),Ot(),wn(),Kn(),lo(),Co(),Ot(),wn();var vT=t.join(S.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(vT);$.existsSync(e)||$.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!$.existsSync(vT))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=$.readFileSync(vT,"utf-8");return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null,...JSON.parse(e)}}catch{return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}}}function writeUpdatesConfig(e){ensureDir(),$.writeFileSync(vT,JSON.stringify(e,null,2))}function updateUpdatesConfig(e){writeUpdatesConfig({...readUpdatesConfig(),...e})}function shouldCheckForUpdate(){const e=readUpdatesConfig();return!!e.autoUpdate&&Date.now()-e.lastCheckedAt>=e.checkIntervalMs}function recordUpdateCheck(){updateUpdatesConfig({lastCheckedAt:Date.now()})}function setPendingUpdate(e){updateUpdatesConfig({lastCheckedAt:Date.now(),pending:e})}function clearPendingUpdate(){updateUpdatesConfig({pending:null})}function getPendingUpdate(e){const t=readUpdatesConfig();return t.pending?t.pending.currentVersion!==e?(clearPendingUpdate(),null):t.pending:null}__name(function getDefaultConfig(){return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}},"getDefaultConfig"),__name(ensureDir,"ensureDir"),__name(readUpdatesConfig,"readUpdatesConfig"),__name(writeUpdatesConfig,"writeUpdatesConfig"),__name(updateUpdatesConfig,"updateUpdatesConfig"),__name(shouldCheckForUpdate,"shouldCheckForUpdate"),__name(recordUpdateCheck,"recordUpdateCheck"),__name(setPendingUpdate,"setPendingUpdate"),__name(clearPendingUpdate,"clearPendingUpdate"),__name(getPendingUpdate,"getPendingUpdate"),GE(),lo();var kT=lt(Ee),TT=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!process.env.COMMANDCODE_SKIP_UPDATES||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=Se("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1"}});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return TT.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(ct.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&ct.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&ct.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 kT(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;const n=await checkForUpdateAvailable(),r=n?.latestVersion??t.targetVersion;if(!ct.gt(r,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${r}`);const o=Re(`Updating ${e} → ${r}`).start(),s=await executeUpdate(r);if(clearPendingUpdate(),!s)return o.fail("Update failed"),void console.log("Run `cmd update` to try again.");o.succeed(`Updated to v${r}`),trackLifecycleEvent({eventType:"cli_updated",metadata:{fromVersion:e,toVersion:r}}).catch(()=>{})}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 Se("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 _T=new Set(["OPEN","MERGED","CLOSED"]),xT=null;function getCachedPRInfo(e){if(xT&&xT.branch===e){if(!(Date.now()-xT.timestamp>3e5))return xT.result;xT=null}}function setPRCache(e,t){xT={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((o,s)=>{ve(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&&_T.has(t.state)?{number:t.number,title:t.title||"",url:t.url,state:t.state}:null}catch{return null}}function getCachedPR(e){return e?getCachedPRInfo(e)??null:null}__name(getCachedPRInfo,"getCachedPRInfo"),__name(setPRCache,"setPRCache"),__name(execFileAsync,"execFileAsync"),__name(parsePRResponse,"parsePRResponse"),__name(getCachedPR,"getCachedPR");var AT=__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 null}},"detectPR");function decompress(e,t,n){if(0===e)return n;if(8===e)return ut(n);throw new Error(`Unsupported compression method ${e} for ${t}`)}function readZipEntries(e){const t=Math.max(0,e.length-65557);let n=-1;for(let r=e.length-22;r>=t;r--)if(101010256===e.readUInt32LE(r)){n=r;break}if(n<0)throw new Error("Not a ZIP archive (no EOCD)");const r=e.readUInt32LE(n+12),o=e.readUInt32LE(n+16),s=o+r,i=[];let a=o;for(;a<s&&33639248===e.readUInt32LE(a);){const t=e.readUInt16LE(a+10),n=e.readUInt32LE(a+20),r=e.readUInt16LE(a+28),o=e.readUInt16LE(a+30),s=e.readUInt16LE(a+32),l=e.readUInt32LE(a+42),u=e.toString("utf8",a+46,a+46+r);if(a+=46+r+o+s,u.endsWith("/"))continue;const d=l+30+e.readUInt16LE(l+26)+e.readUInt16LE(l+28),m=e.subarray(d,d+n);i.push({name:u,data:decompress(t,u,m)})}return i}function parseVsixOnce(e){const t=readZipEntries($.readFileSync(e));return{entries:t,meta:readVsixPackageJson(t)}}function readVsixPackageJson(e){const t=e.find(e=>"extension/package.json"===e.name);if(!t)throw new Error("VSIX missing extension/package.json");const n=JSON.parse(t.data.toString("utf8")),r="string"==typeof n.publisher?n.publisher:"",o="string"==typeof n.name?n.name:"",s="string"==typeof n.version?n.version:"";if(!r||!o||!s)throw new Error("VSIX package.json missing publisher/name/version");return{publisher:r,name:o,version:s}}function extractExtensionInto(e,n){const r=t.resolve(n);for(const o of e){if(!o.name.startsWith("extension/"))continue;const e=o.name.slice(10);if(!e)continue;const s=t.resolve(n,e);if(s!==r&&!s.startsWith(r+t.sep))throw new Error(`Refusing to extract entry outside destDir: ${o.name}`);$.mkdirSync(t.dirname(s),{recursive:!0}),$.writeFileSync(s,o.data)}}Ot(),Kn(),Jr(),Ot(),Kn(),Ot(),__name(decompress,"decompress"),__name(readZipEntries,"readZipEntries"),__name(parseVsixOnce,"parseVsixOnce"),__name(readVsixPackageJson,"readVsixPackageJson"),__name(extractExtensionInto,"extractExtensionInto");var PT={code:"Visual Studio Code",cursor:"Cursor",windsurf:"Windsurf"},IT={code:".vscode",cursor:".cursor",windsurf:".windsurf"},NT=["cursor","code","windsurf"];function getVsixPath(){try{const e=t.dirname(d(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return $.existsSync(n)?n:null}catch{return null}}function getIDEExtensionsDir(e){return t.join(S.homedir(),IT[e],"extensions")}__name(getVsixPath,"getVsixPath"),__name(getIDEExtensionsDir,"getIDEExtensionsDir");var RT={code:"Visual Studio Code.app",cursor:"Cursor.app",windsurf:"Windsurf.app"};function getMacAppBundle(e){if("darwin"!==process.platform)return null;const n=[t.join("/Applications",RT[e]),t.join(S.homedir(),"Applications",RT[e])];for(const e of n)try{if($.existsSync(e))return e}catch{}return null}function getInstalledIDEs(){return NT.filter(e=>{if("darwin"===process.platform)return null!==getMacAppBundle(e);try{return $.existsSync(t.join(S.homedir(),IT[e]))}catch{return!1}})}function formatInstallError(e,t){const n=PT[t],r=e??{},o="string"==typeof r.code?r.code:"",s="string"==typeof r.message?r.message:String(e);return"EACCES"===o||"EPERM"===o?`${n}: permission denied writing to ${getIDEExtensionsDir(t)}. Check directory ownership/permissions.`:"ENOSPC"===o?`${n}: not enough disk space to extract the extension.`:"EROFS"===o?`${n}: ${getIDEExtensionsDir(t)} is on a read-only filesystem.`:"EBUSY"===o?`${n}: extensions directory is locked by another process. Close ${n} and retry.`:"ENOENT"===o?`${n}: required path not found (${s}).`:s.includes("Not a ZIP archive")||s.includes("Unsupported compression")?`${n}: bundled VSIX appears corrupt (${s}). Reinstall Command Code.`:`${n}: ${s}`}function verifyOnDisk(e,n){try{const r=getIDEExtensionsDir(e),o=`${n.publisher}.${n.name}-${n.version}`,s=t.join(r,o,"package.json");if(!$.existsSync(s))return!1;JSON.parse($.readFileSync(s,"utf-8"));const i=t.join(r,"extensions.json");if(!$.existsSync(i))return!1;const a=JSON.parse($.readFileSync(i,"utf-8"));if(!Array.isArray(a))return!1;const l=`${n.publisher}.${n.name}`;return a.some(e=>{const t=e;return"string"==typeof t?.identifier?.id&&t.identifier.id===l&&t.version===n.version})}catch{return!1}}function buildManifestEntry(e,n,r){const o=t.join(e,n),s=m(o).href,i=o.split(t.sep).join("/");return{identifier:{id:`${r.publisher}.${r.name}`},version:r.version,location:{$mid:1,fsPath:o,external:s,path:i.startsWith("/")?i:"/"+i,scheme:"file"},relativeLocation:n,metadata:{installedTimestamp:Date.now(),source:"vsix"}}}function upsertManifestEntry(e,n){const r=t.join(e,"extensions.json");let o=[];try{if($.existsSync(r)){const e=$.readFileSync(r,"utf-8"),t=JSON.parse(e);Array.isArray(t)&&(o=t)}}catch(e){dlog(`[IDE] extensions.json unreadable, rewriting: ${e instanceof Error?e.message:String(e)}`)}o=o.filter(e=>e?.identifier?.id!==n.identifier.id),o.push(n);const s=`${r}.tmp.${process.pid}`;$.writeFileSync(s,JSON.stringify(o,null,"\t")),$.renameSync(s,r)}function directInstallExtension(e,n,r){try{const{entries:o,meta:s}=r??parseVsixOnce(n);if(verifyOnDisk(e,s))return dlog(`[IDE] direct-install ${e}: fast-path skip (${s.publisher}.${s.name}@${s.version})`),{ide:e,status:"already_installed"};const i=getIDEExtensionsDir(e);$.mkdirSync(i,{recursive:!0});const a=`${s.publisher}.${s.name}-${s.version}`,l=t.join(i,a),u=$.existsSync(t.join(l,"package.json"));if(!u){const e=t.join(i,`.commandcode-install-${process.pid}-${Date.now()}`);$.rmSync(e,{recursive:!0,force:!0}),$.mkdirSync(e,{recursive:!0});try{extractExtensionInto(o,e),$.rmSync(l,{recursive:!0,force:!0}),$.renameSync(e,l)}catch(t){throw $.rmSync(e,{recursive:!0,force:!0}),t}}if(upsertManifestEntry(i,buildManifestEntry(i,a,s)),!verifyOnDisk(e,s)){const t="post-install verification failed (extension folder or manifest entry missing)";return dlog(`[IDE] direct-install ${e} verification failed`),{ide:e,status:"failed",error:`${PT[e]}: ${t}`}}return dlog(`[IDE] direct-install ${e}: ${u?"already_installed":"installed"} (${s.publisher}.${s.name}@${s.version})`),{ide:e,status:u?"already_installed":"installed"}}catch(t){const n=formatInstallError(t,e);return dlog(`[IDE] direct-install ${e} failed: ${t instanceof Error?t.message:String(t)}`),{ide:e,status:"failed",error:n}}}function installToAllIDEs(e,t={}){const n=new Set(getInstalledIDEs());t.alwaysInclude&&n.add(t.alwaysInclude);const r=[...n];if(0===r.length)return[];let o;try{o=parseVsixOnce(e)}catch(e){return dlog(`[IDE] VSIX parse failed: ${e instanceof Error?e.message:String(e)}`),r.map(t=>({ide:t,status:"failed",error:formatInstallError(e,t)}))}return r.map(t=>directInstallExtension(t,e,o))}function getStatusHeadline(e,t){return"connected"===e?{prefix:"Connected to ",ide:t,suffix:""}:"installed"===e?{prefix:"IDE extension installed in ",ide:t,suffix:""}:"up_to_date"===e?{prefix:"IDE extension up to date in ",ide:t,suffix:""}:"needs_reload"===e?{prefix:"IDE extension installed — reload ",ide:t,suffix:"'s window to activate"}:"failed"===e?t?{prefix:"",ide:t,suffix:" extension install failed"}:{prefix:"Extension install failed",ide:null,suffix:""}:{prefix:"No supported IDE detected",ide:null,suffix:""}}__name(getMacAppBundle,"getMacAppBundle"),__name(getInstalledIDEs,"getInstalledIDEs"),__name(formatInstallError,"formatInstallError"),__name(verifyOnDisk,"verifyOnDisk"),__name(buildManifestEntry,"buildManifestEntry"),__name(upsertManifestEntry,"upsertManifestEntry"),__name(directInstallExtension,"directInstallExtension"),__name(installToAllIDEs,"installToAllIDEs"),Ot(),__name(getStatusHeadline,"getStatusHeadline");var MT={connected:ce.green("✔"),installed:ce.green("✔"),up_to_date:ce.green("✔"),needs_reload:ce.yellow("◌"),failed:ce.red("✖"),not_in_ide:ce.yellow("◌")};function formatSetupResult(e){const{prefix:t,ide:n,suffix:r}=getStatusHeadline(e.status,e.ide),o=`${t}${n??""}${r}`;return["",`${MT[e.status]} ${o}`,...(e.details??[]).map(e=>ce.dim(` ${e}`)),""]}__name(formatSetupResult,"formatSetupResult");var LT=PT;async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}async function ensureExtensionInstalled(){if(process.env.CI)return;const e=vv();if(!e)return;if(!await isAutoInstallEnabled())return;const t=getVsixPath();if(t)try{const n=installToAllIDEs(t,{alwaysInclude:e});for(const e of n)"failed"===e.status&&dlog(`[IDE] auto-install failed for ${e.ide}: ${e.error??"unknown"}`)}catch(e){dlog(`[IDE] auto-install threw: ${e instanceof Error?e.message:String(e)}`)}else dlog("[IDE] auto-install skipped: VSIX bundle missing")}__name(isAutoInstallEnabled,"isAutoInstallEnabled"),__name(ensureExtensionInstalled,"ensureExtensionInstalled");var $T="Select code in your IDE and it's automatically included in your prompt: no copy-paste needed.";async function runIDESetup(){const e=getVsixPath();if(!e)return{status:"failed",ide:null,details:["VSIX bundle missing from this build.","Reinstall Command Code or send feedback with /feedback"]};const t=vv(),n=installToAllIDEs(e,{alwaysInclude:t??void 0});if(0===n.length)return{status:"not_in_ide",ide:null,details:["Install Visual Studio Code, Cursor, or Windsurf, then run /ide again."]};const r=n.filter(e=>"failed"!==e.status),o=n.filter(e=>"failed"===e.status);if(0===r.length)return{status:"failed",ide:o.map(e=>PT[e.ide]).join(", "),details:[...o.map(e=>e.error??`${PT[e.ide]}: unknown error`),"","Run /ide to retry the installation. Report the issue with /feedback including the error messages above."]};const s=r.map(e=>PT[e.ide]).join(", "),i=r.filter(e=>"installed"===e.status),a=r.filter(e=>"already_installed"===e.status),l=i.map(e=>PT[e.ide]).join(", "),u=a.map(e=>PT[e.ide]).join(", "),d=o.map(e=>`Note: ${e.error??`install failed for ${PT[e.ide]}`}`);if(t){const e=o.filter(e=>e.ide===t).map(e=>`Note: ${e.error??`install failed for ${PT[e.ide]}`}`),n=new Mv,r=await n.connect(500);n.disconnect();const s=LT[t]||t;if(r)return{status:"connected",ide:s,details:[$T,...e.length>0?["",...e]:[]]};const i="darwin"===process.platform?"Cmd+Shift+P":"Ctrl+Shift+P";return{status:"needs_reload",ide:s,details:[$T,"",`${i} → Developer: Reload Window in ${s}, then re-run /ide to verify.`,...e.length>0?["",...e]:[]]}}const m="Run /ide from inside the IDE's terminal to verify the connection.";if(0===i.length)return{status:"up_to_date",ide:s,details:[$T,"",m,...d.length>0?["",...d]:[]]};const g=a.length>0?`Already up to date in ${u}.`:null;return{status:"installed",ide:l,details:[$T,"",m,...g?[g]:[],...d.length>0?["",...d]:[]]}}__name(runIDESetup,"runIDESetup"),ro(),io(),Ot();var DT='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets.';function buildReviewPrompt({prNumber:e,autoDetected:t=!1}){const n=e.trim();return n?`${DT}\n\nReview PR number: ${n}${t?"\n(Note: PR number auto-detected from current branch.)":""}`:`${DT}\n\nReview PR number: `}__name(buildReviewPrompt,"buildReviewPrompt"),Ot(),Ot(),ao(),Rr();var OT=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),FT=__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"),qT=__name(({icon:e,label:t,children:n})=>Q.createElement(ne,null,Q.createElement(ne,{color:ar.CYAN},e," "),Q.createElement(ne,{color:ar.DIM},t.padEnd(12)),n),"Row"),jT=__name(({title:e})=>Q.createElement(ne,null,Q.createElement(ne,{color:ar.GRAY},"───"),Q.createElement(ne,{color:ar.WHITE}," ",e," "),Q.createElement(ne,{color:ar.GRAY},"─".repeat(35))),"Header"),UT=__name(({title:e,marginTop:t=0,children:n})=>Q.createElement(te,{flexDirection:"column",marginTop:t},Q.createElement(jT,{title:e}),Q.createElement(te,{flexDirection:"column",paddingY:1},n)),"Section"),BT=__name(({cpuCount:e,totalMem:t,systemInfo:n})=>Q.createElement(UT,{title:"System Information"},Q.createElement(qT,{icon:Pe.bullet,label:"Version"},Q.createElement(ne,{color:ar.GREEN},n.version)),Q.createElement(qT,{icon:Pe.bullet,label:"Date"},Q.createElement(ne,null,formatDate())),Q.createElement(qT,{icon:Pe.pointer,label:"Platform"},Q.createElement(ne,{color:ar.GREEN},n.os),Q.createElement(ne,{color:ar.DIM}," ","(",w.platform(),", ",w.arch(),")")),Q.createElement(qT,{icon:Pe.triangleUp,label:"Hostname"},Q.createElement(ne,null,w.hostname())),Q.createElement(qT,{icon:Pe.bullet,label:"User"},Q.createElement(ne,{color:ar.YELLOW},w.userInfo().username)),Q.createElement(qT,{icon:Pe.bullet,label:"CPUs"},Q.createElement(ne,{color:ar.MAGENTA},e," cores")),Q.createElement(qT,{icon:Pe.bullet,label:"Memory"},Q.createElement(ne,{color:ar.CYAN},t," GB")),Q.createElement(qT,{icon:Pe.play,label:"Uptime"},Q.createElement(ne,null,FT(w.uptime()))),Q.createElement(qT,{icon:Pe.arrowRight,label:"Home"},Q.createElement(ne,{color:ar.DIM},w.homedir())),Q.createElement(qT,{icon:Pe.pointer,label:"Shell"},Q.createElement(ne,null,n.shell)),Q.createElement(qT,{icon:Pe.bullet,label:"Node"},Q.createElement(ne,{color:ar.GREEN},process.version)),Q.createElement(qT,{icon:Pe.pointer,label:"Terminal"},Q.createElement(ne,{color:ar.CYAN},n.terminal)),Q.createElement(qT,{icon:Pe.bullet,label:"IDE"},Q.createElement(ne,null,n.ide))),"SystemInfoSection"),zT=__name(({cpus:e})=>Q.createElement(UT,{title:"CPU Details",marginTop:1},e.map((e,t)=>Q.createElement(qT,{key:t,icon:Pe.bullet,label:`Core ${t}`},Q.createElement(ne,null,e.model.trim()),Q.createElement(ne,{color:ar.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),HT=__name(({networkInterfaces:e})=>Q.createElement(UT,{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(qT,{key:`${e}-${n}`,icon:Pe.bullet,label:e},Q.createElement(ne,{color:ar.GREEN},t.address))):null})),"NetworkSection"),WT=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r,systemInfo:o})=>Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,null,"System Information"),Q.createElement(ne,null,"─".repeat(40)),Q.createElement(ne,null,"Version ",o.version),Q.createElement(ne,null,"Date ",formatDate()),Q.createElement(ne,null,"Platform ",o.os," (",w.platform(),", ",w.arch(),")"),Q.createElement(ne,null,"Hostname ",w.hostname()),Q.createElement(ne,null,"User ",w.userInfo().username),Q.createElement(ne,null,"CPUs ",e.length," cores"),Q.createElement(ne,null,"Memory ",t," GB"),Q.createElement(ne,null,"Uptime ",FT(w.uptime())),Q.createElement(ne,null,"Home ",w.homedir()),Q.createElement(ne,null,"Shell ",o.shell),Q.createElement(ne,null,"Node ",process.version),Q.createElement(ne,null,"Terminal ",o.terminal),Q.createElement(ne,null,"IDE ",o.ide),r&&Q.createElement(Q.Fragment,null,Q.createElement(ne,null,"\n","CPU Details"),Q.createElement(ne,null,"─".repeat(40)),e.map((e,t)=>Q.createElement(ne,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),Q.createElement(ne,null,"\n","Network"),Q.createElement(ne,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>Q.createElement(ne,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),GT=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r,systemInfo:o})=>Q.createElement(te,{flexDirection:"column"},Q.createElement(BT,{cpuCount:e.length,totalMem:t,systemInfo:o}),r&&Q.createElement(zT,{cpus:e}),r&&Q.createElement(HT,{networkInterfaces:n})),"StyledInfo"),VT=__name(({verbose:e=!1,text:t=!1,systemInfo:n})=>{const{exit:r}=ae();X(()=>{const e=setTimeout(()=>r(),50);return()=>clearTimeout(e)},[r]);const o=w.cpus(),s=w.networkInterfaces(),i=Math.round(w.totalmem()/1024/1024/1024);return t?Q.createElement(WT,{cpus:o,totalMem:i,networkInterfaces:s,verbose:e,systemInfo:n}):Q.createElement(GT,{cpus:o,totalMem:i,networkInterfaces:s,verbose:e,systemInfo:n})},"InfoUI"),QT={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},KT={26:"Tahoe",15:"Sequoia",14:"Sonoma",13:"Ventura",12:"Monterey",11:"Big Sur"},YT=5e3,JT=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),XT=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(JT("__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"),ZT=__name(()=>{const e=XT();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&QT[t]?QT[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),e_=__name(()=>{if("win32"===S.platform()){const e=process.env.COMSPEC;return e?u(e):process.env.SHELL?u(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=Se(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:YT,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=u(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?u(e):"N/A"},"getShellName"),t_=__name(()=>{const e=XT();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),n_=__name(e=>{if(!e)return"macOS";const t=parseInt(e.split(".")[0],10),n=KT[t];return n?`macOS ${n} ${e}`:`macOS ${e}`},"formatMacOSDetail"),r_=__name(()=>{try{const e=Se("sw_vers -productVersion",{encoding:"utf8",timeout:YT,stdio:["ignore","pipe","ignore"]}).trim();return e?n_(e):null}catch{return null}},"getMacOSDetail"),o_=__name(()=>{const e=S.platform();return"darwin"===e?r_()??OT(e):OT(e)},"getDetailedPlatform"),s_=__name(()=>{try{const e=Se("cmd --version",{encoding:"utf8",timeout:YT,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:o_(),terminal:ZT(),shell:e_(),version:s_(),ide:t_()}}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"),Ot();var i_=["Code","Code - Insiders","VSCodium","Cursor"],a_="Code",l_={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},c_=__name(e=>m(e).href,"formatPathForTerminal"),u_=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),d_=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),m_=__name(({home:t,configSegments:n,variants:r})=>{for(const o of r){const r=d_({home:t,configSegments:n,variant:o});if(L.existsSync(e.dirname(r)))return o}return null},"findExistingVariant"),p_=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&g_(t.when)},"isTerminalShiftEnterBinding"),g_=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),h_=__name(e=>{const t=dt(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),f_=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),y_=__name(({error:e,content:t})=>{const n=e.message;return f_(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"),w_=__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"),S_=__name(e=>{try{const t=dt(e),n=w_(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:y_({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),E_=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:c_(t)}),"createSuccessResult"),b_=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:c_(t)}),"createErrorResult"),C_=__name(()=>{const t=w.homedir(),n=w.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=u_(n);if(!r)return d_({home:t,configSegments:[".config"],variant:a_});const o=m_({home:t,configSegments:r,variants:i_});return d_({home:t,configSegments:r,variant:o??a_})},"getVSCodeKeybindingsPath"),v_=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)p_(n)&&(n.command===l_.command&&n.args?.text===l_.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),k_=__name(t=>{try{if(!L.existsSync(t)){const n=e.dirname(t);return L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=L.readFileSync(t,"utf-8");if(h_(n))return{rawContent:n,keybindings:[]};const r=S_(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:b_({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):b_({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return b_({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),T_=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(l_,null,2);if(h_(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return b_({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?b_({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=C_();try{const t=k_(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=v_(r);if(o.hasConflicting)return b_({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return E_({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=T_({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(L.writeFileSync(e,s,"utf-8"),E_({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return b_({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"),Ot(),wn(),Kn(),io(),as(),Rr();var __=(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.RENAME="/rename",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.MCP="/mcp",e.COMPACT="/compact",e.COMPACT_MODE="/compact-mode",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e.ADD_DIR="/add-dir",e.REVIEW="/review",e.PR_COMMENTS="/pr-comments",e.CONTEXT="/context",e.STATUS="/status",e.USAGE="/usage",e.UPGRADE="/upgrade",e.EXTRA="/extra",e.COURSES="/courses",e))(__||{}),x_=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/provider","/model","/memory","/init","/agents","/mcp","/compact","/compact-mode","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/pr-comments","/context","/status","/usage","/upgrade","/extra","/courses"]),A_=new Set(["/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/rename","/provider","/model","/memory","/init","/agents","/mcp","/compact","/compact-mode","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/context","/status","/usage","/upgrade","/extra","/courses"]),P_=[{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:"/compact-mode",description:"Select a compact mode to compact sessions"},{command:"/context",description:"Show context window usage and breakdown"},{command:"/exit",description:"Exit Command Code"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/help",description:"Show available shortcuts"},{command:"/ide",description:qv},{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:"Log in to Command Code"},{command:"/logout",description:"Log out of Command Code"},{command:"/courses",description:"Open Command Code courses in your browser"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/memory",description:"Manage Command Code memory"},{command:"/model",description:"Switch between Command Code models"},{command:"/pr-comments",description:"Fetch all PR comments for current branch"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/rename",description:"Rename the current session"},{command:"/resume",description:"Resume a past conversation"},{command:"/review",description:"Review a pull request (optional PR number)"},{command:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/status",description:"Show comprehensive environment status"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/usage",description:"Display credits, plan, and usage metrics"},{command:"/upgrade",description:"Open billing page to upgrade your plan"},{command:"/extra",description:"Open billing page to buy on-demand credits"}];function shadowedSuffix(e){return` — shadowed by ${e}`}function buildCommandMenuItems(e){const{customMenuItems:t,builtinMenuItems:n,skills:r}=e,o=new Map;for(const e of n)o.set(e.command,"built-in");for(const e of t)o.has(e.command)||o.set(e.command,"custom command");const s=[],i=new Set;for(const e of r){if(i.has(e.name))continue;i.add(e.name);const t=`/${e.name}`,n=o.get(t)?shadowedSuffix(t):"";s.push({command:t,description:`[skill] ${e.description}${n}`})}return[...n,...t,...s]}__name(shadowedSuffix,"shadowedSuffix"),__name(buildCommandMenuItems,"buildCommandMenuItems");var I_=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[o,s]=Y(0),[i,a]=Y(0),[l,u]=Y([]);X(()=>{let e=!1;return loadAllSkillSummaries().then(t=>{e||u(deduplicateSkills(t))}).catch(t=>{e||(dlog("[CommandMenu] Failed to load skills for slash menu",t),u([]))}),()=>{e=!0}},[]);const{stdout:d}=oe(),m=d?.columns??80,g=Math.max(20,m-22-2-1-2),h=Z(()=>{const e=buildCommandMenuItems({customMenuItems:customCommandsToMenuItems(loadCustomCommands()),builtinMenuItems:P_.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal())),skills:l});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,l]),f=Z(()=>{const e=i,t=Math.min(e+8,h.length);return h.slice(e,t)},[h,i]);return X(()=>{s(0),a(0)},[r]),se((r,l)=>{if(l.escape)n();else if(l.upArrow)s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t});else if(l.downArrow)s(e=>{const t=Math.min(h.length-1,e+1);return t>=i+8&&a(Math.max(0,t-8+1)),t});else{if(l.return){const t=h[o];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=h[o];return void(e&&t(e.command))}}}),0===h.length?Q.createElement(te,{flexDirection:"column",paddingLeft:2},Q.createElement(ne,{color:ar.DIM},"No commands found")):(h.length,Q.createElement(te,{flexDirection:"column",paddingLeft:1},Q.createElement(te,{columnGap:2},Q.createElement(te,{flexDirection:"column",width:22},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:n,color:o===n?ar.WHITE:ar.DIM,wrap:"truncate"},e.command)})),Q.createElement(te,{flexDirection:"column"},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:n,color:o===n?ar.WHITE:ar.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:g}))})))))},"CommandMenu");async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=yn();if(await getAuthKey(n)){let t="";try{const e=await loadCredentials();t=e?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}return void e(e=>[...e,oE(formatAlreadyLoggedIn(t))])}t(!0)}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:o,contextEngineRef:s}){if(n(!1),!e)return r(e=>[...e,cE(t)]),void o("Ready...");r(e=>[...e,oE(t)]),s.current&&s.current.refreshRequest(),o("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,oE("Authentication cancelled")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t,setRetryAttempt:n,setIsCmdCodeBusy:r}){let o;try{o=await getUserName()||void 0}catch{o=void 0}const s=await performLogout();if(!s.success)return void e(e=>[...e,cE(formatLogoutFailed(s.error||"Unknown error"))]);if(n(null),r(!1),t.current&&(t.current.interrupt(),t.current.refreshRequest()),!s.wasAuthenticated)return void e(e=>[...e,oE("Not currently authenticated")]);const i=formatLogoutWarnings(s.warnings),a=i?`${formatLogoutSuccess(o)}. ${i}`:formatLogoutSuccess(o);e(e=>[...e,oE(a)])}async function handleCompactCommand({contextEngineRef:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:o,setStaticKey:s}){if(e.current)try{r(!0),n("Compacting conversation...");const i=await e.current.manualCompact();wb(),s(e=>e+1);let a="Compacted conversation.";i.didCompact||(a="Conversation is already compact."),i.didCompact&&i.tokensSaved>0&&(a=`Compacted conversation, saved ~${i.tokensSaved.toLocaleString()} tokens.`),t(e=>[...e,oE(a)]),r(!1),n("Ready..."),o({current:e.current.getContextTokensUsed()||0,limit:getContextLimit(getConfiguredModel())})}catch(e){const o=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,cE(o)]),r(!1),n("Ready...")}else t(e=>[...e,oE("No active conversation to compact.")])}async function handleRenameCommand({name:e,contextEngineRef:t,setFeed:n}){const r=e?.trim();if(!r)return void n(e=>[...e,oE("Usage: /rename [name]")]);const o=t.current?.getSessionManager();if(!o)return void n(e=>[...e,oE("No active session to rename")]);const s=o.getSessionId();await ok.isSessionNameTaken({name:r,excludeSessionId:s})?n(e=>[...e,cE(`A session named "${r}" already exists. Choose a different name.`)]):await o.saveSessionMeta({title:r,userRenamed:!0})?n(e=>[...e,oE(`Session renamed to "${r}"`)]):n(e=>[...e,cE("Failed to rename session. Please try again.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,oE("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,oE("No active conversation to rewind.")])}async function handleRewindSelect({messageId:e,mode:t,contextEngineRef:n,setFeed:r,setStatus:o,setShowRewindSelector:s,setStaticKey:i,setInput:a}){if(s(!1),n.current)try{const s=n.current.listCheckpoints().find(t=>t.messageId===e);o("Restoring checkpoint...");const l=await n.current.restoreToCheckpoint({messageId:e,mode:t});if(l.success){const e=n.current.getSessionManager(),t=n.current.getMessages();r(e.reconstructFeedFromMessages(t)),wb(),i(e=>e+1),s?.userPrompt&&a(s.userPrompt);const u=[];l.filesRestored>0&&u.push(`${l.filesRestored} file${l.filesRestored>1?"s":""} restored`),l.filesDeleted>0&&u.push(`${l.filesDeleted} file${l.filesDeleted>1?"s":""} deleted`),l.messagesRemoved>0&&u.push(`${l.messagesRemoved} message${l.messagesRemoved>1?"s":""} removed`);const d=u.length>0?`Restored to checkpoint: ${u.join(", ")}.`:"Restored to checkpoint.";return r(e=>[...e,oE(d)]),void o("Ready...")}r(e=>[...e,cE(`Failed to restore: ${l.error}`)]),o("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;r(e=>[...e,cE(t)]),o("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleHelpCommand({setFeed:e}){const{createSystemEntry:t}=await Promise.resolve().then(()=>(xE(),TE));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=rE(`/${tn.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=dE(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=mE(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveEntries:t,setShareInfo:n,setShowShareNotification:r,setUnshareNotificationMessage:o,setStaticKey:s,setContextUsage:i,setInteractionTokens:a,contextEngineRef:l,setSessionId:u,createContextEngineCallbacks:d,clearSessionPermissions:m,permissionModeRef:g}){if(e([]),t([]),wb(),n(null),r(!1),o(""),l.current){const t=l.current.getSessionManager();t&&await t.deleteShareInfo(),await(l.current.getHookSystem()?.shutdown()),l.current=null;const n=crypto.randomUUID();u(n),m();const r=getContextEngineCallbacks({createContextEngineCallbacks:d,sessionId:n}),{contextEngine:o,startupEntriesPromise:s}=bootstrapContextEngineWithHooks({projectRoot:process.cwd(),sessionId:n,runMode:"interactive",permissionMode:g.current,callbacks:r});l.current=o;const i=await s;i.length>0&&e(e=>[...e,...i])}s(e=>e+1),i(null),a(0)}async function handleInitCommand({setFeed:e}){try{const t=process.cwd(),n=`Created AGENTS.md at ${await initProjectMemory(t)}. You can now edit it with /memory or open it in your editor.`;e(e=>[...e,oE(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,oE(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await pe(n,{wait:!1,background:!0}),e(e=>[...e,oE(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(xE(),TE));e(e=>[...e,r("Failed to open browser"),t(createOSC8Link(n,"Open GitHub issue manually"))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const o=uE();n(o.id),r(e=>[...e,o])}async function handleCommand(e,t){const n=e.startsWith("/resume:"),r=n?null:parseCommandInput({input:e}),o=n?"/resume":r?.commandName??"";if(t.isCmdCodeBusy&&A_.has(o))return t.setFeed(e=>[...e,oE(`Cannot run ${o} while Command Code is working. Press Esc or Ctrl+C to interrupt the current turn first.`)]),{status:"handled"};if(n){const n=e.substring(8);return await handleSelectSession({selectedSessionId:n,sessionLoadIdRef:t.sessionLoadIdRef,contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,permissionModeRef:t.permissionModeRef,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,createContextEngineCallbacks:t.createContextEngineCallbacks}),{status:"handled"}}if(!r)return{status:"unknown"};const{commandName:s,rawArguments:i,positionalArgs:a}=r;if(x_.has(s)&&i.trim().length>0)return{status:"unknown"};if("/exit"===s)return t.setShouldExit(!0),{status:"handled"};if("/clear"===s)return await handleClearCommand(t),{status:"handled"};if("/help"===s)return await handleHelpCommand(t),{status:"handled"};if("/share"===s)return await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/unshare"===s)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/taste"===s)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===s)return handleLearnCommand(t),{status:"handled"};if("/skills"===s)return t.setShowSkillsConfig(!0),{status:"handled"};if("/provider"===s)return isInternalTeamFlagEnforced()?(t.setShowProviderSelector(!0),{status:"handled"}):(t.setStatus("Provider selection not available"),{status:"handled"});if("/model"===s)return t.setShowModelSelector(!0),{status:"handled"};if("/memory"===s)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===s)return t.setShowSessionSelector(!0),{status:"handled"};if("/init"===s)return await handleInitCommand(t),{status:"handled"};if("/agents"===s)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===s)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===s)return await handleCompactCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/compact-mode"===s)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/context"===s)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===s)return handleRewindCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/login"===s)return await handleLoginCommand({setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay}),t.setInput(""),{status:"handled"};if("/logout"===s)return await handleLogoutCommand({setFeed:t.setFeed,contextEngineRef:t.contextEngineRef,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),t.setInput(""),{status:"handled"};if("/courses"===s){const e="https://commandcode.ai/courses";try{await pe(e,{wait:!1,background:!0}),t.setFeed(t=>[...t,oE(`Opened ${createOSC8Link(e,"courses")} in your browser`)])}catch{t.setFeed(t=>[...t,oE(`Command Code courses: ${e}`)])}return{status:"handled"}}if("/feedback"===s)return await handleFeedbackCommand(t),{status:"handled"};if("/terminal-setup"===s)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===s)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===s)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===s)return await handleRenameCommand({name:i.trim(),contextEngineRef:t.contextEngineRef,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/usage"===s)return t.setShowUsageOverlay(!0),{status:"handled"};if("/review"===s){const e=i.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(kb(),Cb));let r=e,o=!1;if(!e){const e=await AT();r=e?String(e.number):"",o=!!e}return await n({input:buildReviewPrompt({prNumber:r,autoDetected:o}),role:"user",displayMessage:r?`/review ${r}`:"/review",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}if("/pr-comments"===s)return await handleSubmit({input:"Fetch and display all comments from the current GitHub pull request.\n\n Run these commands in order:\n\n 1. `gh pr view --json number,headRepository` — if this fails, reply \"No comments found.\" and stop.\n 2. `gh api --paginate '/repos/{owner}/{repo}/issues/NUMBER/comments' --jq '.[] | {body,\n user: .user.login, id, created_at}' > /tmp/pr-NUMBER-issue-comments.json`\n 3. `gh api --paginate '/repos/{owner}/{repo}/pulls/NUMBER/comments' --jq '.[] | {body,\n diff_hunk: (.diff_hunk | split(\"\n\") | .[-5:] | join(\"\n\")), path, line, user: .user.login,\n in_reply_to_id, id, created_at}' > /tmp/pr-NUMBER-review-comments.json`\n\n If both return empty, reply \"No comments found.\"\n\n `{owner}` and `{repo}` are gh template variables — write them literally, never substitute. Always\n use `--jq` (not piped `| jq`).\n\n Read the temp JSON files to build output comments directly in markdown using the format:\n\n ## PR Comments\n\n - @author (date):\n > body\n\n ## Review Comments\n\n - @author path#line:\n ```diff (replace ```suggestion code blocks with ```diff to avoid rendering errors)\n [diff_hunk]\n ```\n > body [replies indented by in_reply_to_id]\n\n Number the comments in the order they were created (created_at).\n No explanatory text, no horizontal rules. No extra space in the end.",role:"user",displayMessage:"/pr-comments",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),lastResponseHasComments(t.contextEngineRef.current?.getMessages()??[])&&t.setInput("Fix all review comments"),{status:"handled"};if("/status"===s)return t.setShowStatusView(!0),{status:"handled"};if("/upgrade"===s){let e=await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})??"https://commandcode.ai/settings/billing";e+="#plans";try{await pe(e,{wait:!1,background:!0}),t.setFeed(t=>[...t,oE(`Opened ${createOSC8Link(e,"billing page")} in your browser`)])}catch{t.setFeed(t=>[...t,oE(`Upgrade your plan: ${e}`)])}return{status:"handled"}}if("/extra"===s){let e=await getBillingLink({billingLink:t.billingLink,setBillingLink:t.setBillingLink})??"https://commandcode.ai/settings/billing";e+="#extra-usage";try{await pe(e,{wait:!1,background:!0}),t.setFeed(t=>[...t,oE(`Opened ${createOSC8Link(e,"billing page")} in your browser`)])}catch{t.setFeed(t=>[...t,oE(`Buy on-demand credits: ${e}`)])}return{status:"handled"}}const l=getCustomCommandContent(s);if(l){const n=processCommandTemplate({template:l,rawArguments:i,positionalArgs:a}),{handleSubmit:r}=await Promise.resolve().then(()=>(kb(),Cb));return await r({input:n.content,role:"user",displayMessage:e,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,currentModel:t.currentModel,premiumCreditsExhausted:t.premiumCreditsExhausted,setPremiumCreditsExhausted:t.setPremiumCreditsExhausted,setCurrentModel:t.setCurrentModel,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}return await handleSkillCommand({commandName:s,command:e,rawArguments:i,positionalArgs:a,ctx:t})||{status:"unknown"}}async function handleSkillCommand({commandName:e,command:n,rawArguments:r,positionalArgs:o,ctx:s}){const i=e.startsWith("/")?e.substring(1):e;let a;try{a=await loadAllSkillSummaries()}catch{return null}const l=deduplicateSkills(a).find(e=>e.name===i);if(!l)return null;const{names:u}=await loadDisabledSkills();if(u.has(l.name))return s.setFeed(e=>[...e,oE(`Skill "${i}" is disabled. Toggle it back on with /skills.`)]),{status:"handled"};try{const a=await loadSkill({filePath:l.filePath}),u=buildSlashCommandMessage({commandName:e,rawArguments:r,skillName:i}),d=buildSlashCommandSkillContextMessage({rawArguments:r,positionalArgs:o,skillContent:a.content,skillDirectory:t.dirname(l.filePath)});return await handleSubmit({input:u,hiddenMessages:[{role:"user",content:d}],role:"user",displayMessage:n,isAutomated:!0,feed:s.feed,setFeed:s.setFeed,isCmdCodeBusy:s.isCmdCodeBusy,setIsCmdCodeBusy:s.setIsCmdCodeBusy,setQueuedMessages:s.setQueuedMessages,setStatus:s.setStatus,setInteractionTokens:s.setInteractionTokens,updateStatus:s.updateStatus,setUpdateStatus:s.setUpdateStatus,billingLink:s.billingLink,setBillingLink:s.setBillingLink,contextEngineRef:s.contextEngineRef,isSubmittingRef:s.isSubmittingRef,setInput:s.setInput,setStaticKey:s.setStaticKey,executeBash:s.executeBash}),{status:"handled"}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return s.setFeed(e=>[...e,cE(`Failed to load skill "${i}": ${t}`)]),{status:"handled"}}}function useCommandCtx({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,permissionState:a,contextEngineRef:l,isSubmittingRef:u,executeBash:d,createContextEngineCallbacks:m,setInput:g}){const h=Z(()=>({feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,setStaticKey:o.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,currentModel:r.currentModel,premiumCreditsExhausted:r.premiumCreditsExhausted,setPremiumCreditsExhausted:r.setPremiumCreditsExhausted,setCurrentModel:r.setCurrentModel,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setRetryAttempt:n.setRetryAttempt,setShowTasteConfig:o.setShowTasteConfig,setShowSkillsConfig:o.setShowSkillsConfig,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowMemorySelector:o.setShowMemorySelector,setShowAgentsConfig:o.setShowAgentsConfig,setShowMcpManager:o.setShowMcpManager,setShowRewindSelector:o.setShowRewindSelector,setShowCompactModeSelector:o.setShowCompactModeSelector,setShowContextView:o.setShowContextView,setShowAddDirModal:o.setShowAddDirModal,setShowLoginOverlay:o.setShowLoginOverlay,setShowStatusView:o.setShowStatusView,setShowUsageOverlay:o.setShowUsageOverlay,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:o.setShowSessionSelector,setPermissionMode:a.setPermissionMode,permissionModeRef:a.permissionModeRef,contextEngineRef:l,clearSessionPermissions:a.clearSessionPermissions,createContextEngineCallbacks:m,setShouldExit:i.setShouldExit,setInput:g,isSubmittingRef:u,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:d}),[e,t,n,r,o,s,i,a,l,u,d,m,g]),f=J(h);return f.current=h,{commandCtx:h,onCommand:ee(e=>handleCommand(e,f.current),[])}}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i}){try{const a=getProviderConfig(e);if(a?.requiresAuth&&a.checkAuth&&!await a.checkAuth()&&a.authComponent)return void r({provider:e,Component:a.authComponent});await updateUserConfig({provider:e}),t(e),n(!1),o(`Provider set to ${getProviderDisplayName(e)}`),i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),o("Failed to set provider"),n(!1)}}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:o,setShowProviderNotification:s,providerNotificationTimer:i}){e&&(t(null),n(!1),r(e.provider),o(`${getProviderDisplayName(e.provider)} authentication successful`),i.current&&clearTimeout(i.current),s(!0),i.current=setTimeout(()=>{s(!1),i.current=null},5e3))}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}async function resolveAuthBlock(e){if(!e)return null;const t=getProviderConfig(e);return t?.requiresAuth&&t.checkAuth?await t.checkAuth()?null:{displayName:t.displayName}:null}async function persistSelection(e){const{modelId:t,provider:n,setCurrentProvider:r}=e;n?(dlog(`[Model] Setting provider to ${n} for ${t}`),await updateUserConfig({provider:n,model:t}),r?.(n)):await updateUserConfig({model:t})}async function handleModelSelect({modelId:e,provider:t,setCurrentModel:n,setShowModelSelector:r,setStatus:o,modelNotificationTimer:s,setShowModelNotification:i,setCurrentProvider:a,setStaticKey:l,contextEngineRef:u,setFeed:d,setContextUsage:m}){try{const g=await resolveAuthBlock(t);if(g)return o(`Run /provider to authenticate with ${g.displayName} first`),void r(!1);const h=getConfiguredModel();await persistSelection({modelId:e,provider:t,setCurrentProvider:a}),n(e);const f=h!==e;f&&(hardResetForResize(),l(e=>e+1)),r(!1);const y=getModelDisplayName(e);o(`Model set to ${y}`),f&&await reconcileContextOnModelChange({modelId:e,modelName:y,previousLimit:getContextLimit(h),contextEngineRef:u,setFeed:d,setContextUsage:m}),s.current&&clearTimeout(s.current),i(!0),s.current=setTimeout(()=>{i(!1),s.current=null},5e3)}catch(e){console.error("Failed to set model:",e),o("Failed to set model"),r(!1)}}async function reconcileContextOnModelChange(e){const{modelId:t,modelName:n,previousLimit:r,contextEngineRef:o,setFeed:s,setContextUsage:i}=e,a=o?.current;if(!a)return void i?.({current:0,limit:getContextLimit(t)});const l=await a.onModelChanged(r);if(i?.({current:a.getContextTokensUsed(),limit:l.newLimit}),!l.overflowed)return;const u=Math.round(l.tokensUsed/l.newLimit*100),d=l.tokensSaved>0?`${n} has a smaller context window (${l.newLimit.toLocaleString()} tokens). Auto-compacted to fit — saved ~${l.tokensSaved.toLocaleString()} tokens.`:`${n} has a smaller context window (${l.newLimit.toLocaleString()} tokens) and current usage is ~${l.tokensUsed.toLocaleString()} (${u}%). Run /compact to free space before your next message.`;s?.(e=>[...e,oE(d)])}function handleModelCancel({setShowModelSelector:e}){e(!1)}Ot(),xE(),yb(),fs(),ME(),cb(),ws(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ot(),xE(),Eb(),Jr(),__name(handleCompactCommand,"handleCompactCommand"),Ot(),xE(),__name(handleRenameCommand,"handleRenameCommand"),Ot(),xE(),Eb(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),kb(),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(handleFeedbackCommand,"handleFeedbackCommand"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(handleSkillCommand,"handleSkillCommand"),__name(useCommandCtx,"useCommandCtx"),Ot(),Ot(),io(),Jr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Ot(),xE(),Jr(),io(),Qr(),Kn(),__name(resolveAuthBlock,"resolveAuthBlock"),__name(persistSelection,"persistSelection"),__name(handleModelSelect,"handleModelSelect"),__name(reconcileContextOnModelChange,"reconcileContextOnModelChange"),__name(handleModelCancel,"handleModelCancel"),Ot(),Jr();var N_={default:"Compact Normal",fast:"Compact Fast"};async function handleCompactModeSelect({mode:e,setShowCompactModeSelector:t,setStatus:n}){try{await setCompactMode({mode:e}),t(!1),n(`Compact mode set to: ${N_[e]}`)}catch{n("Failed to set compact mode"),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var R_=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l}){const u=J({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l});return u.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l},{onSelectSession:ee(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:o,permissionState:s,contextEngineRef:i,createContextEngineCallbacks:a}=u.current;handleSelectSession({selectedSessionId:e,sessionLoadIdRef:n.sessionLoadIdRef,contextEngineRef:i,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:o.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,permissionModeRef:s.permissionModeRef,setStaticKey:o.setStaticKey,setShareInfo:r.setShareInfo,createContextEngineCallbacks:a})},[]),onNewSession:ee(()=>{const{feedState:e,sessionState:t,uiOverlays:n,permissionState:r,contextEngineRef:o}=u.current;handleNewSession({contextEngineRef:o,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:n.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:r.setPermissionMode})},[]),onRewindSelect:ee(({messageId:e,mode:t})=>{const{feedState:n,statusState:r,uiOverlays:o,contextEngineRef:s,setInput:i}=u.current;handleRewindSelect({messageId:e,mode:t,contextEngineRef:s,setFeed:n.setFeed,setStatus:r.setStatus,setShowRewindSelector:o.setShowRewindSelector,setStaticKey:o.setStaticKey,setInput:i})},[]),onRewindCancel:ee(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:ee((e,t)=>{const{feedState:n,statusState:r,uiOverlays:o,contextEngineRef:s}=u.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:o.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus,contextEngineRef:s})},[]),onLoginCancel:ee(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:ee(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:r.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:n.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer})},[]),handleProviderCancel:ee(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:ee((e,t)=>{const{authState:n,statusState:r,uiOverlays:o,feedState:s,contextEngineRef:i}=u.current;handleModelSelect({modelId:e,provider:t,setCurrentModel:n.setCurrentModel,setShowModelSelector:o.setShowModelSelector,setStatus:r.setStatus,modelNotificationTimer:n.modelNotificationTimer,setShowModelNotification:R_,setCurrentProvider:n.setCurrentProvider,setStaticKey:o.setStaticKey,contextEngineRef:i,setFeed:s.setFeed,setContextUsage:r.setContextUsage})},[]),handleModelCancel:ee(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleCompactModeSelect:ee(e=>{const{statusState:t,uiOverlays:n}=u.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),handleCompactModeCancel:ee(()=>{handleCompactModeCancel({setShowCompactModeSelector:u.current.uiOverlays.setShowCompactModeSelector})},[]),handleAuthSuccess:ee(()=>{const{authState:e,statusState:t,uiOverlays:n}=u.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:n.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:t.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer})},[]),handleAuthCancel:ee(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}function findNewThreshold({depletionPct:e,warnedThresholds:t}){const n=[...en].sort((e,t)=>t-e);for(const r of n)if(e>=r&&!t.has(r))return r;return null}function getDepletionPct({planId:e,monthlyCredits:t}){const n=Yt[e];if(!n||n.total<=0)return null;const r=n.total-t;return Math.min(100,Math.max(0,r/n.total*100))}function buildWarningMessage({depletionPct:e,remainingCredits:t,billingUrl:n}){return`${Math.round(e)}% of plan credits used (${Number.isInteger(t)?String(t):t.toFixed(1)} remaining). Upgrade: ${n}`}function useCreditWarning({interactionTokens:e}){const[t,n]=Y(null),r=J(new Set),o=J(null),s=J(!1),i=J(null),a=J("https://commandcode.ai/settings/billing"),l=J(null),u=J(null),d=ee(async()=>{try{const e=getApiBaseUrl(),t=new jw({baseUrl:e});if(!s.current){s.current=!0;try{const e=await getAuthenticatedEntity();i.current=e.org?.id??null,a.current=e.org?`https://commandcode.ai/${e.org.login}/settings/billing`:"https://commandcode.ai/settings/billing";const n=await t.get({endpoint:buildEndpoint({endpoint:Bt.ALPHA.BILLING.SUBSCRIPTIONS,params:{orgId:i.current}})});o.current=n}catch{return}}const l=o.current;if(!l?.success||!l.data)return;const{planId:d,status:m}=l.data;if("active"!==m&&"past_due"!==m)return;if(!Yt[d]||Yt[d].total<=0)return;let g;try{g=await t.get({endpoint:buildEndpoint({endpoint:Bt.ALPHA.BILLING.CREDITS,params:{orgId:i.current}})})}catch{return}const{monthlyCredits:h}=g.credits,f=getDepletionPct({planId:d,monthlyCredits:h});if(null===f)return;const y=findNewThreshold({depletionPct:f,warnedThresholds:r.current});if(null===y)return;for(const e of en)e<=y&&r.current.add(e);const w=buildWarningMessage({depletionPct:f,remainingCredits:h,billingUrl:a.current});n(w),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{n(null),u.current=null},3e4)}catch{}},[]);return X(()=>{if(0!==e)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{d(),l.current=null},2e3),()=>{l.current&&clearTimeout(l.current)}},[e,d]),X(()=>()=>{u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current)},[]),{creditWarning:t}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Ot(),fS(),sS(),bb(),wn(),__name(findNewThreshold,"findNewThreshold"),__name(getDepletionPct,"getDepletionPct"),__name(buildWarningMessage,"buildWarningMessage"),__name(useCreditWarning,"useCreditWarning"),Ot(),Ot(),Ot();var M_=__name(({staticKey:e})=>Q.createElement(re,{items:[{staticKey:e}],key:e},()=>Q.createElement(ne,{key:e},"\0")),"Responsive");Ot(),wn(),Rr();var L_=__name(({onTrust:e,onExit:t})=>{const{exit:n}=ae(),[r,o]=Y(1),s=process.cwd().replace(process.env.HOME||"","~");return se((s,i)=>{i.upArrow||i.downArrow?o(1===r?2:1):i.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||i.escape||i.ctrl&&"c"===s)&&(t(),n())}),Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.YELLOW,padding:1},Q.createElement(ne,{color:ar.YELLOW,bold:!0},"Do you trust the files in this folder?"),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},s)),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:1===r?ar.CYAN:ar.GRAY},1===r?Pe.pointer:" "," 1. Yes, proceed")),Q.createElement(te,null,Q.createElement(ne,{color:2===r?ar.CYAN:ar.GRAY},2===r?Pe.pointer:" "," 2. No, exit"))))},"TrustPrompt"),$_=K(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return Q.createElement(Q.Fragment,null,Q.createElement(M_,{staticKey:e}),Q.createElement(L_,{onTrust:t,onExit:n}))},"TrustView"));Ot(),Ot(),as(),Rr();var D_=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=ae(),[r,o]=Y([]),[s,i]=Y(0),[a,l]=Y(!0),[u,d]=Y(0),m=30;X(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await ok.listSessions();o(e),l(!1)},"loadSessions");if(se((t,o)=>{o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):o.downArrow?i(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()}),a)return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:ar.GRAY},"Loading sessions..."));const h=__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),i=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===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),f=__name(e=>truncateString({text:e,maxChars:Yo}),"truncateMessage");if(0===r.length)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.GRAY},"No sessions available"));const y=r.slice(u,u+m),w=u;return Q.createElement(te,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.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(te,{columnGap:2,marginBottom:1},Q.createElement(te,{width:7},Q.createElement(ne,{color:ar.GRAY}," ")),Q.createElement(te,{width:13},Q.createElement(ne,{color:ar.GRAY},"Modified")),Q.createElement(te,{width:11},Q.createElement(ne,{color:ar.GRAY},"# Messages")),Q.createElement(te,{width:20},Q.createElement(ne,{color:ar.GRAY},"Git Branch")),Q.createElement(te,null,Q.createElement(ne,{color:ar.GRAY},"Summary"))),Q.createElement(te,{columnGap:2},Q.createElement(te,{flexDirection:"column",width:7},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`sel-${n}`,color:s===n?ar.CYAN:ar.GRAY},s===n?`${Pe.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(te,{flexDirection:"column",width:13},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`mod-${e.id}`,color:s===n?ar.WHITE:ar.GRAY},h(e.lastModified))})),Q.createElement(te,{flexDirection:"column",width:11},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`msg-${e.id}`,color:s===n?ar.WHITE:ar.GRAY},e.messageCount)})),Q.createElement(te,{flexDirection:"column",width:20},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`branch-${e.id}`,color:s===n?ar.WHITE:ar.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(te,{flexDirection:"column"},y.map((e,t)=>{const n=w+t;return Q.createElement(ne,{key:`summary-${e.id}`,color:s===n?ar.WHITE:ar.GRAY},f(e.firstMessage))}))))},"SessionTable"),O_=K(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return Q.createElement(D_,{onSelectSession:e,onNewSession:t})},"SessionView"));Ot(),Ot(),$r(),Rr();var F_=__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"),q_=__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,i)=>{const a=i===t&&!r,l=n.has(i);let u,d;a?(u=Pe.bullet,d=ar.CYAN):l?(u=Pe.tick,d=ar.GREEN):(u=Pe.circle,d=ar.GRAY),s.push(Q.createElement(ne,{key:i},Q.createElement(ne,{color:d},u),Q.createElement(ne,{color:a?ar.CYAN:void 0}," ",o.header),i<e.length-1?Q.createElement(ne,{color:ar.DIM}," | "):null))}),!o){const e=r;s.push(Q.createElement(ne,{key:"review"},Q.createElement(ne,{color:ar.DIM}," | "),Q.createElement(ne,{color:e?ar.CYAN:ar.GRAY},e?Pe.bullet:Pe.circle),Q.createElement(ne,{color:e?ar.CYAN:void 0,bold:e}," ","Review")))}return Q.createElement(te,null,s)},"TabIndicator"),j_=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,o]=Y(0),[s,i]=Y(new Map),a=J(new Map),[l,u]=Y(""),[d,m]=Y(new Set),[g,h]=Y(null),[f,y]=Y(!1),[w,S]=Y(!1),[E,C]=Y(!1),[v,k]=Y(null),[T,_]=Y(!1),x=e[r],A=x?.multiSelect??!1,P=s.get(r),I=x?[...x.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],N=I.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),R=new Map(N.map((e,t)=>[e.label,I[t]])),M=__name(e=>{"submit"===e.value?q():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),L=__name(()=>{if(!P||0===P.length)return 0;const e=P[0],t=x.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),$=__name(e=>{if(!f)if(A){const t=F_(e.value,x.options.length-1);if(null===t)return;const n=x.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=F_(e.value,x.options.length-1);if(null===t)return;y(!0);const n=x.options[t]?.label||"";F([n])}},"handleSelect"),D=__name(()=>{if(f)return;y(!0);const e=Array.from(d);F(e)},"handleMultiSelectDone"),O=__name(()=>{if(!f&&l.trim())if(A){const e=new Set(x.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 y(!0),F([l.trim()])},"handleOtherSubmit"),F=__name(t=>{a.current.set(r,t);const s=new Map(a.current);i(s);const l=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),o(e),y(!1),C(!1),k(null),_(!1)}else if(e.every((e,t)=>s.has(t))){if(n&&1===e.length)return void q();m(new Set),u(""),S(!0),y(!1)}else{const t=e.findIndex((e,t)=>!s.has(t));-1!==t&&(l(t),o(t)),y(!1),C(!1),k(null),_(!1)}},"finishQuestion"),q=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),j=__name(t=>{S(!1),o(t),_(!1),C(!1),k(null);const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),U=__name(t=>{if(t<0||t>=e.length)return;A&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),y(!1),C(!1),k(null),_(!1);const n=e[t],s=a.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"),B=__name(()=>{if(!g||!A)return;if("done"===g.value)return;const e=F_(g.value,x.options.length-1);if(null===e)return;const t=x.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return se((t,o)=>{if(" "===t&&A&&!E&&B(),"d"!==t||!A||E||w||D(),!w&&!f){if(o.downArrow&&!E&&!T&&!n&&g&&N.length>0&&g.value===N[N.length-1]?.value&&C(!0),o.upArrow&&!E&&!T&&g&&N.length>0&&g.value===N[0]?.value&&(A?_(!0):n||(C(!0),k(N.length-1))),o.upArrow&&E){C(!1),k(N.length-1);const e=N[N.length-1];e&&h(e)}if(o.downArrow&&E)if(C(!1),A)_(!0);else{k(0);const e=N[0];e&&h(e)}if(o.upArrow&&T&&(_(!1),C(!0)),o.downArrow&&T){_(!1),k(0);const e=N[0];e&&h(e)}o.return&&T&&A&&D()}if(f||E||T||(w?o.leftArrow&&j(e.length-1):o.leftArrow&&r>0?U(r-1):o.rightArrow&&(r<e.length-1?U(r+1):(A&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),S(!0)))),o.escape&&!f)if(w)S(!1);else if(E){C(!1);const e=v??N.length-1;k(e);const t=N[e];t&&h(t)}else if(T){_(!1);const e=N[N.length-1];e&&h(e)}}),x||w?w?Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(q_,{questions:e,currentIndex:e.length,answeredQuestions:new Set(s.keys()),isReviewPage:!0})),e.map((e,t)=>Q.createElement(te,{key:t,marginBottom:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},t+1,". ",e.question),Q.createElement(ne,{color:ar.GREEN}," ",s.get(t)?.join(", ")||"No answer"))),Q.createElement(mt,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:M,initialIndex:0,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(ne,{color:t?ar.CYAN:ar.WHITE},e)}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},Pe.arrowLeft," to go back and edit"))):Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(q_,{questions:e,currentIndex:r,answeredQuestions:new Set(s.keys()),isReviewPage:!1,hideReview:n})),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0},x.question)),E||T?Q.createElement(te,{flexDirection:"column"},N.map((e,t)=>{const n=R.get(e.label),r=A&&n&&d.has(n.label),o=!A&&n&&P?.includes(n.label),s=r||o;return Q.createElement(te,{key:t,flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,null," "),Q.createElement(ne,{color:s?ar.GREEN:ar.WHITE}," ",t+1,"."," "),A&&(s?Q.createElement(ne,{color:ar.GREEN},"[",Pe.tick,"]"," "):Q.createElement(ne,{color:ar.DIM},"[ ] ")),Q.createElement(ne,{color:s?ar.GREEN:ar.WHITE},n?.label||""),!A&&s&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick)),n?.description&&Q.createElement(te,null,Q.createElement(ne,null," "),Q.createElement(ne,{color:ar.DIM},A?" ":" ",n.description)))})):Q.createElement(mt,{key:`${r}-${v??"default"}`,items:N,initialIndex:v??L(),onSelect:$,onHighlight:h,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=R.get(e),r=A&&n&&d.has(n.label),o=!A&&n&&P?.includes(n.label),s=r||o,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:t?ar.CYAN:s?ar.GREEN:ar.WHITE}," ",a,"."," "),A&&(s?Q.createElement(ne,{color:ar.GREEN},"[",Pe.tick,"]"," "):Q.createElement(ne,{color:ar.DIM},"[ ] ")),Q.createElement(ne,{color:t?ar.CYAN:s?ar.GREEN:ar.WHITE},l),!A&&s&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick)),n?.description&&Q.createElement(ne,{color:ar.DIM},A?" ":" ",n.description))}}),!n&&Q.createElement(te,null,Q.createElement(ne,{color:ar.CYAN},E?Pe.pointer:" "),Q.createElement(ne,{color:E?ar.CYAN:void 0}," ",N.length+1,"."," "),A&&(d.has(l.trim())?Q.createElement(ne,{color:ar.GREEN},"[",Pe.tick,"] "):Q.createElement(ne,{color:ar.DIM},"[ ] ")),Q.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),A&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:O,placeholder:"Type something...",focus:E,stripBracketedPaste:!0})),A&&Q.createElement(te,null,Q.createElement(ne,{color:ar.CYAN},T?Pe.pointer:" "),Q.createElement(ne,{color:T?ar.CYAN:void 0,bold:T}," ",r===e.length-1?"Submit":"Next")),e.length>1&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,dangerouslySkipPermissions:n,setPendingQuestion:r,setStatus:o,setStaticKey:s}){return Q.createElement(te,{marginY:1},Q.createElement(j_,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,onResponse:i=>{if(e.params.exitPlanMode){const e=i.answers[0]?.selectedOptions[0]||"";e.startsWith("Yes, auto-accept")?(t("auto-accept"),wb(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t(n?"bypass":"standard"),wb(),s(e=>e+1))}if(e.params.enterPlanMode){const e=i.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),wb(),s(e=>e+1))}e.resolve(i),r(null),o("Answers submitted")}}))}Eb(),__name(QuestionView,"QuestionView"),Ot(),Ot(),wn(),Ot(),Rr();var U_=/\[([^\]]+)\]/g;function BracketWrap({children:e,color:t,bold:n=!1}){return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIMMEST,bold:n},"["),"string"==typeof e?Q.createElement(ne,{color:t,bold:n},e):e,Q.createElement(ne,{color:ar.DIMMEST,bold:n},"]"))}function BracketedText({text:e,color:t,bold:n=!1,wrap:r}){const o=Z(()=>{const t=[];let n=0;for(const r of e.matchAll(U_)){const o=r.index??0;o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"bracket",value:r[1]??""}),n=o+r[0].length}return n<e.length&&t.push({type:"text",value:e.slice(n)}),0===t.length&&t.push({type:"text",value:e}),t},[e]),s=Z(()=>o.map((e,r)=>"bracket"===e.type?Q.createElement(BracketWrap,{key:`bracket-${r}`,color:t,bold:n},e.value):e.value),[o,t,n]);return Q.createElement(ne,{color:t,bold:n,wrap:r},s)}__name(BracketWrap,"BracketWrap"),__name(BracketedText,"BracketedText"),Rr(),Ot(),xE(),as(),ao(),Rr(),Ot(),Rr();var B_=class extends ht{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}hr(){return"\n"+ce.dim("───")+"\n"}blockquote(e){return"object"==typeof e&&(e=this.parser.parse(e.tokens)),this.o.blockquote(e.trim()).split("\n").map(e=>`│ ${e}`).join("\n")+"\n\n"}listDepth=0;list(e,t=!1,n=""){let r;this.listDepth++;try{r=super.list(e,t,n),r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),1===this.listDepth&&(r=r.replace(/^ /gm,""))}finally{this.listDepth--}return r}},z_=new gt;z_.setOptions({renderer:new B_({strong:ce.bold,em:ce.italic,del:ce.dim.strikethrough,codespan:ce.hex(Tr.CODE),code:ce.hex(Tr.CODE),heading:ce.bold,firstHeading:ce.bold.hex(Tr.HEADING).underline,link:ce.hex(ar.CYAN),href:ce.hex(ar.CYAN).underline,blockquote:ce.hex(ar.GRAY).italic,table:ce.reset,tableOptions:{style:{head:[ar.CYAN],border:[ar.GRAY]}},hr:ce.reset,paragraph:ce.reset,html:ce.hex(ar.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var H_=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=Z(()=>{if(!e)return"";const t=[],n=e.replace(H_,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=z_.parse(n);if("string"!=typeof r)return e;return r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").replace(/^(\s*)\* /gm,"$1- ").replace(/\n{3,}/g,"\n\n").trim()}catch{return e}},[e]);return Q.createElement(ne,{color:t,dimColor:n,wrap:r},o)}function buildTreeConnectors(e,t={}){const{isTruncated:n=!1,closesFrame:r=!0}=t;return e.split("\n").map((e,t,o)=>r&&!n&&t===o.length-1?ST:ET).join("\n")}__name(Markdown,"Markdown"),Ot(),__name(buildTreeConnectors,"buildTreeConnectors");var W_=" │ ";function computeSimilarity({strA:e,strB:t}){const n=e.trim(),r=t.trim();if(n===r)return 1;if(!n||!r)return 0;const o=Object.create(null);for(let e=0;e<n.length;e++){const t=n[e];o[t]=(o[t]??0)+1}let s=0;for(let e=0;e<r.length;e++){const t=r[e],n=o[t];n&&(s++,o[t]=n-1)}return 2*s/(n.length+r.length)}function buildSimilarityMatrix(e,t,n){const r=new Float64Array(e.length*n);for(let o=0;o<e.length;o++)for(let s=0;s<n;s++)r[o*n+s]=computeSimilarity({strA:e[o],strB:t[s]});return r}function collectSimilarityCandidates(e,t,n){const r=[];for(let o=0;o<t;o++)for(let t=0;t<n;t++){const s=e[o*n+t];s>=.3&&r.push({score:s,removedIdx:o,addedIdx:t})}return r}function buildLinePairs(e,t){const n=e.length,r=t.length,o=new Map;if(n*r>200){const e=Math.min(n,r);for(let t=0;t<e;t++)o.set(t,t);return o}const s=collectSimilarityCandidates(buildSimilarityMatrix(e,t,r),n,r);s.sort((e,t)=>t.score-e.score);const i=new Set,a=new Set;for(const{removedIdx:e,addedIdx:t}of s)i.has(e)||a.has(t)||(o.set(e,t),i.add(e),a.add(t));return o}function groupAdjacentChanges(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r.added&&!r.removed){const e=r.value.split("\n");""===e.at(-1)&&e.pop(),t.push({type:"context",contextLines:e,removedLines:[],addedLines:[]}),n++;continue}const o=[],s=[];for(;n<e.length&&(e[n].added||e[n].removed);){const t=e[n].value.split("\n");""===t.at(-1)&&t.pop(),e[n].removed?(o.push(...t),n++):(s.push(...t),n++)}t.push({type:"change",contextLines:[],removedLines:o,addedLines:s})}return t}function renderWordSegments({wordChanges:e,type:t,dimDiff:n}){const r="removed"===t?mr.REMOVED_HIGHLIGHT_BG:mr.ADDED_HIGHLIGHT_BG,o=[];let s=0;for(const i of e){if("removed"===t&&i.added)continue;if("added"===t&&i.removed)continue;const e="removed"===t?i.removed:i.added,a=i.value.replace(/\s/g," "),l=`${t}-${s++}-${e?"highlighted":"unchanged"}`;e?o.push(Q.createElement(ne,{key:l,backgroundColor:r,dimColor:n},a)):o.push(Q.createElement(ne,{key:l,color:ar.WHITE,dimColor:n},a))}return o}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:o}){return Q.createElement(te,{key:o,width:"100%"},Q.createElement(ne,{color:mr.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:r},W_),Q.createElement(ne,{color:ar.WHITE,dimColor:r}," ",e.replace(/\s/g," ")))}function renderContextGroup({lines:e,leadCount:t,trailCount:n,lineNumWidth:r,dimDiff:o,counters:s}){const i=[];if(t+n>=e.length){for(const t of e)i.push(renderContextLine({line:t,lineNum:s.newLineNum,lineNumWidth:r,dimDiff:o,nodeKey:"ctx-"+s.nodeKey++})),s.oldLineNum++,s.newLineNum++;return i}for(let n=0;n<t;n++)i.push(renderContextLine({line:e[n],lineNum:s.newLineNum,lineNumWidth:r,dimDiff:o,nodeKey:"ctx-"+s.nodeKey++})),s.oldLineNum++,s.newLineNum++;const a=e.length-t-n;a>0&&(s.oldLineNum+=a,s.newLineNum+=a,i.push(Q.createElement(te,{key:"sep-"+s.nodeKey++},Q.createElement(ne,{color:mr.LINE_NUM,dimColor:o}," ".repeat(r+1)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:o},W_),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:o},`⋮ ${a} line${1===a?"":"s"}`))));for(let t=e.length-n;t<e.length;t++)i.push(renderContextLine({line:e[t],lineNum:s.newLineNum,lineNumWidth:r,dimDiff:o,nodeKey:"ctx-"+s.nodeKey++})),s.oldLineNum++,s.newLineNum++;return i}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const u=pt.diffLines(e,t);let d=0,m=0;for(const e of u)e.added&&(d+=e.count||1),e.removed&&(m+=e.count||1);const g=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),h=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),f=Math.max(3,(i+g-1).toString().length,(i+h-1).toString().length),y=groupAdjacentChanges(u),w=[],S={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<y.length;e++){const t=y[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===y[e-1].type,o=e<y.length-1&&"change"===y[e+1].type;if(!r&&!o){S.oldLineNum+=n.length,S.newLineNum+=n.length;continue}const s=r?Math.min(3,n.length):0,i=o?Math.min(3,Math.max(0,n.length-s)):0;w.push(...renderContextGroup({lines:n,leadCount:s,trailCount:i,lineNumWidth:f,dimDiff:a,counters:S}));continue}const{removedLines:n,addedLines:r}=t,o=buildLinePairs(n,r),s=new Map,i=new Map;for(const[e,t]of o){const o=pt.diffWordsWithSpace(n[e],r[t]);s.set(e,o),i.set(t,o)}for(let e=0;e<n.length;e++){const t=s.get(e);w.push(Q.createElement(te,{key:"rm-"+S.nodeKey++,width:"100%",backgroundColor:mr.REMOVED_BG},Q.createElement(ne,{color:mr.REMOVED_TEXT,dimColor:a}," "+S.oldLineNum.toString().padStart(f)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:a},W_),Q.createElement(ne,{color:mr.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):Q.createElement(ne,{color:mr.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),S.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);w.push(Q.createElement(te,{key:"add-"+S.nodeKey++,width:"100%",backgroundColor:mr.ADDED_BG},Q.createElement(ne,{color:mr.ADDED_TEXT,dimColor:a}," "+S.newLineNum.toString().padStart(f)),Q.createElement(ne,{color:mr.LINE_NUM,dimColor:a},W_),Q.createElement(ne,{color:mr.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):Q.createElement(ne,{color:mr.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),S.newLineNum++}}const E=void 0!==l&&w.length>l,C=E?w.slice(0,l):w;return{diffContent:Q.createElement(te,{flexDirection:"column"},o&&!r&&(d>0||m>0)&&Q.createElement(ne,{color:ar.GRAY},"Updated"," ",Q.createElement(ne,{color:ar.WHITE,bold:!0},n)," ","with"," ",d>0&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:fr.SUCCESS},d)," ","addition",1!==d?"s":"",m>0?" and ":""),m>0&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:fr.ERROR},m)," ","removal",1!==m?"s":"")),r&&Q.createElement(ne,{color:ar.RED},"Rejected update to",Q.createElement(ne,{color:ar.RED},` ${n}`)),Q.createElement(te,{flexDirection:"column",marginLeft:s,marginRight:s+4,width:(process.stdout.columns||80)-2*s-8},C)),isTruncated:E,totalLines:w.length}}function formatTodosForDisplay(e){const t=vE(e);return t?Q.createElement(te,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?Pe.checkboxOn:Pe.checkboxOff;let r,o=!1;switch(e.status){case"completed":r=fr.SUCCESS,o=!0;break;case"in_progress":r=fr.IN_PROGRESS;break;default:r=ar.WHITE}return Q.createElement(te,{key:e.id||t,flexDirection:"row"},Q.createElement(te,{width:2},Q.createElement(ne,{color:r},n)),Q.createElement(ne,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):Q.createElement(ne,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){if(!e)return e;if(t){const t=e.split(/[.\n]/)[0];return t?t+(e.includes(".")||e.includes("\n")?".":""):e}return n&&!r?truncateCommand({command:e}):e}function formatToolInput({input:e,isShell:t}){return Q.createElement(BracketWrap,null,t?e:Q.createElement(Markdown,null,e))}function parseReadSummaryLine(e){if(!e)return null;const t=e.split("\n")[0]?.trim();return t?t.match(vC):null}function getReadToolInlineSummary({name:e,summaryMatch:t}){if(!t||"READ"!==e)return null;const n=t[3]?Number(t[3]):void 0;return{dimText:void 0===n?void 0:`${n} ${1===n?"line":"lines"}`}}function renderReadToolInlineSummary(e){return e?.dimText?Q.createElement(ne,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:o}){if(e)return{symbolColor:ar.YELLOW,symbol:Pe.arrowRight};if(t)return{symbolColor:ar.RED,symbol:Pe.square};if(n)return{symbolColor:ur,symbol:"✻"};if(r&&o){const e=vE(o),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?fr.SUCCESS:fr.WARNING,symbol:Pe.square}}return{symbolColor:pr.BG,symbol:Pe.square}}function renderToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:o,expandedOutput:s,expandKey:i,output:a}){if(e){const e=a?Math.max(1,Math.round(a.length/500)):1;return Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ur},`Thought for ${e} second${1!==e?"s":""}`," "),!s&&Q.createElement(BracketWrap,{color:ar.DIM},`${i}+o to expand`))}if(t)return Q.createElement(Q.Fragment,null,Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG,bold:!0},CT)),Q.createElement(ne,null," ","Using your taste"," ",n?"package of ":"packages",n&&Q.createElement(ne,{bold:!0},n)));let l=r;return"READ[n]"===r&&o&&(l=`READ[${Number(o[1])}]`),Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:pr.BG,color:pr.FG,bold:!0},`${bT}${l}${bT}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:o}){const s=`${formatTime2(r)} | ${formatTokens(o)}`;return"running"===e?Q.createElement(ne,{color:ar.GRAY},"Running (",s,")"):"interrupted"===e||"Interrupted by user"===n?Q.createElement(ne,{color:ar.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?Q.createElement(ne,{color:ar.RED,wrap:"wrap"},n," (",s,")"):Q.createElement(Q.Fragment,null,Q.createElement(ne,{wrap:"wrap"},"Done"),Q.createElement(ne,{color:ar.GRAY}," (",s,")"))}function getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}){if(n)return{text:e,isTruncated:!1,remainingLines:0,truncationMsg:null};const o=dedentText(e),{text:s,isTruncated:i,remainingLines:a}=truncateToVisualLines({output:o,maxVisualLines:"Question"===t?zo:Bo,maxChars:"Question"===t?1/0:Ko}),l=i&&"Question"!==t;return{text:s,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?Q.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:ar.DIM}):Q.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:ar.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:o,isTruncated:s,truncationMsg:i}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return s?Q.createElement(Q.Fragment,null,o,"\n",i):o}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:o,expandKey:s}){const i=n?void 0:Ho,{diffContent:a,isTruncated:l,totalLines:u}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue,newValue:t.newValue,startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i});return Q.createElement(te,{flexDirection:"column"},a,l&&Q.createElement(te,{marginTop:1},Q.createElement(BracketedText,{text:`… (${u-Ho} more lines) [${s}+o to expand]`,color:ar.DIM})),r&&o&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.RED,wrap:"wrap"},o)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const o=t.content;if(!o)return Q.createElement(ne,{color:ar.GRAY},"Created"," ",Q.createElement(ne,{color:ar.WHITE,bold:!0},e)," ","(empty file)");const s=o.endsWith("\n")?o.slice(0,-1).split("\n"):o.split("\n"),i="number"==typeof t.totalLines?t.totalLines:s.length,a=n?void 0:Wo,l=void 0!==a&&i>a,u=l?s.slice(0,a):s,d=String(i).length;return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.GRAY},"Created"," ",Q.createElement(ne,{color:ar.WHITE,bold:!0},e)," ","(",i," line",1!==i?"s":"",")"),Q.createElement(te,{marginTop:1,flexDirection:"column"},u.map((e,t)=>Q.createElement(te,{key:t,width:"100%",backgroundColor:mr.ADDED_BG},Q.createElement(ne,{color:mr.ADDED_TEXT}," "+String(t+1).padStart(d)),Q.createElement(ne,{color:mr.LINE_NUM},W_),Q.createElement(ne,{color:mr.ADDED_TEXT,wrap:"truncate-end"},e.replace(/\s/g," "))))),l&&void 0!==a&&Q.createElement(te,{marginTop:1},Q.createElement(BracketedText,{text:`… (${i-a} more lines) [${r}+o to expand]`,color:ar.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:o,output:s,expandedOutput:i,isPermissionDenied:a,input:l,hasError:u,name:d,expandKey:m,showTreeConnector:g,closesFrame:h}){if(e)return formatTodosForDisplay(s);if(t)return i?Q.createElement(te,{width:"100%",flexDirection:"column"},Q.createElement(ne,null," "),Q.createElement(ne,{color:ur,wrap:"wrap",italic:!0},s)):null;const f=h?ST:ET;if(n&&o?.oldValue&&o?.newValue){const e=renderEditFileDiff({input:l,metadata:o,expandedOutput:i,isPermissionDenied:a,output:s,expandKey:m});return g?Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},f," "),e):e}if(r&&o&&"content"in o){const e=renderWriteFileContent({input:l,metadata:o,expandedOutput:i,expandKey:m});return g?Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},f," "),e):e}return g?renderTextWithLongConnector({output:s,name:d,expandedOutput:i,expandKey:m,hasError:u,closesFrame:h}):Q.createElement(te,{width:"100%"},Q.createElement(ne,{color:u?ar.RED:"",wrap:"wrap"},renderTruncatedOutput({output:s,name:d,expandedOutput:i,expandKey:m})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:o,closesFrame:s}){const{text:i,isTruncated:a,truncationMsg:l}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),u=o?ar.RED:void 0,d=buildTreeConnectors(i,{isTruncated:a,closesFrame:s}),m=s?ST:ET;return Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(te,{columnGap:1,width:"100%"},Q.createElement(ne,{color:Ar},d),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:u,wrap:"wrap"},i))),a&&Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},m," "),l))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,u="EDIT"===e,d="WRITE"===e,m="READ"===e||e.startsWith("READ[")&&e.endsWith("]"),g=!0===s?.isTasteFile,h=s?.tasteCategory,f=!0===s?.permissionDenied,y=!a&&!l&&!g,w="ctrl",S=!0===s?.isAgent,E=computeDisplayInput({input:t,isAgent:S,isShell:"SHELL"===e,expandedOutput:i}),C=!a&&E&&!g,v=s?.status,k=s?.tokensUsed||0,T="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0,_=m?parseReadSummaryLine(n):null,x=m?getReadToolInlineSummary({name:e,summaryMatch:_}):null,A=Boolean(n&&!g&&!S&&(!m||o)),{symbolColor:P,symbol:I}=resolveSymbol({isPending:r,hasError:o,isThinking:a,isTodos:l,output:n}),N=s?.preHookLines,R=s?.postHookLines,M=Boolean(N?.length),L=Boolean(R?.length),$=Boolean(s?.hookOutcome),D=r&&!S&&!$,O=!$&&!D,F=A&&!L&&!$&&!D,q=M&&!A&&!L&&!$&&!D;return Q.createElement(te,null,a&&Q.createElement(ne,{color:P},I),Q.createElement(te,{flexDirection:"column",marginLeft:a?1:0},Q.createElement(te,null,renderToolHeader({isThinking:a,isTasteFile:g,tasteCategory:h,name:e,summaryMatch:_,expandedOutput:i,expandKey:w}),C&&Q.createElement(ne,null," ",formatToolInput({input:E,isShell:"SHELL"===e})),renderReadToolInlineSummary(x)),S&&("running"===v||n)&&Q.createElement(te,{columnGap:1,marginLeft:y?1:0},y&&Q.createElement(ne,{color:Ar},ST," "),renderAgentStatus({agentStatus:v,hasError:o,output:n,elapsedSeconds:T,tokensUsed:k})),renderHookLines({lines:N,showTreeConnector:y,closesFrame:q}),A&&Q.createElement(te,{marginLeft:y?1:0},renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,isWriteFile:d,metadata:s,output:n,expandedOutput:i,isPermissionDenied:f,input:t,hasError:o,name:e,expandKey:w,showTreeConnector:y,closesFrame:F})),renderHookLines({lines:R,showTreeConnector:y,closesFrame:O}),renderHookOutcome({outcome:s?.hookOutcome,showTreeConnector:y}),D&&Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,{color:Ar},ST," "),Q.createElement(ne,{color:ar.GRAY},"Processing…"))))}function renderHookLines({lines:e,showTreeConnector:t,closesFrame:n=!1}){if(!e||0===e.length)return null;const r=e.length-1;return Q.createElement(te,{flexDirection:"column",marginLeft:t?1:0},e.map((e,t)=>{const o=n&&t===r?ST:ET;return Q.createElement(te,{key:t,columnGap:1},Q.createElement(ne,{color:Ar},o),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.DIM},e)))}))}function renderHookOutcome({outcome:e,showTreeConnector:t}){if(!e)return null;const n="stop"===e.kind?ar.YELLOW:ar.RED;return Q.createElement(te,{columnGap:1,marginLeft:t?1:0},Q.createElement(ne,{color:Ar},ST),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:n},e.text)))}__name(computeSimilarity,"computeSimilarity"),__name(buildSimilarityMatrix,"buildSimilarityMatrix"),__name(collectSimilarityCandidates,"collectSimilarityCandidates"),__name(buildLinePairs,"buildLinePairs"),__name(groupAdjacentChanges,"groupAdjacentChanges"),__name(renderWordSegments,"renderWordSegments"),__name(renderContextLine,"renderContextLine"),__name(renderContextGroup,"renderContextGroup"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(formatToolInput,"formatToolInput"),__name(parseReadSummaryLine,"parseReadSummaryLine"),__name(getReadToolInlineSummary,"getReadToolInlineSummary"),__name(renderReadToolInlineSummary,"renderReadToolInlineSummary"),__name(resolveSymbol,"resolveSymbol"),__name(renderToolHeader,"renderToolHeader"),__name(renderAgentStatus,"renderAgentStatus"),__name(getTruncatedOutputParts,"getTruncatedOutputParts"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderWriteFileContent,"renderWriteFileContent"),__name(renderOutputContent,"renderOutputContent"),__name(renderTextWithLongConnector,"renderTextWithLongConnector"),__name(ToolMessage,"ToolMessage"),__name(renderHookLines,"renderHookLines"),__name(renderHookOutcome,"renderHookOutcome");var G_=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[o]=Y(0),[s,i]=Y(1);X(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&i(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session [shift+tab]",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],l=__name(e=>{const t=a.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),u=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),d=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),m=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,paddingX:1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0,color:ar.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&Q.createElement(te,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:s}).diffContent),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0},"Do you want to ",u()," ",Q.createElement(ne,{color:ar.CYAN},d()),"?")),Q.createElement(mt,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:o,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(ne,{color:t?ar.CYAN:ar.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?ar.CYAN:ar.WHITE,bold:!0},"shift+tab")):e.includes("(")?Q.createElement(Q.Fragment,null,e.split("(")[0],Q.createElement(ne,{color:ar.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Ot(),wn(),Rr();var V_=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=Y(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"),i=__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(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.GRAY,paddingX:1,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0,color:ar.YELLOW},"Execute Shell Command")),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",Q.createElement(ne,{color:ar.CYAN},i()),".")),e.workingDirectory&&Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.GRAY},"Working directory: ",e.workingDirectory)),e.description&&Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM,italic:!0},e.description)),Q.createElement(mt,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(ne,{color:t?ar.CYAN:ar.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?ar.CYAN:ar.WHITE,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function getKillShellRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}function getFileAction2(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:o,permissionMode:s,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const u="no"!==e.value;t(u),n(null),u?(o(a),"standard"===s&&i("Use shift+tab to enable auto-accept")):o(l)}__name(getKillShellRequest,"getKillShellRequest"),__name(getFileAction2,"getFileAction"),__name(handlePermissionResponse,"handlePermissionResponse");var Q_=K(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:o,showHintMessage:s,handleToggleAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:o,setStatus:r,permissionMode:t,showHintMessage:s};if("shell_command"===e.toolName){const t=e.params;return Q.createElement(te,{marginY:1},Q.createElement(V_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"}),onToggleAutoAccept:i}))}if("kill_shell"===e.toolName){const t=getKillShellRequest(e.params);return Q.createElement(te,{marginY:1},Q.createElement(V_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"}),onToggleAutoAccept:i}))}const l=e.params,u={action:getFileAction2(e.toolName),filePath:String(l.filePath??l.file_path??l.path??l.absolutePath??l.notebook_path??"unknown"),description:`Allow ${e.toolName} operation`,oldContent:"edit_file"===e.toolName&&"string"==typeof l.oldContent?l.oldContent:void 0,newContent:"edit_file"===e.toolName&&"string"==typeof l.newContent?l.newContent:void 0};return Q.createElement(te,{marginY:1},Q.createElement(G_,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Ot(),Eb(),Ot(),Ot(),wn();var K_=Ye`
|
|
284
284
|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
|
285
285
|
░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░
|
|
286
286
|
░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░
|
|
@@ -288,8 +288,8 @@ import*as e from"path";import t,{join as n,dirname as r,parse as o,relative as s
|
|
|
288
288
|
░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░
|
|
289
289
|
░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░
|
|
290
290
|
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
|
|
291
|
-
`,
|
|
291
|
+
`,Y_="\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 J_=getMaxLineWidth(K_),X_=getMaxLineWidth(Y_),Z_=J_+1,ex=X_+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var tx=__name(e=>{const t=e??getTerminalWidth();return t>=Z_?K_:t>=ex?Y_:nx},"getResponsiveCommandLogo"),nx="⌘ CMD\n",rx=Ye`
|
|
292
292
|
░█▀▀░█▀▄▀█░█▀▄░
|
|
293
293
|
░█░░░█░▀░█░█░█░
|
|
294
294
|
░▀▀▀░▀░░░▀░▀▀░░
|
|
295
|
-
`,rx=getMaxLineWidth(nx),ox=Z_,sx=__name(e=>{const t=e??getTerminalWidth();return t>=X_?"full":t>=ox?"compact":"minimal"},"getHeaderLayout");Ot(),Rr();var ix=__name(({children:e})=>{const t=[];let n="",r=!0;const o=__name(()=>{0!==n.length&&(t.push({text:n,panel:r}),n="")},"flush");for(const t of e){const e="░"===t;0===n.length?r=e:e!==r&&(o(),r=e),n+=t}return o(),Q.createElement(ne,null,t.map((e,t)=>Q.createElement(ne,{key:t,color:e.panel?Pr.BG:Pr.TEXT},e.text)))},"CommandLogoBanner");Ot(),Rr();var ax=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:o=0,titleColor:s=ar.GRAY,dividerChar:i="─",dividerColor:a=ar.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*o),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return Q.createElement(te,{paddingLeft:o,paddingRight:o,marginBottom:1,...l},(t||n)&&Q.createElement(ne,{color:a},d),e&&Q.createElement(ne,{color:s},m),Q.createElement(ne,{color:a},f),r&&Q.createElement(ne,{color:ar.DIM},g))},"Divider");Sb(),Rr(),Ot(),Rr();var lx=[{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}],cx=__name(({onComplete:e,onExit:t})=>{const[n,r]=Y(0),[o,s]=Y(!1),i=n>=lx.length;return X(()=>{if(n>=lx.length)return;if(o)return;const e=lx[n],t=setTimeout(()=>{r(e=>Math.min(e+1,lx.length))},e.duration);return()=>clearTimeout(t)},[n,o]),se((n,o)=>{""===n||o.ctrl&&"c"===n?t?t():e():o.escape?e():i?(o.return||" "===n)&&e():" "===n?s(e=>!e):o.return&&r(e=>Math.min(e+1,lx.length))}),Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Meet Your Coding Taste")),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"Command Code learns your coding style as you work.")),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"Here's how your preferences evolve in real-time:")),Q.createElement(te,{flexDirection:"column",marginY:1},lx.slice(0,n).map((e,t)=>"user"===e.type?Q.createElement(te,{key:t},Q.createElement(ne,null,Pe.pointer," ",e.text)):Q.createElement(te,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"⎿ "),Q.createElement(ne,{color:cr.TEXT},e.text)),e.details&&Q.createElement(te,{marginLeft:3},Q.createElement(ne,{color:ar.DIM},"Saved(",e.details,")"))))),i?Q.createElement(te,{flexDirection:"column",marginY:1},Q.createElement(te,null,Q.createElement(ne,{bold:!0,color:cr.TEXT},"Demo Complete!")),Q.createElement(te,null,Q.createElement(ne,null,"Command Code will now use these preferences to generate")),Q.createElement(te,null,Q.createElement(ne,null,"better suggestions tailored to your coding style. The")),Q.createElement(te,null,Q.createElement(ne,null,"more you code, the smarter it gets.")),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press Enter to get started →"))):Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(o?" (paused)":""))))},"TasteDemoComponent"),ux=__name(({onClose:e,onExit:t})=>{const[n,r]=Y(Kk.getEvents()),[o,s]=Y(0);se((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),X(()=>{const e=__name(()=>{r(Kk.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return Kk.on("new-event",e),Kk.on("cleared",t),()=>{Kk.off("new-event",e),Kk.off("cleared",t)}},[]),X(()=>{const e=__name(()=>{yb(),s(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=Z(()=>n.find(e=>"analyzing"===e.type),[n]),l=Z(()=>n.find(e=>"analyzed"===e.type),[n]),u=Z(()=>n.find(e=>"no_learnings"===e.type),[n]),d=Z(()=>n.find(e=>"learned"===e.type||"refactored"===e.type),[n]),m=u?n.indexOf(u):1/0,g=d?n.indexOf(d):1/0,h=!!u&&m<g,f=!!a||!!l||h,y=Z(()=>n.filter(e=>"analyzing"!==e.type&&"analyzed"!==e.type&&"no_learnings"!==e.type),[n]),w=Z(()=>[...y].reverse(),[y]),S=__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 i={learned:"LEARNED",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),E=__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"),C=__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"),v=Z(()=>(process.stdout.rows??24)-1,[o]);return Q.createElement(te,{flexDirection:"column",width:"100%",height:v,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ix,null,ex())),Q.createElement(ax,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),Q.createElement(te,{flexDirection:"column"},0===n.length?Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(te,null,Q.createElement(ne,null,"Start using Command Code and it will begin recording your coding taste.")),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"Your preferences, patterns, and style will appear here in real-time."))),Q.createElement(le,{count:2}),Q.createElement(ax,{title:"DEMO",titleColor:"white",subPrefix:!0}),Q.createElement(cx,{onComplete:()=>{e()},onExit:t})):Q.createElement(te,{flexDirection:"column"},y.length>0&&Q.createElement(te,{flexDirection:"column",gap:1},w.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:o}=S(e.message),s="moved"===t?C(e.details):null,i="upgraded"===t||"downgraded"===t?E(r):null,a=s?.fullPath??e.details;let l=Q.createElement(Q.Fragment,null,Q.createElement(ne,null," ",r),o&&Q.createElement(ne,{color:ar.DIM}," ","(",o,")"));return i&&(l=Q.createElement(Q.Fragment,null,Q.createElement(ne,null," ",i.text," ("),Q.createElement(ne,{color:ar.DIM},"confidence:"," "),Q.createElement(ne,{color:ar.DIM},i.oldPercent,"%"),Q.createElement(ne,null," ",Pe.arrowRight," "),Q.createElement(ne,{color:i.diff>0?ar.GREEN:ar.RED},i.newPercent,"%"),Q.createElement(ne,null,")"))),s&&(l=Q.createElement(Q.Fragment,null,Q.createElement(ne,null," ",s.category," package ("),Q.createElement(ne,{color:ar.DIM},s.oldPath),Q.createElement(ne,null," ",Pe.arrowRight," ",s.newPath),Q.createElement(ne,null,")"))),Q.createElement(te,{key:e.id},Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG,bold:!0},`${ET}${n}${ET}`)),a&&Q.createElement(ne,{color:ar.DIM}," ","(",a,")")),Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM},"⎿"," "),l)))}return Q.createElement(te,{key:e.id},Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",e.message))})),f&&Q.createElement(te,{flexDirection:"column",marginTop:y.length>0?1:0},a&&Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",a.message)),l&&Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",l.message)),h&&u&&Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",u.message))))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return Q.createElement(ux,{onClose:()=>{yb(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ot(),Rr(),Ot(),Rr(),Sb(),Jr();var dx=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=Y(!1),[s,i]=Y(!0);X(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),se((t,n)=>{if(!n.return&&" "!==t)return n.escape?(yb(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?Q.createElement(te,{key:n,borderStyle:"single",borderColor:ar.BLUE,padding:1,flexDirection:"column"},Q.createElement(ne,{color:ar.BLUE,bold:!0},"Taste Settings"),Q.createElement(ne,{color:ar.DIM},"Loading configuration...")):Q.createElement(te,{key:n,borderStyle:"single",borderColor:ar.GRAY,padding:1,flexDirection:"column"},Q.createElement(ne,{bold:!0},"Taste Learning"),Q.createElement(ne,{color:ar.DIM},"Configure taste learning preferences for this project"),Q.createElement(te,{marginTop:1}),Q.createElement(te,{justifyContent:"space-between"},Q.createElement(ne,null,"Taste learning",Q.createElement(ne,{color:ar.DIM}," - Learn from your interactions")),Q.createElement(ne,{color:r?ar.GREEN:ar.GRAY},r?"enabled":"disabled")),Q.createElement(te,{marginTop:1}),Q.createElement(ne,{color:ar.DIM},"Taste data stored in .commandcode/taste/taste.md"),Q.createElement(ne,{color:ar.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return Q.createElement(Q.Fragment,null,Q.createElement(R_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"Press Esc to return to conversation")),Q.createElement(dx,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}function fuzzyMatch(e,t){let n=0;for(const r of e)if(r===t[n]&&(n++,n===t.length))return!0;return!1}function fuzzyScore(e,t){let n=0;for(const r of e)fuzzyMatch(r.text.toLowerCase(),t)&&(n+=r.weight);return n}function fuzzyFilter(e,t,n){if(!t.trim())return e;const r=t.toLowerCase().split("");return e.map(e=>({item:e,score:fuzzyScore(n(e),r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score).map(({item:e})=>e)}__name(TasteConfigView,"TasteConfigView"),Ot(),Ot(),wn(),Ot(),__name(fuzzyMatch,"fuzzyMatch"),__name(fuzzyScore,"fuzzyScore"),__name(fuzzyFilter,"fuzzyFilter"),Sb(),Rr(),Ot(),Rr();var mx=__name(({query:e,resultCount:t,placeholder:n="Type to search..."})=>Q.createElement(te,{width:"100%"},Q.createElement(ne,{color:ar.GRAY},Pe.pointerSmall," "),Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},e||n),e&&void 0!==t&&Q.createElement(ne,{dimColor:!0}," (",t," found)")),"SearchInput");function useListNavigation({items:e,onSelect:t,onCancel:n,validate:r,initialIndex:o=0,searchQuery:s,onSearchChange:i}){const[a,l]=Y(o),[u,d]=Y(null);X(()=>{s||l(o)},[o,s]);const m=e.length-1,g=__name(e=>{i(e),l(0)},"updateSearch");return se((o,i)=>{if(i.escape&&s)g("");else if(i.escape)n();else if(i.backspace||i.delete)g(s.slice(0,-1));else if(0!==e.length){if(i.upArrow)return d(null),void l(e=>e>0?e-1:m);if(i.downArrow)return d(null),void l(e=>e<m?e+1:0);if(i.return){const n=e[a];if(!n)return;if(r){const e=r(n);if(e)return void d(e)}return void t(n)}!i.ctrl&&!i.meta&&!i.tab&&o&&1===o.length&&o>=" "&&g(s+o)}}),{cursor:a,error:u,setError:d}}Ot(),__name(useListNavigation,"useListNavigation"),Ot(),wn(),Rr();var px=__name(()=>Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ne,{color:lr,bold:!0},"Skills"),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"No skills found")),Q.createElement(ne,{color:ar.DIM},"Create skills in:"),Q.createElement(ne,{color:ar.DIM}," ","~/",".commandcode","/","skills","/ (user)"),Q.createElement(ne,{color:ar.DIM}," ","~/.agents/","skills","/ (user, .agents)"),Q.createElement(ne,{color:ar.DIM}," ",".commandcode","/","skills","/ (project)"),Q.createElement(ne,{color:ar.DIM}," ",".agents/","skills","/ (project, .agents)"),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press ",Q.createElement(ne,{bold:!0},"Esc")," to close"))),"SkillsConfigEmpty");Ot();var gx=__name(e=>Math.ceil(e.length/4),"estimateTokens"),hx=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),fx={user:"user settings",projectShared:"project shared",projectLocal:"project local"},yx=__name(()=>"win32"===process.platform?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===process.platform?"~/.zshrc":"~/.bashrc"),"getEditorSetupMessage");Ot(),Rr();var wx=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(te,null,Q.createElement(ne,{color:wr,bold:!0},e," "),Q.createElement(ne,{color:wr},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=hx(e.filePath);return Q.createElement(te,{key:e.filePath},Q.createElement(ne,{color:ar.GREEN},n?"▸ ":" "),Q.createElement(ne,{color:i?ar.DIM:ar.GREEN},i?"[off] ":"[on] "),Q.createElement(ne,{color:i?ar.DIM:ar.WHITE},e.label),a&&Q.createElement(ne,{color:ar.DIM}," [.agents]"),Q.createElement(ne,{color:ar.DIM}," · ~",gx(e.description)," tokens"))})),"SkillSection");Ot();var Sx=__name(e=>[{text:e.label,weight:100}],"SKILL_SEARCH_FIELDS"),Ex=__name(({onClose:e})=>{const[t,n]=Y([]),[r,o]=Y(!0),[s,i]=Y(null),[a,l]=Y(""),[u,d]=Y(new Set),[m,g]=Y(new Map),[h,f]=Y(!1),[y,w]=Y(null),S=J(!1);X(()=>{__name(async()=>{try{const e=findGitRoot(),[{global:t,project:r},o]=await Promise.all([loadAllSkillSummaries(),loadDisabledSkills({projectRoot:e})]),s=[...r.map(e=>({label:e.name,location:"project",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,location:"user",description:e.description,filePath:e.filePath}))];s.sort((e,t)=>e.location!==t.location?"project"===e.location?-1:1:e.label.localeCompare(t.label)),n(s),d(new Set(o.names)),g(new Map(o.bySkill)),f(o.noProjectRoot)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{o(!1)}},"load")()},[]);const E=Z(()=>fuzzyFilter(t.filter(e=>"project"===e.location),a,Sx),[t,a]),C=Z(()=>fuzzyFilter(t.filter(e=>"user"===e.location),a,Sx),[t,a]),v=Z(()=>[...E,...C],[E,C]),k=__name(async e=>{if(S.current)return;const t=u.has(e.label),n=m.get(e.label);if(t&&void 0!==n&&"projectLocal"!==n&&!h)return void w(`Cannot enable: "${e.label}" is disabled in ${fx[n]}. Edit that file to override.`);S.current=!0;const r=new Set(u);t&&r.delete(e.label),t||r.add(e.label),d(r),w(null);try{const n=findGitRoot(),r=await setSkillEnabled(e.label,t,{projectRoot:n}),o=new Map(m);t&&o.delete(e.label),t||o.set(e.label,r),g(o),"user"===r&&w("Saved to user settings — no project found.")}catch(e){d(u),w(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{S.current=!1}},"toggleSkill"),{cursor:T}=useListNavigation({items:v,onSelect:k,onCancel:__name(()=>{yb(),e()},"onCancel"),searchQuery:a,onSearchChange:l,initialIndex:0});if(se((t,n)=>{if(!n.tab)return;const r=v[T];r&&(async()=>{try{await ft([{file:r.filePath,line:1}]),yb(),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void i(yx());i(e instanceof Error?e.message:"Failed to open skill in editor")}})()}),r)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ne,{color:lr,bold:!0},"Skills"),Q.createElement(ne,{color:ar.DIM},"Loading skills..."));if(s)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ne,{color:ar.RED,bold:!0},"Skills"),Q.createElement(ne,{color:ar.DIM},s),Q.createElement(te,{marginTop:1}),Q.createElement(ne,{color:ar.DIM},"Press ",Q.createElement(ne,{bold:!0},"Esc")," to close"));if(0===t.length)return Q.createElement(px,null);const _=t.filter(e=>u.has(e.label)).length;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Skills"," "),Q.createElement(ne,{color:ar.DIM},t.length," skill",1===t.length?"":"s"),_>0&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:ar.YELLOW},_," off"))),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{dimColor:!0},h?"No project found — toggles will be saved to user settings.":"Toggle skills on or off for this project.")),Q.createElement(te,{marginBottom:1,flexDirection:"column",width:"100%"},Q.createElement(mx,{query:a,resultCount:a?v.length:void 0,placeholder:"Type to search skills..."})),0===v.length?Q.createElement(te,{marginY:1},Q.createElement(ne,{color:ar.GRAY},'No skills match "',a,'"')):Q.createElement(Q.Fragment,null,E.length>0&&Q.createElement(wx,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:E,baseIndex:0,cursor:T,disabled:u}),C.length>0&&Q.createElement(wx,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:C,baseIndex:E.length,cursor:T,disabled:u})),y&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.YELLOW},y)),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},a?"type to search · ↑/↓ navigate · enter to toggle · tab to edit · esc to clear":"type to search · ↑/↓ navigate · enter to toggle · tab to edit · esc to close"),Q.createElement(ne,{color:ar.DIM},"add skills:"," ",Q.createElement(ne,{color:ar.CYAN},"cmd skills add ","<owner/repo>"))))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return Q.createElement(Q.Fragment,null,Q.createElement(R_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(Ex,{onClose:()=>t(!1),staticKey:e})))}function useTerminalWidth(){const{stdout:e}=oe(),[t,n]=Y(()=>e.columns??80);return X(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function getUsageColor(e){return e>=80?ar.RED:e>=50?ar.YELLOW:ar.GREEN}function buildBlockBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e));let r=Math.round(n/100*t);n>.5&&0===r&&(r=1),n<99.5&&r===t&&(r=t-1);const o=t-r;return{filled:"█".repeat(r),empty:"░".repeat(o)}}function getStudioUsageUrl(e){const t=e?.org?.login??e?.user?.userName;return t?`https://commandcode.ai/${t}/settings/usage`:null}__name(SkillsConfigView,"SkillsConfigView"),Ot(),Ot(),Qr(),Sb(),Rr(),Ot(),__name(useTerminalWidth,"useTerminalWidth"),Ot(),Rr(),__name(getUsageColor,"getUsageColor"),__name(buildBlockBar,"buildBlockBar"),Xr(),__name(getStudioUsageUrl,"getStudioUsageUrl");var bx=__name(e=>e.replace(/^https?:\/\//,""),"stripScheme");function getProgressBarWidth({terminalWidth:e}){return e<50?Math.max(10,e-10):e<70?Math.max(15,e-15):Math.min(30,e-15)}function getDaysColor(e){if(null!==e)return e<3?ar.RED:e<7?ar.YELLOW:void 0}__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var Cx=__name(({plan:e,status:t})=>Q.createElement(te,{marginBottom:0},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:ar.BLUE,color:"#f4f4f4",bold:!0},`${ET}USAGE${ET}`)),e&&Q.createElement(Q.Fragment,null,Q.createElement(ne,null," "),Q.createElement(ne,{color:ar.GRAY},`${e.name} Plan`)),t&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:"active"===t?ar.GREEN:ar.YELLOW},t))),"UsageBadge"),vx=__name(({showRetry:e})=>Q.createElement(te,{marginTop:1},e&&Q.createElement(ne,{color:ar.DIM},Q.createElement(ne,{bold:!0},"r")," to retry · "),Q.createElement(ne,{color:ar.DIM},"Press ",Q.createElement(ne,{bold:!0},"Esc")," to close")),"UsageFooter"),kx=__name(({models:e,grandTotal:t})=>{if(0===e.length)return null;const n=e.map(e=>({...e,displayName:getModelDisplayName(e.model),costLabel:formatCredits(e.totalCost)})),r=Math.max(...n.map(e=>e.displayName.length)),o=Math.min(24,Math.max(10,r)),s=Math.max(...n.map(e=>e.costLabel.length)),i=Math.max(8,s+2);return Q.createElement(te,{flexDirection:"column",marginTop:1},n.map(({model:e,displayName:n,costLabel:r,totalCost:s})=>{const a=t>0?Math.round(s/t*100):0,l=n.length>o?n.slice(0,o-1)+"…":n;return Q.createElement(te,{key:e},Q.createElement(ne,null,l.padEnd(o+2)),Q.createElement(ne,null,r.padEnd(i)),Q.createElement(ne,{color:ar.DIM},`${a}%`))}))},"ModelBreakdownRows"),Tx=__name(({onClose:e})=>{const[t,n]=Y("loading"),[r,o]=Y(null),[s,i]=Y(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ee(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return i(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),u=Q.useRef(null);se((r,o)=>{if(o.escape&&(yb(),e()),"r"===r&&"error"===t){n("loading"),u.current?.abort();const e=new AbortController;u.current=e,l(e.signal)}}),X(()=>{const e=new AbortController;return u.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?.subscription?.data??null,m=d?getPlanInfo({planId:d.planId??""}):null;if("loading"===t)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(Cx,{plan:m,status:d?.status??null}),Q.createElement(ne,{color:ar.DIM},"Loading…"),Q.createElement(vx,null));if("error"===t)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(Cx,{plan:m,status:d?.status??null}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),Q.createElement(vx,{showRetry:!s}));if(!r)return null;const g=r.credits||r.subscription,h=getStudioUsageUrl(r.whoami);if(!g)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(Cx,{plan:m,status:d?.status??null}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"No billing data found."),h&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," Visit "),Q.createElement(Kr,{url:h,text:"Studio",color:ar.CYAN}),Q.createElement(ne,{color:ar.DIM}," ","for usage details."))),Q.createElement(vx,null));const f=r.credits?.credits,y=r.summary,w=r.modelBreakdown,S=null!=w&&w.length>0,E=Math.max(0,f?.monthlyCredits??0)+Math.max(0,f?.purchasedCredits??0)+Math.max(0,f?.freeCredits??0),C=Math.max(0,y?.totalCost??0),v=getUsagePercent({used:C,total:C+E}),k=E>0||C>0,T=d?.currentPeriodEnd?getDaysRemaining(d.currentPeriodEnd):null,_=getDaysColor(T),x=getUsageColor(v),A=buildBlockBar({percentage:v,width:a}),P=S?w.reduce((e,t)=>e+t.totalCost,0):0;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(Cx,{plan:m,status:d?.status??null})),k?Q.createElement(te,null,Q.createElement(ne,{color:x},A.filled),Q.createElement(ne,{color:wr},A.empty),Q.createElement(ne,{bold:!0,color:x},` ${Math.round(v)}% used`)):Q.createElement(ne,{color:ar.DIM},"Plan details unavailable"),k&&Q.createElement(te,null,d?.currentPeriodEnd&&Q.createElement(ne,{color:ar.DIM},"Cycle: "),Q.createElement(ne,null,formatCredits(E)),Q.createElement(ne,{color:ar.DIM}," left"),y&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,null,y.totalCount.toLocaleString()),Q.createElement(ne,{color:ar.DIM}," requests")),null!==T&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),0===T?Q.createElement(ne,{color:_},"renewal today"):Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:_},`${T} day${1===T?"":"s"}`),Q.createElement(ne,{color:ar.DIM}," to renewal")))),S&&Q.createElement(kx,{models:w,grandTotal:P}),h&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Full breakdown at "),Q.createElement(Kr,{url:h,text:bx(h),color:ar.CYAN})),Q.createElement(vx,null))},"UsageOverlay");function UsageView({staticKey:e,setShowUsageOverlay:t}){return Q.createElement(Q.Fragment,null,Q.createElement(R_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(Tx,{onClose:()=>t(!1)})))}__name(UsageView,"UsageView"),Ot(),Ot(),wn(),US(),Jr();var _x="System prompt",xx="Messages";function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&!isHiddenTranscriptMessage({message:r})&&t++,"assistant"===r.message.role&&n++;return{user:t,assistant:n}}function countToolCalls({messages:e}){let t=0,n=0;for(const r of e){if(isHiddenTranscriptMessage({message:r}))continue;const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)isHiddenTranscriptMessage({message:n})||(t+=estimateTokens(n.message));return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:hn.TIER_1_THRESHOLD,description:`Prune to last ${hn.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:hn.TIER_2_THRESHOLD,description:`Prune to last ${hn.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:hn.TIER_3_THRESHOLD,description:"Full summarization"}];let o=0;const s=r.map(r=>{const s=Math.round(r.threshold*t),i=Math.max(0,s-e);let a="upcoming";return n>=r.threshold&&(a="passed",o=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:s,description:r.description,status:a,tokensAway:i}}),i=s.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?s.map((e,t)=>t===i?{...e,status:"current"}:e):s,currentTier:o,keepRecentTokens:hn.KEEP_RECENT_TOKENS}}function getPrimaryTip({percentage:e,conversationPct:t}){return e>=90?"Tier 3 auto-compact imminent — /compact now to control what gets summarized":e>=80?"Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in":t>60&&e>40?`${t}% is conversation — /compact to reclaim tokens`:e>=50?"/compact to free space · /model to switch models":null}function getSecondaryTip({mcpToolCount:e,imageCount:t,messageCount:n,percentage:r}){return e>0&&r>30?`${e} MCP tools loaded — disconnect unused servers to save tokens`:t>0&&r>30?`${t} image${t>1?"s":""} in context — images use ~1.5k tokens each`:n>50&&r>40?`${n} messages — consider starting a new session for a fresh context`:null}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:o,imageCount:s}){if(0===n)return[];const i=getPrimaryTip({percentage:e,conversationPct:Math.min(100,Math.round(t/n*100))}),a=getSecondaryTip({mcpToolCount:r,imageCount:s,messageCount:o,percentage:e}),l=[];return i&&l.push(i),a&&l.push(a),0===l.length&&l.push("/compact to summarize and free context · /model to switch models"),l}async function collectMemoryItems(){const e=(await discoverMemoryFiles(process.cwd())).filter(e=>e.exists),t=[];for(const n of e){const e=await loadMemoryFile(n.path),r=e?estimateTokens(e):0,o=process.env.HOME??"",s=o&&n.path.startsWith(o)?`~${n.path.slice(o.length)}`:n.path;t.push({name:n.description,tokens:r,source:s})}return t}function collectBuiltInTools(){const e=[];for(const t of hk){const n=JSON.stringify(t.input_schema??{}),r=estimateTokens(`${t.name} ${t.description??""} ${n}`);e.push({name:t.name,tokens:r})}for(const t of fk){const n=estimateTokens(`${t.name} ${t.type}`);e.push({name:t.name,tokens:n})}return e}function collectMcpTools(){const e=getMcpConnectionManager().getConnectedServers(),t=[];for(const n of e)if("connected"===n.status)for(const e of n.tools){const r=JSON.stringify(e.inputSchema??{}),o=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:o,source:n.name})}return t}async function collectSkillItems(){const e=await loadAllSkillSummaries(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.global){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"user"})}return t}async function collectAgentItems(){const e=await loadAllAgents(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.personal){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"user"})}return t}function sumTokens(e){let t=0;for(const n of e)t+=n.tokens;return t}async function analyzeContext({contextEngine:e}){const t=e.getContextTokensUsed(),n=e.getSystemPromptBreakdown(),r=getConfiguredModel(),o=getContextLimit(r),s=e.getHistory(),i=countMessagesByRole({messages:s}),a=countToolCalls({messages:s}),l=countImages({messages:s}),u=estimateConversationTokens({messages:s}),d=collectBuiltInTools(),m=collectMcpTools(),[g,h,f]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),y=sumTokens(d),w=sumTokens(m),S=sumTokens(g),E=sumTokens(h),C=sumTokens(f),v=t>0,k=n?n.memory:C,T=null!==n&&Math.abs(C-n.memory)>50,_=n?n.taste:0,x=y+w+S+E,A=v?t:u+x+k+_,P=!v&&s.length>0,I=Math.min(A/o*100,100),N=Math.max(0,o-A),R=[];if(A>0){const e=n?n.systemPrompt:Math.max(0,A-u-x-k-_);if(e>0&&R.push({name:_x,tokens:e,detail:n?"identity":"identity + taste"}),k>0&&R.push({name:"Memory",tokens:k,detail:T?"memory files (modified, refreshes next request)":"memory files"}),_>0&&R.push({name:"Taste",tokens:_,detail:"taste.md"}),y>0&&R.push({name:"System tools",tokens:y,detail:`${d.length} built-in`}),w>0){const e=Array.from(new Set(m.map(e=>e.source).filter(e=>"string"==typeof e)));let t=`${m.length} tools`;e.length>3&&(t=`${e.length} servers`),e.length>=1&&e.length<=3&&(t=e.join(", ")),R.push({name:"MCP",tokens:w,detail:t})}S>0&&R.push({name:"Skills",tokens:S,detail:`${g.length} loaded`}),E>0&&R.push({name:"Subagents",tokens:E,detail:`${h.length} loaded`});const r=e+k+_+x,o=v?Math.max(0,t-r):u;o>0&&R.push({name:xx,tokens:o,detail:`${i.user} user · ${i.assistant} assistant`})}R.sort((e,t)=>e.name===_x?-1:t.name===_x||e.name===xx?1:t.name===xx?-1:t.tokens-e.tokens);const M=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:A,tokenLimit:o,percentage:I,tokensRemaining:N,isEstimated:P,model:r,breakdown:R,autoCompact:buildAutoCompactStatus({tokensUsed:A,tokenLimit:o}),stats:{messageCount:s.length,userMessages:i.user,assistantMessages:i.assistant,toolCalls:a.calls,toolResults:a.results,imageCount:l,sessionStartTime:M},tips:generateTips({percentage:I,conversationTokens:u,totalTokens:A,mcpToolCount:m.length,messageCount:s.length,imageCount:l})}}function formatK(e){if(e<1e3)return String(e);const t=e/1e3;return Number.isInteger(t)?`${t}k`:`${t.toFixed(1)}k`}function formatBreakdownValue(e){return e<1e3?String(e):`${(e/1e3).toFixed(1)}k`}function getLayoutSizes({terminalWidth:e}){const t=Math.max(20,e),n=Math.min(50,Math.max(30,Math.floor(.5*t)));return{labelWidth:16,progressBarWidth:Math.max(10,Math.min(n,t-10)),showBreakdownDetail:t>=70}}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildBlockBar({percentage:e.percentage,width:t});return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{marginBottom:1},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:ar.BLUE,color:"#f4f4f4",bold:!0},`${ET}CONTEXT${ET}`)),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:ar.GRAY},getModelDisplayName(e.model))),Q.createElement(te,null,Q.createElement(ne,{color:n},r.filled),Q.createElement(ne,{color:wr},r.empty),Q.createElement(ne,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),Q.createElement(te,null,Q.createElement(ne,null,formatK(e.tokensUsed)),Q.createElement(ne,{color:ar.GRAY},` / ${formatK(e.tokenLimit)}`),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:n},formatK(e.tokensRemaining)),Q.createElement(ne,{color:ar.GRAY}," remaining"),e.isEstimated&&Q.createElement(ne,{color:ar.DIM}," (estimated)")))}function CompactionDistance({analysis:e}){if(e.percentage<40)return null;const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const{tokensAway:n}=t;let r=ar.GRAY;return n<=5e4&&(r=ar.YELLOW),n<=2e4&&(r=ar.RED),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:r},`~${formatK(n)}`),Q.createElement(ne,{color:ar.DIM}," until auto-compact"))}function BreakdownRow({item:e,labelWidth:t,numWidth:n,showDetail:r}){return Q.createElement(te,null,Q.createElement(ne,null,e.name.padEnd(t)),Q.createElement(ne,{bold:!0},formatBreakdownValue(e.tokens).padStart(n)),Q.createElement(ne,{color:ar.GRAY}," tokens"),r&&e.detail&&Q.createElement(ne,{color:ar.DIM},` · ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,showBreakdownDetail:n}){const r=e.breakdown.filter(e=>e.tokens>0);if(0===r.length)return null;const o=Math.max(4,...r.map(e=>formatBreakdownValue(e.tokens).length));return Q.createElement(te,{flexDirection:"column",marginTop:1},r.map(e=>Q.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t,numWidth:o,showDetail:n})))}function ContextTips({tips:e}){return 0===e.length?null:Q.createElement(te,{flexDirection:"column",marginTop:1},e.map(e=>Q.createElement(te,{key:e},Q.createElement(ne,{color:ar.CYAN},Pe.pointer),Q.createElement(ne,{color:ar.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return Q.createElement(te,{flexDirection:"column",paddingTop:1},Q.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),Q.createElement(CompactionDistance,{analysis:e}),Q.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,showBreakdownDetail:t.showBreakdownDetail}),Q.createElement(ContextTips,{tips:e.tips}))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[o,s]=Y(null),[i,a]=Y(null);return X(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&s(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),se((e,t)=>{t.escape&&(yb(),r(""),n(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(R_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},i?Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Context"),Q.createElement(ne,{color:ar.DIM},i)):o?Q.createElement(ContextMessage,{analysis:o}):Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Context"),Q.createElement(ne,{color:ar.DIM},"Loading context analysis...")),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press Esc to return to conversation"))))}__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(getPrimaryTip,"getPrimaryTip"),__name(getSecondaryTip,"getSecondaryTip"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),Sb(),Ot(),Qr(),Rr(),__name(formatK,"formatK"),__name(formatBreakdownValue,"formatBreakdownValue"),__name(getLayoutSizes,"getLayoutSizes"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),Rr(),__name(ContextConfigView,"ContextConfigView"),Ot(),Ot(),wn(),Ns(),Co(),io(),Jr();var Ax="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson().version,updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkAuthStatus(),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(){try{const e=await getSelectedModel(),t=getProviderDisplayName((await loadUserConfig()).provider||null);return{id:e,displayName:getModelDisplayName(e),provider:t}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}async function getSkillsAgentsStatus(){let e=0,t=0,n=0,r=0;try{const n=await loadAllSkillSummaries();e=n.global.length,t=n.project.length}catch{}try{const e=await loadAllAgents();n=e.personal.length,r=e.project.length}catch{}return{personalSkills:e,projectSkills:t,personalAgents:n,projectAgents:r}}function execGitAsync(e){return new Promise(t=>{ve("git",e,{encoding:"utf8",cwd:process.cwd(),timeout:3e3},(e,n)=>{t(e?null:n.trim()||null)})})}async function getGitStatus2(){const e=await execGitAsync(["rev-parse","--abbrev-ref","HEAD"]);if(!e)return{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null};const[t,n]=await Promise.all([execGitAsync(["rev-parse","--show-toplevel"]),execGitAsync(["remote","get-url","origin"])]);return{branch:e,worktreePath:t,remoteUrl:n?formatRemoteUrl(n):null,remoteHttpUrl:n?buildHttpUrl(n):null}}function parseSSHUrl(e){const t=e.match(/@([^:]+):(.+?)(?:\.git)?$/);return t?.[1]&&t[2]?{host:t[1],path:t[2]}:null}function formatRemoteUrl(e){const t=parseSSHUrl(e);if(t)return t.path;const n=e.match(/\/\/[^/]+\/(.+?)(?:\.git)?$/);return n?.[1]?n[1]:e}function buildHttpUrl(e){const t=parseSSHUrl(e);if(t)return`https://${t.host}/${t.path}`;const n=e.match(/^ssh:\/\/[^@]+@([^/]+)\/(.+?)(?:\.git)?$/);return n?.[1]&&n[2]?`https://${n[1]}/${n[2]}`:/^https?:\/\//.test(e)?e.replace(/\.git$/,""):e}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}async function hasTasteMdFiles(e){if(!D(e))return!1;try{return(await I(e,{recursive:!0,encoding:"utf-8"})).some(e=>e.endsWith(".md"))}catch{return!1}}async function getTasteStatus(){const e=t.join(process.cwd(),".commandcode","taste"),n=t.join(e,"taste.md"),r=D(n),o=r||await hasTasteMdFiles(e);let s=!0;try{s=await isTasteLearningEnabled()}catch{}return{fileExists:o,filePath:r?n:e,learningEnabled:s}}function detectProxy(){const e=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy;return e?sanitizeProxyUrl(e):null}function sanitizeProxyUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString().replace(/\/$/,"")}catch{return"[malformed proxy URL]"}}function getSystemStatus(){let e,t,n,r;try{e=DT(S.platform()),t=XT(),n=ZT(),r=e_()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:S.arch(),shell:n,terminal:t,nodeVersion:process.version,ide:"N/A"!==r?r:null,proxy:detectProxy()}}async function gatherStatusData(){const e=safeSync(getVersionStatus,{current:"Unknown",updateAvailable:null}),t=safeSync(getSystemStatus,{cwd:process.cwd(),os:"Unknown",arch:S.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,o,s,i]=await Promise.all([safeAsync(getAuthStatus,{authenticated:!1,username:null}),safeAsync(getModelStatus,{id:"Unknown",displayName:"Unknown",provider:"Unknown"}),safeAsync(getTasteStatus,{fileExists:!1,filePath:"",learningEnabled:!1}),safeAsync(getSkillsAgentsStatus,{personalSkills:0,projectSkills:0,personalAgents:0,projectAgents:0}),safeAsync(getGitStatus2,{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null})]),a=safeSync(()=>getPrStatus(i.branch),null);return{version:e,auth:n,model:r,git:i,pr:a,taste:o,skillsAgents:s,system:t}}function safeSync(e,t){try{return e()}catch{return t}}async function safeAsync(e,t){try{return await e()}catch{return t}}function formatCountValue(e,t){const n=e+t;return 0===n?"None":`${n} (${e} user, ${t} project)`}function formatSystemValue({system:e}){const t=[`${e.os} ${e.arch}`];return e.ide&&t.push(e.ide),!e.terminal||e.ide&&e.ide.toLowerCase().startsWith(e.terminal.toLowerCase())||t.push(e.terminal),t.push(e.shell),t.push(`Node ${e.nodeVersion}`),t.join(" · ")}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getSkillsAgentsStatus,"getSkillsAgentsStatus"),__name(execGitAsync,"execGitAsync"),__name(getGitStatus2,"getGitStatus"),__name(parseSSHUrl,"parseSSHUrl"),__name(formatRemoteUrl,"formatRemoteUrl"),__name(buildHttpUrl,"buildHttpUrl"),__name(getPrStatus,"getPrStatus"),__name(hasTasteMdFiles,"hasTasteMdFiles"),__name(getTasteStatus,"getTasteStatus"),__name(detectProxy,"detectProxy"),__name(sanitizeProxyUrl,"sanitizeProxyUrl"),__name(getSystemStatus,"getSystemStatus"),__name(gatherStatusData,"gatherStatusData"),__name(safeSync,"safeSync"),__name(safeAsync,"safeAsync"),Ot(),wn(),vE(),Rr(),Xr(),__name(formatCountValue,"formatCountValue"),__name(formatSystemValue,"formatSystemValue");var Px=__name(({label:e,value:t,valueColor:n,dimValue:r})=>Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},`${e}:`.padEnd(14)),r?Q.createElement(ne,{dimColor:!0},t):Q.createElement(ne,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=e,n=t.version.updateAvailable?`v${t.version.current} → v${t.version.updateAvailable} available`:`v${t.version.current}`,r=`${t.model.provider} · ${t.model.displayName}`,o=t.git.branch||"N/A",s=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?Pe.tick:Pe.cross,a=t.auth.authenticated?ar.WHITE:fr.ERROR,l=t.skillsAgents.personalSkills+t.skillsAgents.projectSkills,u=t.skillsAgents.personalAgents+t.skillsAgents.projectAgents,d=t.taste.fileExists?"Active · "+(t.taste.learningEnabled?"Learning on":"Learning off"):"No taste.md";return Q.createElement(te,{flexDirection:"column",paddingX:0},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Command Code"," "),Q.createElement(ne,{dimColor:!0},n)),Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},"Visit "),Q.createElement(Kr,{url:Ax,text:Ax,color:ar.CYAN}),Q.createElement(ne,{dimColor:!0}," for usage and billing")),Q.createElement(te,{marginTop:1},Q.createElement(ne,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?Q.createElement(Q.Fragment,null,Q.createElement(Kr,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:ar.CYAN}),Q.createElement(ne,{color:a}," ",i)):t.auth.authenticated?Q.createElement(Q.Fragment,null,Q.createElement(ne,null,"Authenticated"),Q.createElement(ne,{color:a}," ",i)):Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:fr.WARNING},"Not signed in"),Q.createElement(ne,{color:a}," ",i),Q.createElement(ne,{dimColor:!0}," — run "),Q.createElement(ne,{bold:!0},"/login"))),Q.createElement(Px,{label:"Model",value:r}),Q.createElement(Px,{label:"Branch",value:o,dimValue:!t.git.branch}),s?Q.createElement(Px,{label:"Worktree",value:s}):null,t.git.remoteUrl?Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},"Repository:".padEnd(14)),Q.createElement(Kr,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:ar.CYAN}),t.pr?Q.createElement(Q.Fragment,null,Q.createElement(ne,{dimColor:!0}," · "),Q.createElement(Kr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?ar.CYAN:ar.GRAY}),Q.createElement(ne,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null):t.pr?Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},"Pull Request:".padEnd(14)),Q.createElement(Kr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?ar.CYAN:ar.GRAY}),Q.createElement(ne,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,Q.createElement(Px,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),Q.createElement(Px,{label:"Directory",value:toRelativePath(t.system.cwd)}),Q.createElement(Px,{label:"Skills",value:formatCountValue(t.skillsAgents.personalSkills,t.skillsAgents.projectSkills),dimValue:0===l}),Q.createElement(Px,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),Q.createElement(Px,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?Q.createElement(Px,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,o]=Y({phase:"loading"});return X(()=>{let e=!1;return gatherStatusData().then(t=>{e||o({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";o({phase:"error",message:n})}),()=>{e=!0}},[]),se((e,r)=>{r.escape&&(n(""),t(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(R_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},"ready"===r.phase?Q.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?Q.createElement(ne,{dimColor:!0},"Could not load status: ",r.message):Q.createElement(ne,{dimColor:!0},"Gathering status…"),Q.createElement(te,{marginTop:1},Q.createElement(ne,{dimColor:!0},"Press Esc to return to conversation"))))}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 $.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"}__name(StatusMessage,"StatusMessage"),__name(StatusConfigView,"StatusConfigView"),Ot(),Ot(),Ao(),Ot(),Ao(),__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"),Rr(),$r();var Ix=__name(({onClose:e})=>{const[t,n]=Y(""),[r,o]=Y(null),[s,i]=Y([]),[a,l]=Y(getAdditionalDirectories()),[u,d]=Y({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=Y(0);X(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),X(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__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"),f=__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");se((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&s[u.suggestionIndex]?void h(s[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[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:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),X(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,s.length]),X(()=>{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>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[s.length,a.length]);const y=s.slice(m,m+8),w=getFooterText({focusZone:u.zone});return Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.CYAN,paddingX:1,paddingY:0},Q.createElement(ne,{bold:!0,color:ar.CYAN},"Add directory to workspace"),Q.createElement(ne,{color:ar.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,{color:ar.GRAY},"Added directories"),0===a.length?Q.createElement(ne,{color:ar.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return Q.createElement(ne,{key:e,color:n?ar.YELLOW:ar.GREEN,bold:n},n?` ${Pe.pointer} `:" ",formatDirectoryForDisplay(e))})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0,color:ar.WHITE},"Path")),Q.createElement(te,null,Q.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?Pe.pointer:" "} `,prefixColor:"input"===u.zone?ar.CYAN:ar.GRAY,onChange:e=>{n(e),o(null)},onSubmit:h})),!t&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:{error:ar.RED,warning:ar.YELLOW,success:ar.GREEN}[r.tone]},r.text)),s.length>0&&Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return Q.createElement(ne,{key:e,color:r?ar.CYAN:ar.GRAY,bold:r},r?` ${Pe.pointer} `:" ",e)})),Q.createElement(te,{marginTop:1},Q.createElement(BracketedText,{text:w,color:ar.DIM})))},"AddDirModal");Ot(),Ot(),wn(),Ot(),Ot(),wn(),Rr();var Nx=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),Rx=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Mx=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=Y("idle"),[i,a]=Y(""),l=[...hk.map(e=>e.name),...fk.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void a("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Nx():Rx();await k.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),i=Array.from(e.selectedTools).map(e=>Sk[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await k.writeFile(s,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");se((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>Sk[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return Q.createElement(te,{flexDirection:"column",gap:1},Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Name:"),Q.createElement(ne,{color:ar.GRAY},e.agentType)),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Location:"),Q.createElement(ne,{color:ar.GRAY},m)),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Tools:"),Q.createElement(ne,{color:ar.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Description"),Q.createElement(ne,{color:ar.GRAY},"(Tells ","Command Code"," when to use this agent):")),Q.createElement(ne,{color:ar.GRAY},e.ccToolDefinition),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"System Prompt:")),Q.createElement(ne,{color:ar.GRAY},e.sysPrompt),!r&&Q.createElement(te,{marginTop:1},"idle"===o&&Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.GREEN,dimColor:!0},"Press"),Q.createElement(ne,{color:ar.GREEN,bold:!0},"Enter"),Q.createElement(ne,{color:ar.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===o&&Q.createElement(ne,{color:ar.YELLOW},"Saving agent..."),"saved"===o&&Q.createElement(ne,{color:ar.GREEN},Pe.tick," ",i),"error"===o&&Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.RED},Pe.cross," Error: ",i),Q.createElement(ne,{color:ar.GRAY},"Press Enter to retry"))))},"AgentSummary");Rr();var Lx=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=Y("menu"),i=[...hk.map(e=>e.name),...fk.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>Ek[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(se((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return Q.createElement(te,{flexDirection:"column"},Q.createElement(Mx,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Press Enter to go back")));if("edit"===o)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.YELLOW},"Edit functionality coming soon..."),Q.createElement(ne,{color:ar.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 k.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return Q.createElement(te,{flexDirection:"column",gap:1},Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.RED},"Delete agent"),Q.createElement(ne,{color:ar.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),Q.createElement(te,null,Q.createElement(mt,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)})))}return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE,bold:!0},e.name),Q.createElement(te,{marginTop:1},Q.createElement(mt,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");Rr();var $x=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=Y([]),[s,i]=Y([]),[a,l]=Y([]),[u,d]=Y(!0),[m,g]=Y(!1),[h,f]=Y(null),[y,w]=Y(!1),E=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),C=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),v=__name(async(e,n)=>{try{g(!1);const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=Ke(s);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");X(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([v(E(),"personal"),v(C(),"project")]),n=Qv.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),i(t),l(n),d(!1)},"loadAgents")()},[m]);const T=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{T.push({label:e.name,value:e.filePath})}),s.forEach(e=>{T.push({label:e.name,value:e.filePath})});const _=r.length+s.length,x=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(f(e),w(!0))}},"handleAgentSelect");if(u)return Q.createElement(ne,{color:ar.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return Q.createElement(Lx,{agent:h,onBack:()=>{w(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const A=__name(({isSelected:e,label:t})=>{const n=T.find(e=>e.label===t),o=n?.value||"",i=r[0]?.filePath===o,a=s[0]?.filePath===o;return Q.createElement(te,{flexDirection:"column"},i&&r.length>0&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY,bold:!0},"User agents")),a&&s.length>0&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY,bold:!0},"Project agents")),Q.createElement(te,null,Q.createElement(ne,{color:ar.WHITE},e?">":" "),Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY}," ",t)))},"CustomItemComponent");return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Agents"),_>0?Q.createElement(ne,{color:ar.GRAY}," ","(",_," agent",_>1?"s":"",")"):Q.createElement(ne,{color:ar.GRAY}," (No custom agents)")),n&&Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{color:ar.GREEN,dimColor:!0},"Created agent: ",n)),Q.createElement(mt,{items:T,onSelect:x,indicatorComponent:()=>null,itemComponent:A}),a.length>0&&Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(ne,{color:ar.GRAY,bold:!0},"Default agents"),a.map(e=>Q.createElement(ne,{key:e.filePath,color:ar.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Create specialized subagents that Command Code can delegate to."),Q.createElement(ne,{color:ar.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ot(),wn(),Ds(),Rr(),Ot(),Ot(),wn(),Rr();var Dx=__name(({onSelect:e})=>Q.createElement(mt,{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(ne,{color:e?ar.WHITE:ar.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)}),"LocationSelector");Ot(),$r(),wn(),qr(),zr(),Rr();var Ox=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=Y(!1),[g,h]=Y(!1),f=ee(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]),y=ee(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(Sk).some(e=>Fe(e)===Fe(t))||Object.keys(Sk).some(e=>Fe(e)===Fe(t)))&&Q.createElement(ne,{color:ar.RED},Pe.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Fe(t))&&Q.createElement(ne,{color:ar.RED},Pe.warning," This name is reserved. Reserved names:"," ",Vv.join(", "))),Q.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Fe(t);Object.values(Sk).some(t=>Fe(t)===e)||Object.keys(Sk).some(t=>Fe(t)===e)||isReservedAgentName(e)||a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE},"Enter the system prompt for your agent:"),Q.createElement(ne,{color:ar.GRAY},"Be comprehensive for best results.")),Q.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.WHITE},"When should ","Command Code"," use this agent?"),Q.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ot(),Rr();var Fx=__name(({onSelect:e})=>Q.createElement(mt,{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(ne,{color:e?ar.WHITE:ar.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)}),"MethodSelector");Ot(),$r(),Ot(),wb(),Rr();var qx=["·","○","◇","☆","✧","☆","◇","○","⌘"],jx=[12,5,4,4,4,4,4,5,16],Ux=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<jx.length;e++)if(n+=jx[e],t<n)return qx[e];const r=t-58;n=0;for(let e=0;e<Ux.length;e++)if(n+=Ux[e],r<n)return qx[7-e];return qx[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=Z(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<_r.length?_r[n]:xr},"getCharColor");return Q.createElement(ne,null,r.map((e,t)=>Q.createElement(ne,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return Q.createElement(ne,{color:t??lr,bold:!0},`${getWaveSymbol(e)} `)}function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var Bx=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=Y(0),[s,i]=Y(0),a=J(n);a.current=n;const l=getTerminalWidth(),[u,d]=Y(()=>l>=72?"all":l>=42?"medium":"none");X(()=>{d(e=>"all"===e?l<68?l>=42?"medium":"none":"all":"medium"===e?l>=72?"all":l<38?"none":"medium":l>=72?"all":l>=42?"medium":"none")},[l]),X(()=>{const e=setInterval(()=>{o(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const m=r%(e.length+10),g="all"===u,h="medium"===u;return gb.statusRender({width:l,layoutMode:u,status:e,frame:r}),Q.createElement(te,{width:l,height:1,paddingLeft:0,marginLeft:0},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:gr.BG,color:gr.FG}," "),Q.createElement(ne,{backgroundColor:gr.BG},Q.createElement(CMDIcon,{frame:4*r})),Q.createElement(ShimmerText,{text:e,offset:m,bg:gr.BG}),Q.createElement(ne,{backgroundColor:gr.BG,color:gr.FG}," ")),g&&Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,{bold:!0,color:ar.GRAY},"esc"),Q.createElement(ne,{color:ar.DIM},"to interrupt"),Q.createElement(ne,{color:ar.DIM},"•"),Q.createElement(ne,{color:ar.DIM},formatTime3(t)),Q.createElement(ne,{color:ar.DIM},"•"),Q.createElement(ne,{color:ar.GRAY},Pe.arrowDown),Q.createElement(ne,{color:ar.DIM},formatToken(Math.round(s)))),h&&Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM},formatToken(Math.round(s)))))},"Status");zr(),qr(),Rr();var zx=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=Y(!1),[a,l]=Y(0),[u,d]=Y(0);X(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=ee(()=>{0!==e.trim().length&&n()},[e,n]),g=ee(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return Q.createElement(te,{flexDirection:"column"},r?Q.createElement(te,null,Q.createElement(CMDIcon,{frame:u}),Q.createElement(ne,{color:ar.WHITE},"Generating agent from description...")):Q.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),o&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.RED},`${Pe.warning} ${o}`)))},"RecommendedFlow");Ot(),Rr();var Hx=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=Y(!1),[i,a]=Y(0),l=Z(()=>[...hk.map(e=>e.name),...fk.map(e=>e.name)],[]),u=Z(()=>[{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=Z(()=>{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]":"[ ]"} ${Sk[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 se((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?g.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=g.length?0:t});else if(l.return||" "===e){const e=g[i];if(e){const i=d[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(s(!o),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),Q.createElement(te,{flexDirection:"column"},m.map((e,t)=>{const n=g.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return Q.createElement(te,{key:`divider-${t}`},Q.createElement(ne,{color:ar.GRAY}," ",e.label));if("spacer"===e.type)return Q.createElement(te,{key:`spacer-${t}`,height:1});if("label"===e.type)return Q.createElement(te,{key:`label-${t}`},Q.createElement(ne,{color:ar.GRAY}," ",e.label));const o="continue"===e.type;return Q.createElement(te,{key:`item-${t}`},Q.createElement(ne,{color:r?ar.WHITE:ar.GRAY,bold:o&&r},r?">":" "," ",e.label))}),Q.createElement(te,{marginTop:1},e.size===l.length&&Q.createElement(ne,{color:ar.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&Q.createElement(ne,{color:ar.GRAY},e.size," tools selected"),0===e.size&&Q.createElement(ne,{color:ar.GRAY},"No tools selected")))},"ToolsSelector");ao(),fS(),sS(),Rs(),vb(),Jr();var Wx=__name(({onComplete:e})=>{const[t,n]=Y("location"),[r,o]=Y(!1),[s,i]=Y(null),[a,l]=Y("agentType"),u=Z(()=>[...hk.map(e=>e.name),...fk.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=Y(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[Ut.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[Ut.OAUTH_TOKEN]=`Bearer ${r}`,s&&(a[Ut.OAUTH_PROVIDER]=s));const l=getApiBaseUrl(),u=new jw({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:Bt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:Fe(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof bs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/settings/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Fe(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),C=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),v=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__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(te,{flexDirection:"column",gap:1},Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Create new agent"),Q.createElement(ne,{color:ar.GRAY},f())),Q.createElement(te,null,"location"===t&&Q.createElement(Dx,{onSelect:y}),"method"===t&&Q.createElement(Fx,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&Q.createElement(zx,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:S}),"configuration"===t&&"manual"===m.method&&Q.createElement(te,{flexDirection:"column",gap:1},Q.createElement(Ox,{step:a,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:C,onCCToolDefinitionSubmit:v})),"tools"===t&&Q.createElement(Hx,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&Q.createElement(Mx,{config:m,onSaveComplete:h})))},"AgentNew");Rr();var Gx=__name(({onCancel:e})=>{const[t,n]=Y(null),[r,o]=Y(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return se((t,n)=>{n.escape&&e()}),Q.createElement(te,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:ar.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&Q.createElement($x,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&Q.createElement(Wx,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");Rr(),Ot(),Jr(),Rr();var Vx=[{label:"Compact Normal (default)",value:"default",description:"Summarize session when context limit reached."},{label:"Compact Fast",value:"fast",description:"Fast tiered compaction. Higher quality, uses more tokens."}],Qx=__name(({onSelect:e,onCancel:t})=>{const[n,r]=Y(null);X(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(se((e,n)=>{n.escape&&t()}),null===n)return null;const s=Vx.findIndex(e=>e.value===n);return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Select a compact mode to compact sessions")),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"Choose how Command Code handles automatic context compaction.")),Q.createElement(mt,{items:Vx,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=Vx.find(e=>e.label===t),o=r?.value===n,s=Vx.findIndex(e=>e.label===t);return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:e?ar.CYAN:o?ar.GREEN:ar.WHITE},` ${s+1}. ${r?.label??t}`),o&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick)),Q.createElement(ne,{color:ar.DIM},` ${r?.description??""}`))}}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to cancel")))},"CompactModeSelector");Ot(),Rr(),Ot(),$r(),wn(),qr(),Bn(),Ot();var Kx=n(E(),"commandcode-images"),Yx={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{D(Kx)||j(Kx,{recursive:!0});const r=Yx[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(Kx,o),i=Buffer.from(e.data,"base64");return U(s,i),s}catch{return null}}function stripInputAfterSuffix(e,t){return t&&e.endsWith(t)?e.slice(0,e.length-t.length):e}function extractAppendedChunk(e,t,n){const r=t+n;return e.length>=r.length&&e.startsWith(r)?e.slice(r.length):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:i,setInitialCursor:a}=e,l=ee((e,t,n="")=>{o(t=>[...t,e]),r(t+n),a(t.length),i()},[o,r,a,i]),u=J(!1),d=J(""),m=J(null),g=J(""),h=J(""),f=ee(async(e,t,o)=>{let u=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const d=await detectDroppedImageFile(u);if(d)return void l(d,t,o);const m=await detectClipboardImage();if(m)return void l(m,t,o);let g=u;if(0===g.length){const e=await detectClipboardText();g=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(!g&&!o)return;if(!g)return r(t+o),a(t.length),void i();if(g.length>300){const e=t+`[Text#${n.length+1}]`;return s(e=>[...e,g]),r(e+o),a(e.length),void i()}const h=t+g;r(h+o),a(h.length),i()},[l,n.length,s,r,a,i]),y=ee(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(async()=>{if(u.current){const e=d.current,t=g.current,n=h.current;d.current="",g.current="",h.current="",u.current=!1,m.current=null,e?await f(e,t,n):n&&await f("",t,n)}},500)},[f]);return{handlePaste:ee(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return u.current&&(u.current=!1,d.current="",g.current="",h.current="",m.current&&(clearTimeout(m.current),m.current=null)),await f(n.pastedContent??n.cleanedContent,n.textBeforePaste??"",n.textAfterPaste??""),!0;if(n.isPasteStart&&!u.current){u.current=!0;const e=n.textBeforePaste??t,r=t.slice(e.length);g.current=e,h.current=r;const o=n.pastedContent??n.cleanedContent;return d.current=stripInputAfterSuffix(o,r),y(),!0}if(u.current&&!n.isPasteEnd){const e=g.current,t=h.current;if(void 0!==n.pastedContent)d.current=stripInputAfterSuffix(n.pastedContent,t);else if(n.cleanedContent){const r=extractAppendedChunk(n.cleanedContent,e,t);d.current=null!==r?d.current+r:accumulateDelta(n.cleanedContent,d.current,e)}return y(),!0}if(u.current&&n.isPasteEnd){m.current&&(clearTimeout(m.current),m.current=null);const e=g.current,t=h.current,r=n.textAfterPaste??"";let o=n.cleanedContent??"";if(r&&o.endsWith(r)&&(o=o.slice(0,o.length-r.length)),void 0!==n.pastedContent)d.current=stripInputAfterSuffix(n.pastedContent,t);else if(o){const n=extractAppendedChunk(o,e,t);d.current=null!==n?d.current+n:accumulateDelta(o,d.current,e)}const s=d.current,i=e,a=r||t;return d.current="",g.current="",h.current="",u.current=!1,await f(s,i,a),!0}if(n.isPasteEnd&&!n.isPasteStart&&!u.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return l(e,t),!0}return!1},[t,f,y,l]),resetPasteState:ee(()=>{u.current=!1,d.current="",g.current="",h.current="",m.current&&(clearTimeout(m.current),m.current=null)},[]),isPasting:ee(()=>u.current,[])}}__name(saveTempImage,"saveTempImage"),er(),ao(),Ot(),zr(),qr(),__name(stripInputAfterSuffix,"stripInputAfterSuffix"),__name(extractAppendedChunk,"extractAppendedChunk"),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),zr(),Ot(),Ot();var Jx=["code --wait","cursor --wait","nano"],Xx=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return Xx.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 Se(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of Jx)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var Zx=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 Zx;t=ensureWaitFlag(t);const r=n(E(),`commandcode-${Date.now()}.md`);return await _(r,e),new Promise((e,n)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],i=o.slice(1),a=be(s,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await A(r,"utf-8");await P(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await P(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=Y(!1),[l,u]=Y(null),d=ee(async()=>{if(!i){a(!0),u(null);try{let i=e.replace(/\n+$/,"");r.forEach((e,t)=>{const n=`[Text#${t+1}]`;i.includes(n)&&(i=i.replace(n,e))});const a=await openInEditor2(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){u(e instanceof Zx?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{a(!1)}}},[e,t,n,r,o,s,i]),m=ee(()=>{u(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:m}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),Ot();var eA=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=Y(null),o=J(!1);return X(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,xT().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=nt(),r=n(e,".gitignore");if(D(r))try{const e=F(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}Rr(),Ot(),Rr(),__name(loadGitignore,"loadGitignore");var tA=__name(({onSelectFile:e,onClose:t,searchQuery:o=""})=>{const[i,l]=Y(process.cwd()),[u,d]=Y([]),[m,g]=Y(0),[h,f]=Y(0),y=o.trim()?15:10,w=ee((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const o=n(t,e);try{const e=B(o),i=[];return e.forEach(e=>{const a=n(o,e);try{const e=z(a),n=s(t,a);if(r.ignores(n))return;i.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}),i.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i.slice(0,50)}catch{}}if(e.includes("/")){const o=e.split("/"),i=o.pop()||"",a=n(t,o.join("/"));try{const e=B(a),o=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=z(i),n=s(t,i);if(r.ignores(n))return;o.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),o.slice(0,50)}catch{}}const o=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{B(e).forEach(u=>{const d=n(e,u);try{const e=z(d),n=s(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&o.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&a(d,l+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),o.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),o=n===i,s=r===i;if(o&&!s)return-1;if(!o&&s)return 1;const a=n.split("/").pop()||"",l=r.split("/").pop()||"",u=a.includes(i),d=l.includes(i);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,g=t.name.split("/").length;return m!==g?m-g:e.name.localeCompare(t.name)}),o.slice(0,50)},[]),S=ee(e=>{try{const t=B(e),o=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&o.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=z(r),n=s(i,r);if(a.ignores(n))return;o.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(o),g(0),f(0)}catch{}},[]);X(()=>{if(o.trim()){const e=w(o);d(e),g(0),f(0)}else S(i)},[i,S,o,w]),se((n,r)=>{if(r.escape)t();else if(r.upArrow)g(e=>{const t=Math.max(0,e-1);return t<h&&f(t),t});else if(r.downArrow)g(e=>{const t=Math.min(u.length-1,e+1);return t>=h+y&&f(t-y+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!o.trim()&&l(a(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const E=u.slice(h,h+y);return Q.createElement(te,{flexDirection:"column",paddingLeft:1},Q.createElement(te,{marginBottom:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},o.trim()?`Searching for: "${o}"`:`Files: ${i}`),Q.createElement(ne,{color:ar.DIM},o.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?Q.createElement(ne,{color:ar.DIM},o.trim()?`No files found matching "${o}"`:"No files found in this directory"):E.map((e,t)=>{const n=h+t,r=e.name,o=n===m;return Q.createElement(ne,{key:e.path,color:o?ar.GREEN:ar.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ot(),wn(),io(),Rr(),Ot(),Rr();var nA=__name(e=>{if(e>=1e6){const t=e/1e6;return`${t%1==0?t.toFixed(0):t.toFixed(1)}M`}return`${Math.round(e/1e3)}k`},"formatTokens"),rA=__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&&e.current>=18e4)return Q.createElement(te,{paddingRight:3},Q.createElement(ne,{color:ar.DIM},"~",nA(e.current)," tokens in context · try"," "),Q.createElement(ne,{color:ar.DIM,bold:!0},"/compact"));if(n>20)return null;const r=__name(e=>e>=90?ar.RED:e>=70?ar.YELLOW:ar.DIM,"getColor"),o=t>=90?6:Math.round(t/100*6),s=6-o,i=Pe.square.repeat(o),a=Pe.squareLightShade.repeat(s),l=r(t);return Q.createElement(te,{paddingRight:3},Q.createElement(ne,{color:l},`Context left before auto-compact ${n}% `),Q.createElement(ne,{color:l},i),s>0&&Q.createElement(ne,{color:ar.DIM},a))},"ContextUsage");Ot(),as(),Rr();var oA=__name(()=>{const[e,t]=Y("continuous learning"),[n,r]=Y(!1),[o,s]=Y(!1),i=J([]),a=J(0),l=J(null),u=J(!1);X(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),s(!1),i.current=[],a.current=0,l.current&&(clearTimeout(l.current),l.current=null),void t(e.message)):u.current&&"analyzed"!==e.type?void i.current.push(e):"analyzed"===e.type?(u.current=!1,void(i.current.length>0?(a.current=0,n()):(r(!1),s(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),s(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const o="learned"===e.type||"refactored"===e.type;s(o);const u="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;l.current=setTimeout(()=>{a.current++,n()},u)},"cycleThroughNextEvent");return Kk.on("new-event",e),()=>{Kk.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?Pe.squareSmallFilled:Pe.squareSmall} TASTE`,m=9+e.length+d.length>Jo;let g=e;g=truncateString(m?{text:e,maxChars:Jo}:{text:e,maxChars:Jo-d.length-9-10});const h=o?void 0:ar.DIM;return Q.createElement(te,{paddingRight:2},!m&&Q.createElement(Q.Fragment,null,Q.createElement(BracketWrap,{color:ar.DIM},"ctrl+t"),Q.createElement(ne,{color:ar.DIM}," ")),Q.createElement(ne,{color:h},g),!m&&Q.createElement(ne,{color:cr.TEXT},d))},"LearningFeedMini");Ot(),Rr();var sA=__name(({mode:e,pendingExitKey:t})=>t?Q.createElement(ne,{color:ar.DIM},"Press Ctrl+C again to exit"):"bypass"===e?Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:ar.RED},"» permission bypass on "),Q.createElement(BracketWrap,{color:ar.DIM},"shift+tab")):"auto-accept"===e?Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:Cr},"» accept edits on "),Q.createElement(BracketWrap,{color:ar.DIM},"shift+tab")):"plan"===e?Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:br},"plan mode "),Q.createElement(BracketWrap,{color:ar.DIM},"shift+tab")):Q.createElement(ne,{color:ar.DIM},"? for shortcuts"),"ModeIndicator");Ot(),Rr(),Xr();var iA=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?ar.DIM:vr.MERGED;return Q.createElement(Q.Fragment,null,t&&Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:n},"PR "),Q.createElement(Kr,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),aA=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?Q.createElement(Q.Fragment,null,t&&Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:"connected"===e.type?ar.GREEN:ar.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),lA=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const C=e>=60;return Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r||l?Q.createElement(te,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(te,{flexDirection:"row",columnGap:0},n&&!l?Q.createElement(ne,{color:yr},t):Q.createElement(sA,{mode:r,pendingExitKey:l}),!l&&Q.createElement(iA,{prInfo:o}),!l&&Q.createElement(aA,{indicator:a})),C&&Q.createElement(te,{flexDirection:"column",alignItems:"flex-end"},s&&Q.createElement(oA,null),i&&Q.createElement(rA,{usage:i}))):Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(sA,{mode:r}),C&&s&&Q.createElement(oA,null)),Q.createElement(te,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(te,{flexDirection:"row",columnGap:0},Q.createElement(ne,{color:n?yr:ar.DIM},t),Q.createElement(iA,{prInfo:o}),Q.createElement(aA,{indicator:a})),C&&i&&Q.createElement(rA,{usage:i}))),(u||d||g&&m)&&Q.createElement(te,{flexDirection:"row",columnGap:1},u&&Q.createElement(ne,null,Pe.tick," ","Command Code"," updated:"," ",Q.createElement(ne,{color:ar.DIM},"v",u.updatedFrom),Q.createElement(ne,{color:ar.DIM}," ",Pe.arrowRight," "),Q.createElement(ne,null,"v",u.updatedTo)),!u&&d&&Q.createElement(ne,{color:ar.YELLOW,dimColor:!0},Pe.info," Update available:"," ",d.currentVersion," ",Pe.arrowRight," ",d.latestVersion),g&&m&&Q.createElement(ne,{color:ar.GREEN,dimColor:!0},Pe.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:ar.GREEN},"! for bash mode")),y&&f&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:lr},"SHARED: ",f.url," (copied to clipboard)")),w&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:w.includes("NOT SHARED")?ar.RED:lr},w)),S&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:lr},S)),E&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:ar.YELLOW},Pe.warning," ",E)))},"BottomIndicator");Ot(),as(),Rr();var cA=12,uA=__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"),dA=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),mA=__name(e=>truncateString({text:dA(e),maxChars:Yo}),"truncateMessage"),pA=__name(e=>e.title?dA(e.title):mA(e.firstMessage),"getSessionSummary"),gA=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=Y([]),[o,s]=Y(0),[i,a]=Y(0),[l,u]=Y(!0),[d,m]=Y(!1),[g]=Y(()=>getCurrentGitBranch());X(()=>{__name(async()=>{u(!0);const e=await rk.listSessions();r(e),u(!1)},"loadSessions")()},[]);const h=d&&g?n.filter(e=>e.gitBranch===g):n;if(se((n,r)=>{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),s(0),void a(0)):void(r.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?s(e=>{const t=Math.min(h.length-1,e+1);return t>=i+cA&&a(t-cA+1),t}):r.return&&h.length>0&&o<h.length&&e(h[o].id));t()}),l)return Q.createElement(te,{flexDirection:"column",paddingLeft:2},Q.createElement(ne,{color:ar.GRAY},"Loading sessions..."));if(0===h.length)return Q.createElement(te,{flexDirection:"column",paddingLeft:2},Q.createElement(ne,{color:ar.GRAY},d&&g?`No sessions found for branch "${g}"`:"No previous sessions found"),Q.createElement(ne,{color:ar.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const f=h.slice(i,i+cA);return Q.createElement(te,{flexDirection:"column",paddingLeft:1,width:"100%"},Q.createElement(ne,{color:ar.CYAN,bold:!0},"Resume Session"),Q.createElement(te,{marginTop:1}),Q.createElement(te,{columnGap:2,marginBottom:1},Q.createElement(te,{width:5},Q.createElement(ne,{color:ar.GRAY}," ")),Q.createElement(te,{width:13},Q.createElement(ne,{color:ar.GRAY},"Modified")),Q.createElement(te,{width:20},Q.createElement(ne,{color:ar.GRAY},"Git Branch")),Q.createElement(te,{width:11},Q.createElement(ne,{color:ar.GRAY},"# Messages")),Q.createElement(te,null,Q.createElement(ne,{color:ar.GRAY},"Summary"))),Q.createElement(te,{columnGap:2},Q.createElement(te,{flexDirection:"column",width:5},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`sel-${n}`,color:o===n?ar.WHITE:ar.GRAY},o===n?`${Pe.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(te,{flexDirection:"column",width:13},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`mod-${e.id}`,color:o===n?ar.WHITE:ar.GRAY},uA(e.lastModified))})),Q.createElement(te,{flexDirection:"column",width:20},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`branch-${e.id}`,color:o===n?ar.WHITE:ar.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(te,{flexDirection:"column",width:11},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`msg-${e.id}`,color:o===n?ar.WHITE:ar.GRAY},e.messageCount)})),Q.createElement(te,{flexDirection:"column"},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`summary-${e.id}`,color:o===n?ar.WHITE:ar.GRAY,wrap:"truncate-end"},pA(e))}))),Q.createElement(te,{marginTop:1}),h.length>cA&&Q.createElement(ne,{color:ar.DIM},"Showing ",i+1,"–",Math.min(i+cA,h.length)," ","of ",h.length,i>0?" · ↑ more":"",i+cA<h.length?" · ↓ more":""),Q.createElement(ne,{color:ar.DIM},"↑↓ navigate · Enter select · ctrl+b ",d?`[branch: ${g??"unknown"}]`:"branch filter"," · ESC cancel"))},"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,i=e+(r.length>0?1:0);r.length>0&&o+i>t?(n.push(r),r=[s],o=e):(r.push(s),o+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return Q.createElement(ne,null,r?" ":"",t?Q.createElement(ne,{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}),i=Math.max(1,r-(s.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return Q.createElement(te,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>Q.createElement(te,{key:r,flexDirection:"row"},Q.createElement(te,{flexShrink:0,marginRight:1},0===r&&Q.createElement(ne,{color:ar.DIM},s)),Q.createElement(te,{flexDirection:"row"},e.map((e,r)=>Q.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ot(),Rr(),Ot(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),ro(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ot();var hA=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=Y(null),[s,i]=Y(!1),a=J(!1),l=J(null),u=J(n),[d,m]=Y(!1),[g,h]=Y("connected"),f=J(null),y=J(null),w=ee((e,t)=>{y.current&&(clearTimeout(y.current),y.current=null),h(e),m(!0),void 0!==t&&(y.current=setTimeout(()=>{m(!1)},t))},[]),S=ee(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),E=ee(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Rv,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=f.current;if(null===r?n&&w("connected",3e3):r!==n&&(n?w("connected",2e3):w("disconnected",5e3)),f.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),o(r)}else o(null)}catch{!0===f.current&&w("disconnected",5e3),f.current=!1,i(!1),o(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[w]);X(()=>{const e=u.current;u.current=n,e&&!n&&t&&null!==Cv()&&E(!1)},[n,t,E]),X(()=>{if(!t)return;if(null===Cv())return;let e=null,n=!1,r=0;function schedule(t){n||(e=setTimeout(()=>{tick(!1)},t))}async function tick(e){if(u.current)return void schedule(500);if(await E(e),n)return;if(l.current?.isConnected)return r=0,void schedule(500);r+=1;const t=Math.min(r,6);schedule(Math.min(3e4,500*2**t)+250*Math.random())}return __name(schedule,"schedule"),__name(tick,"tick"),tick(!0),()=>{n=!0,e&&clearTimeout(e),S(),l.current?.disconnect(),l.current=null}},[t,E,S]);const C=Cv(),v={visible:d,message:"connected"===g?`${C?MT[C]??"IDE":"IDE"} ${Pe.tick}`:"run /ide",type:g};return{context:r,connected:s,refresh:E,connectionIndicator:v}},"useVSCodeContext");Ot();var fA=__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 i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"</ide-context>").replace(/[\u202A-\u202E\u2066-\u2069\u200B-\u200D\uFEFF]/g,"");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Ot();var yA=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),wA=__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"),SA=["","[118;5u","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var EA=__name(()=>Q.createElement(te,{flexDirection:"column",paddingLeft:1},Q.createElement(ne,{color:ar.DIM,bold:!0},"Available Shortcuts:"),Q.createElement(te,{columnGap:4},Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},"! for bash mode"),Q.createElement(ne,{color:ar.DIM},"/ for commands"),Q.createElement(ne,{color:ar.DIM},"@ for file paths"),Q.createElement(ne,{color:ar.DIM},"shift + tab to toggle auto-accept")),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},"double tap esc to clear input"),Q.createElement(ne,{color:ar.DIM},"ctrl + j / shift + ⏎ for newline"),Q.createElement(ne,{color:ar.DIM},"ctrl + g to open in editor"),Q.createElement(ne,{color:ar.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),bA=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:C,updateFailedInfo:v,currentProvider:k,showProviderInfo:T,permissionMode:_="standard",onToggleAutoAccept:x,hintMessage:A,historyManager:P,pendingExitKey:I=null,onOverlayVisibilityChange:N,onDoubleEscapeEmpty:R,onAltP:M,isProcessing:L=!1,ideContextEnabled:$=!0})=>{const[D,O]=Y(0),[F,q]=Y(!1),[j,U]=Y(!1),[B,z]=Y(!1),[H,W]=Y(!1),[G,V]=Y(""),[K,re]=Y(!1),ie=J(0),ae=J(0),[le,ce]=Y([]),[ue,de]=Y([]),[me,pe]=Y(-1),[ge,he]=Y(""),fe=J(!1),ye=J(!1),we=J(void 0),[Se,Ee]=Y(-1),[be,Ce]=Y(""),ve=J(0),{isEditorOpen:ke,editorError:Te,handleOpenInEditor:_e,clearEditorError:xe}=useExternalEditor({input:e,setInput:n,setInputKey:O,detectedContent:le,setDetectedContent:ce,onEditorClose:__name(()=>{fe.current=!1},"onEditorClose")}),{handlePaste:Ae,resetPasteState:Ie,isPasting:Ne}=useBracketedPaste({input:e,detectedContent:le,setInput:n,setDetectedImages:de,setDetectedContent:ce,incrementInputKey:__name(()=>O(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{we.current=e},"setInitialCursor")}),{context:Re,connected:Me,refresh:Le,connectionIndicator:$e}=hA({enabled:$,paused:L}),{stdout:De}=oe(),Oe=De?.columns??80,{pr:Fe}=eA();X(()=>{const e=i||H||K;N?.(e)},[i,H,K,N]);const qe=ee(()=>{de([]),pe(-1)},[]),je=ee(()=>{n(""),U(!1),W(!1),V(""),re(!1),ce([]),qe(),he(""),Ie(),Ee(-1),Ce(""),O(e=>e+1)},[n,Ie,qe]),Ue=ee(()=>{fe.current=!0;const{text:t,cursor:r}=insertTextAt(e,ve.current,"\n");n(t),we.current=r,O(e=>e+1),setTimeout(()=>{fe.current=!1},0)},[e,n]);se(async(t,r)=>{if(-1!==me&&r.leftArrow)return void pe(prevImageIndex({currentIndex:me,imageCount:ue.length}));if(-1!==me&&r.rightArrow)return void pe(nextImageIndex({currentIndex:me,imageCount:ue.length}));if(r.upArrow){if(i||H||K)return;const t=e.indexOf("\n"),r=-1===t||ve.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ue.length,selectedImageIndex:me,historyIndex:Se}))return void pe(ue.length-1);if(-1!==me&&pe(-1),0!==e.length&&-1===Se&&!r)return;const o=P?.count()??0;if(0===o)return;-1===Se&&Ce(e);const s=Math.min(Se+1,o-1);return void(s!==Se&&(Ee(s),n(P?.getAt(s)||""),O(e=>e+1)))}if(r.downArrow){if(i||H||K)return;if(-1===Se)return;const t=e.lastIndexOf("\n");if(!(-1===t||ve.current>t))return;const r=Se-1;return Ee(r),n(-1===r?be:P?.getAt(r)||""),void O(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void qe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return fe.current=!0,void _e();if(getIsExpandToolShortcut(r,t))return fe.current=!0,n(e),O(e=>e+1),void setTimeout(()=>{fe.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ne()}))return ye.current=!0,Ue(),void setTimeout(()=>{ye.current=!1},0);if(r.meta&&r.backspace)return void je();if(r.meta&&"w"===t)return fe.current=!0,void je();const o=r.ctrl&&"v"===t||SA.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e;fe.current=!0;const r=await detectClipboardImage();return r&&(de(e=>[...e,r]),n(t),O(e=>e+1)),void(fe.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return z(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==me&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ue,index:me});return de([...e]),void pe(t)}if(r.escape){if(-1!==me)return void pe(-1);if(H)return;if(K)return re(!1),n(ge),void O(e=>e+1);const t=Date.now();return t-ie.current<500?(e.length>0?je():R?.(),ie.current=0,ae.current=0):(ie.current=t,F||j||(ae.current=t)),q(!1),void U(!1)}F&&(r.backspace||r.delete)&&0===e.length&&q(!1)}});const Be=ee(async t=>{if(ke)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void M?.();const o=processBracketedPaste(t);if((o.isPasteStart||o.isPasteEnd||Ne())&&await Ae(t))return;if(fe.current)return void(fe.current=!1);-1!==Se&&Ee(-1);const s=1===t.length,l=t.slice(-1);if(s){if("?"===l&&!F)return q(!0),n(""),void O(e=>e+1);if("!"===l&&!j)return q(!1),U(!0),n(""),void O(e=>e+1)}if("/"!==l||H||"/"!==t||(W(!0),V("")),H&&!t.startsWith("/")&&(W(!1),V("")),H&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(W(!1),V("")):V(e)}"@"!==l||i||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(a(!0),u(""));const d=t.lastIndexOf("@");if(t.length<e.length&&-1!==d&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(d+1),n=!e.includes(" "),r=d>0?t[d-1]:"";n&&isPrecededByWhitespace(r)&&(a(!0),u(e))}if(i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!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),a(!1)}else u(n)}}F&&(t!==e||t.length<e.length)&&q(!1),Te&&xe(),0===t.length&&(U(!1),W(!1),V(""),re(!1),ce([]),u(""),he(""),Ie()),n(t)},[F,e,n,i,a,H,j,ue,Se,Ae,Ie,M,Te,xe,ke]),ze=ee(async()=>{if(Le(),ae.current=0,F)return void q(!1);let n=e.trim();if(!j&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return P?.add(n),U(!1),W(!1),V(""),qe(),ce([]),Ee(-1),void Ce("");Ee(-1),Ce("");let r=[];const o=ue.length>0,s=le.length>0;if(!j&&o&&(r=[...ue]),!j&&s){let e=n;le.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}n.length>0&&P?.add(n);const i=Re?.selection?{lines:Re.selection.lineCount,file:Re.activeFile?.relativePath?.split("/").pop()??Re.activeFile?.path?.split("/").pop()??"unknown",ide:MT[Cv()??""]??"IDE"}:void 0;t({input:n,role:j?"bash":"user",images:r,ideContext:Re?fA(Re):void 0,ideHint:i}),U(!1),W(!1),V(""),qe(),ce([])},[t,d,F,e,j,ue,le,P,Le,qe]),He=ee(t=>{const r=s(process.cwd(),t);let o;if(i&&""!==l){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),a(!1),u(""),O(e=>e+1)},[n,a,e,i,l,u]),We=ee(()=>{a(!1),u("")},[a,u]),Ge=ee(t=>{if("/resume"===t)P?.add(t),Ee(-1),Ce(""),he(e),W(!1),V(""),re(!0),n(""),O(e=>e+1);else{const e=Object.values(T_).includes(t),r=__.has(t);W(!1),V(""),e&&r?(P?.add(t),Ee(-1),Ce(""),n(""),O(e=>e+1),d&&d(t)):(n(t+" "),O(e=>e+1))}},[d,n,e,P]),Ve=ee(e=>{W(!1),V(""),n(e+" "),O(e=>e+1)},[n]),Qe=ee(()=>{W(!1),V(""),n(""),Ee(-1),Ce(""),O(e=>e+1)},[n]),Ke=ee(e=>{re(!1),n(""),he(""),Ee(-1),Ce(""),O(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ye=ee(()=>{re(!1),n(ge),Ee(-1),Ce(""),O(e=>e+1)},[ge,n]),Je=ee(e=>{ve.current=e,we.current=void 0},[]),Xe=Z(()=>{const t=Fe&&("OPEN"===Fe.state||"MERGED"===Fe.state);return"auto-accept"===_||"plan"===_||"bypass"===_||Me||t?!F&&!K:!F&&0===e.length&&!j&&!K},[F,e,j,K,_,Me,Fe]),Ze=J(new Map),et=Z(()=>ue.map((e,t)=>{if(Ze.current.has(e))return Ze.current.get(e)??null;const n=saveTempImage(e,t+1);return Ze.current.set(e,n),n}),[ue]),tt=__name(()=>F||i||H||K||B?0:Xe||I||j?3:4,"getBottomMargin");return Q.createElement(te,{width:"100%",flexDirection:"column",marginBottom:tt()},!K&&Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(ImageRowsDisplay,{detectedImages:ue,selectedImageIndex:me,imageTempPaths:et,termWidth:Oe,inHistory:-1!==Se}),Q.createElement(ne,{color:j?ar.GREEN:ar.GRAY},Pe.line.repeat(Oe)),Q.createElement(TextInput,{key:D,value:e,placeholder:ke?"Save and close the editor to continue...":o,onChange:Be,onSubmit:()=>{if(!ye.current)return Date.now()-ae.current<100?(ae.current=0,void Ue()):void(i||H||K||ke||ze());ye.current=!1},showCursor:!ke&&r&&-1===me,onCursorChange:Je,initialCursor:we.current,prefix:`${j?"!":Pe.pointer} `,prefixColor:j?ar.GREEN:ar.WHITE}),Q.createElement(ne,{color:j?ar.GREEN:ar.GRAY},Pe.line.repeat(Oe))),F&&Q.createElement(EA,null),B&&Q.createElement(te,{paddingTop:1},Q.createElement(ne,{color:ar.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&Q.createElement(tA,{onSelectFile:He,onClose:We,searchQuery:l}),H&&Q.createElement(P_,{onSelectCommand:Ge,onInsertCommand:Ve,onClose:Qe,searchQuery:G}),K&&Q.createElement(gA,{onSelectSession:Ke,onClose:Ye}),!H&&(Xe||I)&&Q.createElement(lA,{termWidth:Oe,indicatorText:wA(Me,Re,Oe),isIDEIndicator:yA(Me,Re),permissionMode:_,prInfo:Fe,tasteLearning:g,contextUsage:m,connectionIndicator:$e,pendingExitKey:I,updateStatus:C,updateFailedInfo:v,currentProvider:k,showProviderInfo:T,isBashMode:j,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),Te&&Q.createElement(te,{paddingLeft:1,flexDirection:"column"},Q.createElement(ne,{color:ar.YELLOW},Te)))},"InputBox");Ot(),as(),Rr();var CA=__name(({messages:e})=>0===e.length?null:Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(te,{marginBottom:0},Q.createElement(ne,{color:dr,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>Q.createElement(te,{key:t},Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," "),Q.createElement(ne,{color:ar.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),vA=Q.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:C,updateStatus:v,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:A,onToggleAutoAccept:P,hintMessage:I,historyManager:N,pendingExitKey:R,onResetPendingExitKey:M,onDoubleEscapeEmpty:L,retryAttempt:$,onAltP:D})=>{const[O,F]=Y(0),q=J(o);return X(()=>{R&&o!==q.current&&o.length>0&&M?.(),q.current=o},[o,R,M]),X(()=>{if(!t)return void F(0);const e=setInterval(()=>{F(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),Q.createElement(te,{flexDirection:"column"},Q.createElement(CA,{messages:e}),Q.createElement(te,{flexDirection:"row",justifyContent:"space-between"},Q.createElement(te,{flexDirection:"column"},(t||n.isExecuting)&&null===$&&Q.createElement(Bx,{tokens:g,timeElapsed:O,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),I&&Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM}," ","⎿"," ","Tip: ",I)))),Q.createElement(bA,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:C,updateStatus:v,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:A,onToggleAutoAccept:P,hintMessage:I,historyManager:N,pendingExitKey:!R||t||n.isExecuting?null:R,onDoubleEscapeEmpty:L,onAltP:D,isProcessing:t}))});Ot(),ME(),FE(),Zr(),io();var kA=__name(({onComplete:e,onCancel:t})=>{const[n,r]=Y(!1),[o,s]=Y(""),{authState:i,statusMessage:a,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 se((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(Yr,{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($E,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");function buildOAuthMetadataUrl(e){const t=new g(e),n="/"===t.pathname?"":t.pathname.replace(/\/+$/,"");return t.pathname=`/.well-known/oauth-authorization-server${n}`,t.search="",t.hash="",t.toString()}function buildOidcMetadataUrl(e){const t=new g(e),n=t.pathname.replace(/\/+$/,"");return t.pathname=`${n}/.well-known/openid-configuration`,t.search="",t.hash="",t.toString()}async function tryFetchAsMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.authorization_endpoint&&n.token_endpoint?{authorizationEndpoint:n.authorization_endpoint,tokenEndpoint:n.token_endpoint,registrationEndpoint:n.registration_endpoint,scopes:n.scopes_supported}:null}catch(t){return dlog(`[MCP] OAuth metadata fetch failed for ${e}`,t),null}}async function discoverOAuthMetadataFromIssuer(e){return await tryFetchAsMetadata(buildOAuthMetadataUrl(e))||await tryFetchAsMetadata(buildOidcMetadataUrl(e))}async function discoverOAuthMetadata(e){const t=new g(e),n=`${t.protocol}//${t.host}`;return await tryFetchAsMetadata(`${n}/.well-known/oauth-authorization-server`)||await tryFetchAsMetadata(`${n}/.well-known/openid-configuration`)}function parseResourceMetadataUrl(e){if(!e)return null;const t=e.match(/resource_metadata\s*=\s*"([^"]+)"|resource_metadata\s*=\s*([^\s,]+)/i);return t?t[1]??t[2]??null:null}async function fetchProtectedResourceMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{authorizationServers:n.authorization_servers,scopesSupported:n.scopes_supported}}catch(e){return dlog("[MCP] Protected resource metadata fetch failed",e),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:pS,capabilities:{},clientInfo:gS}})});if(401===t.status||403===t.status){const n=parseResourceMetadataUrl(t.headers?.get?.("www-authenticate")??null);if(n){const e=await fetchProtectedResourceMetadata(n),t=e?.authorizationServers?.[0];if(t){const n=await discoverOAuthMetadataFromIssuer(t);if(n)return e?.scopesSupported&&(n.scopes=e.scopesSupported),{requiresAuth:!0,metadata:n}}}return{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}}return{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}Ot(),Ot(),_S(),wS(),IS(),xS(),NS(),jS(),US(),BS(),Ot(),US(),BS(),vS(),qS(),Ot(),LS(),wS(),Kn(),__name(buildOAuthMetadataUrl,"buildOAuthMetadataUrl"),__name(buildOidcMetadataUrl,"buildOidcMetadataUrl"),__name(tryFetchAsMetadata,"tryFetchAsMetadata"),__name(discoverOAuthMetadataFromIssuer,"discoverOAuthMetadataFromIssuer"),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(parseResourceMetadataUrl,"parseResourceMetadataUrl"),__name(fetchProtectedResourceMetadata,"fetchProtectedResourceMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),Rr(),Xr();var TA=__name(({onClose:e})=>{const[t,n]=Y([]),[r,o]=Y(!0),[s,i]=Y(0),[a,l]=Y("list"),[u,d]=Y(null),m=ee(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!1===e.config.enabled?s="disabled":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)}},[]);X(()=>{m()},[m]);const g=Z(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),h=g[s]??null;se((t,n)=>{if(n.ctrl&&"c"===t)e();else if(n.escape)"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e();else if("list"===a){if(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow){if(0===g.length)return;const e=Math.max(0,g.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&h&&(l("actions"),d(null))}});const f=__name(e=>{switch(e){case"connected":return Q.createElement(ne,{color:ar.GREEN},Pe.tick);case"authenticated":return Q.createElement(ne,{color:ar.CYAN},Pe.tick);case"requires_auth":return Q.createElement(ne,{color:ar.YELLOW},Pe.warning);case"error":return Q.createElement(ne,{color:ar.RED},Pe.cross);default:return Q.createElement(ne,{color:ar.GRAY},Pe.circle)}},"getStatusIcon"),y=__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";case"disabled":return"disabled";default:return"not connected"}},"getStatusText"),w=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),S=__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(h)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)if("remove"!==e.value)if("disable"!==e.value)if("enable"!==e.value);else{d({text:`Enabling ${h.name}...`,color:ar.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:h.name,enabled:!0,scope:h.scope}))return void d({text:`${Pe.cross} Failed to enable ${h.name}, server may no longer exist in ${h.scope} scope`,color:ar.YELLOW});await m(),d({text:`${Pe.tick} Enabled ${h.name}`,color:ar.GREEN})}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else{d({text:`Disabling ${h.name}...`,color:ar.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:h.name,enabled:!1,scope:h.scope}))return void d({text:`${Pe.cross} Failed to disable ${h.name}, server may no longer exist in ${h.scope} scope`,color:ar.YELLOW});await e.disconnectServer(h.name),await m(),d({text:`${Pe.tick} Disabled ${h.name}`,color:ar.GREEN})}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else l("confirm-remove");else{if(!h.config.oauth)return void d({text:"No OAuth configured for this server",color:ar.YELLOW});d({text:`Authenticating ${h.name}...`,color:ar.CYAN,loading:!0});try{const e={authorizationUrl:h.config.oauth.authorizationUrl,tokenUrl:h.config.oauth.tokenUrl,clientId:h.config.oauth.clientId,clientSecret:h.config.oauth.clientSecret,scopes:h.config.oauth.scopes},t=await performOAuthFlow(h.name,h.config.url??"",e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`${Pe.tick} Authenticated with ${h.name}`,color:ar.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name)}catch{}await m()}else d({text:`${Pe.cross} Auth failed: ${t.error}`,color:ar.RED})}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else{d({text:`Connecting ${h.name}...`,color:ar.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name),d({text:`${Pe.tick} Connected to ${h.name}`,color:ar.GREEN}),await m()}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else d({text:"Already authenticated",color:ar.GREEN});else d({text:"Already connected",color:ar.GREEN});else l("list")},"handleActionSelect"),C=__name(async e=>{if(h)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===h.status&&await e.disconnectServer(h.name),await removeMcpServer({name:h.name,scope:h.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,g.length-2)))}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Manage MCP servers"),Q.createElement(ne,{color:ar.DIM},"Loading..."));if("confirm-remove"===a&&h)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.RED,bold:!0},"Remove ",h.name,"?"),Q.createElement(ne,{color:ar.DIM},"This will remove the server from ",h.scope," config."),Q.createElement(te,{marginTop:1},Q.createElement(mt,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY}," ",t)})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&h){const e=[],t="disabled"===h.status,n="connected"===h.status,r="authenticated"===h.status||n;return t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"}),!t&&h.config.oauth&&r&&e.push({label:"Authenticated",value:"authenticated"}),t||!h.config.oauth||r||e.push({label:"Authenticate",value:"auth"}),t||e.push({label:"Disable",value:"disable"}),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},h.name),Q.createElement(te,null,f(h.status),Q.createElement(ne,{color:ar.DIM}," ",y(h))),Q.createElement(te,{marginTop:1},Q.createElement(mt,{items:e,onSelect:E,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY}," ",t)})),u&&Q.createElement(te,{marginTop:1},u.loading&&Q.createElement(ne,{color:u.color},Q.createElement(je,{type:"dots"})," "),Q.createElement(ne,{color:u.color},u.text)),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let v=null;return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Manage MCP servers"),Q.createElement(ne,{color:ar.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},"No MCP servers configured."),Q.createElement(ne,{color:ar.DIM},'Use "cmd mcp add" to add a server.'),Q.createElement(Kr,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:ar.CYAN,dimColor:!0})):Q.createElement(te,{marginTop:1,flexDirection:"column"},g.map((e,t)=>{const n=e.scope!==v;v=e.scope;const r=t===s;return Q.createElement(Q.Fragment,{key:e.name},n&&Q.createElement(te,{marginTop:0===t?0:1},Q.createElement(ne,{bold:!0},w(e.scope)),Q.createElement(ne,{color:ar.DIM}," (",S(e.scope),")")),Q.createElement(te,{paddingLeft:1},Q.createElement(ne,{color:r?ar.WHITE:ar.GRAY},r?"› ":" "),Q.createElement(ne,{color:r?ar.WHITE:void 0,bold:r},e.name),Q.createElement(ne,{color:ar.DIM}," · "),f(e.status),Q.createElement(ne,{color:"connected"===e.status?ar.GREEN:"authenticated"===e.status?ar.CYAN:"requires_auth"===e.status?ar.YELLOW:ar.GRAY}," ",y(e))))})),u&&Q.createElement(te,{marginTop:1},u.loading&&Q.createElement(ne,{color:u.color},Q.createElement(je,{type:"dots"})," "),Q.createElement(ne,{color:u.color},u.text)),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},0===t.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ot(),wn(),Hn(),Rr();var _A=__name(({onClose:e})=>{const[t,n]=Y([]),[r,o]=Y(0),[s,i]=Y(!0),[a,l]=Y(null);X(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(se((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(te,{paddingLeft:1,paddingTop:1},Q.createElement(ne,{color:ar.DIM},"Loading memory files..."));if(a)return Q.createElement(te,{paddingLeft:1,paddingTop:1},Q.createElement(ne,{color:ar.RED},Pe.cross," ",a));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(te,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:ar.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},Q.createElement(te,null,Q.createElement(ne,{color:ar.WHITE,bold:!0},"Select memory to edit:")),Q.createElement(te,{columnGap:4,marginTop:1},Q.createElement(te,{flexDirection:"column"},m.map((e,t)=>Q.createElement(ne,{key:t,color:r===t?ar.WHITE:ar.DIM},r===t?`${Dn} `:" ",e.label))),Q.createElement(te,{flexDirection:"column"},m.map((e,t)=>Q.createElement(ne,{key:t,color:r===t?ar.WHITE:ar.DIM},e.description)))))},"MemorySelector");function AutoCompactMessage({content:e}){return Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.DIM},Pe.bullet," ",e))}function TasteSkipMessage(){return Q.createElement(te,{marginTop:1,marginBottom:1},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG,bold:!0},bT)),Q.createElement(ne,{color:ar.DIM}," Skipped. Run "),Q.createElement(ne,{color:Tr.CODE},"/learn-taste"),Q.createElement(ne,{color:ar.DIM}," or "),Q.createElement(ne,{color:Tr.CODE},"cmd learn-taste"),Q.createElement(ne,{color:ar.DIM}," anytime."))}function HookWarningMessage({content:e}){return Q.createElement(te,null,Q.createElement(ne,{color:ar.YELLOW},Pe.warning),Q.createElement(te,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.YELLOW},e)))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?Q.createElement(TasteSkipMessage,null):t?.isAutoCompact?Q.createElement(AutoCompactMessage,{content:e}):t?.isHookWarning?Q.createElement(HookWarningMessage,{content:e}):Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.DIM},Pe.bullet," ",e))}Ot(),Rr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(InfoMessage,"InfoMessage"),Ot(),wn(),Qr(),_E(),Co(),io(),Rr(),Ot(),Rr();var xA=yt()?"⠶":"#";function AssistantMessage({content:e}){return Q.createElement(te,null,Q.createElement(ne,{color:Er},xA),Q.createElement(te,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=ar.GREEN,s=Pe.tick,i="default",a=t||"(No output)";n&&(o=ar.YELLOW,s=Pe.arrowRight,i=ar.YELLOW,a="Executing…"),r&&(o=ar.RED,s=Pe.cross,i=ar.RED);const l=Z(()=>buildTreeConnectors(a),[a]);return Q.createElement(te,null,Q.createElement(ne,{color:o},s),Q.createElement(te,{flexDirection:"column",marginLeft:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.GRAY},"$ "),Q.createElement(ne,{color:o,bold:!0},e)),Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,{color:Ar},l),Q.createElement(ne,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?ar.YELLOW:void 0,o=Z(()=>buildTreeConnectors(e),[e]);return Q.createElement(te,{flexDirection:"column",marginBottom:0,marginTop:-1},Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},o),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:r},e))),t&&Q.createElement(te,{marginLeft:3},Q.createElement(ne,{color:ar.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return Q.createElement(te,null,Q.createElement(ne,{color:ar.RED},t?Pe.pointer:Pe.warning),Q.createElement(te,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?Q.createElement(ne,{color:ar.RED,wrap:"wrap"},e):Q.createElement(Markdown,{color:ar.RED},e)))}__name(AssistantMessage,"AssistantMessage"),Ot(),Rr(),__name(BashMessage,"BashMessage"),Ot(),Rr(),__name(CommandResultMessage,"CommandResultMessage"),Ot(),Rr(),__name(ErrorMessage,"ErrorMessage"),Ot(),Rr();var AA={connected:{char:Pe.tick,color:ar.GREEN},installed:{char:Pe.tick,color:ar.GREEN},up_to_date:{char:Pe.tick,color:ar.GREEN},needs_reload:{char:Pe.circle,color:ar.YELLOW},failed:{char:Pe.cross,color:ar.RED},not_in_ide:{char:Pe.circle,color:ar.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getStatusHeadline(e,t),i=AA[e];return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,null,Q.createElement(ne,{color:i.color},i.char),Q.createElement(ne,null," ",r),o&&Q.createElement(ne,{color:ar.CYAN},o),s&&Q.createElement(ne,null,s))),n?.map((e,t)=>Q.createElement(ne,{key:t,color:ar.DIM}," ",e)))}__name(IDEStatusMessage,"IDEStatusMessage"),Ot(),Ot(),wn();Rr(),Ot(),Co();var PA="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]:[PA]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||PA;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||PA}catch{return PA}}function HelpMessage(){const e=getInvokedCommandName(),t=Z(()=>Uv.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return Q.createElement(te,{flexDirection:"column",paddingY:1},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Command Code"),Q.createElement(ne,{color:ar.GRAY}," v","0.26.5")),Q.createElement(ne,{color:ar.GRAY},Dv)),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Usage"),Q.createElement(te,{paddingLeft:2},Q.createElement(ne,null,e," <command> [options]"))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Options"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},jv.map(t=>Q.createElement(te,{key:t.key},Q.createElement(ne,null,t.key.replace(/^cmd/,e).padEnd(Ov)),Q.createElement(ne,{color:ar.GRAY},t.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Commands"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},Bv.map(t=>Q.createElement(te,{key:t.key},Q.createElement(ne,null,t.key.replace(/^cmd/,e).padEnd(Ov)),Q.createElement(ne,{color:ar.GRAY},t.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Slash Commands"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},t.map(e=>Q.createElement(te,{key:e.key},Q.createElement(ne,null,e.key.padEnd(Ov)),Q.createElement(ne,{color:ar.GRAY},e.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Keyboard Shortcuts"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},qv.map(e=>Q.createElement(te,{key:e.key},Q.createElement(ne,null,e.key.padEnd(Ov)),Q.createElement(ne,{color:ar.GRAY},e.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Examples"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},Hv.map(t=>Q.createElement(te,{key:t.key},Q.createElement(ne,null,t.key.replace(/^cmd/,e).padEnd(Ov)),Q.createElement(ne,{color:ar.GRAY},t.description))))),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.CYAN},Pe.pointer),Q.createElement(ne,{color:ar.GRAY}," ",Wv.replace(/cmd/,e))),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{bold:!0},"Links"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},zv.map(e=>Q.createElement(te,{key:e.key},Q.createElement(ne,null,e.key.padEnd(Ov)),Q.createElement(ne,{color:ar.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?Q.createElement(HelpMessage,null):Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{wrap:"wrap"},Q.createElement(Markdown,null,e)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),io(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ot(),Hn(),ro(),Rr();var IA={"Interrupted by user":"Interrupted by user","Insufficient credits":Ln};function UserMessage({content:e,images:t,imageCount:n=0,ideHint:r}){const o="Interrupted by user"===e,s="Insufficient credits"===e,i=e.startsWith("Error:"),a=o||s||i,l=a&&IA[e]||e,u=null!=t?t.length:n,d=J(null);null===d.current&&t&&t.length>0&&(d.current=t.map((e,t)=>saveTempImage(e,t+1)));const m=d.current??[];return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{backgroundColor:a?void 0:Sr.BG,paddingRight:1},Q.createElement(ne,{color:a?ar.RED:Sr.POINTER,bold:!a},Pe.pointer),Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:a?ar.RED:ar.WHITE,wrap:"wrap"},l))),u>0&&Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM},"⎿"," ",Array.from({length:u},(e,t)=>{const n=m[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))),r&&!a&&Q.createElement(te,{marginLeft:2},Q.createElement(ne,{color:Ar},wT),Q.createElement(ne,{color:ar.DIM}," ","Selected ",r.lines," ",1===r.lines?"line":"lines"," from ",r.file," in ",r.ide)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0,n=e.metadata?.ideHint;return Q.createElement(UserMessage,{content:e.input,images:t,ideHint:n})}return"assistant"===e.role?Q.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?Q.createElement(ToolMessage,{name:SE(e.name||""),input:e.input,output:e.output||"",isPending:fE(e),hasError:hE(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?Q.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:fE(e),hasError:hE(e)}):"system"===e.role?Q.createElement(SystemMessage,{content:e.input}):"info"===e.role?Q.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?Q.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?Q.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?Q.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=findModelById(e);return t?t.name.toLowerCase().replaceAll(" ","-"):e}function getProviderShortName(e){return e?dn[e]?.shortLabel??e.slice(0,4):""}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [ctrl+e to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:wr},o),Q.createElement(BracketedText,{text:n,color:wr}),Q.createElement(ne,{color:wr},o))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(getProviderShortName,"getProviderShortName"),__name(TranscriptDivider,"TranscriptDivider");var NA=Q.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentProvider:s,hiddenCount:i=0})=>{const a=i>0?{role:"transcript-divider",count:i}:null,l=[...t?["header"]:[],...a?[a]:[],...e],u=useTerminalWidth(),d=Z(()=>ex(u),[u]),m=Z(()=>sx(u),[u]),g=Z(()=>getPackageJson().version||"0.0.0",[]),h=Z(()=>getGitHeaderInfo(),[]),f=Z(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?getModelShortName(o):"sonnet-4.6",w="taste-1",S=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO,E=S?" · co":"",C=S&&s?` · ${getProviderShortName(s)}`:"";return Q.createElement(re,{items:l,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return Q.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:u});if("header"===e)return"compact"===m?Q.createElement(te,{key:"header",marginBottom:1,flexDirection:"row"},Q.createElement(te,{width:rx,flexShrink:0},Q.createElement(ix,null,nx)),Q.createElement(te,{flexDirection:"column",marginLeft:2},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Command Code"),Q.createElement(ne,{color:wr}," ","v",g)),Q.createElement(ne,{color:wr},"models: ",y," · ",w,E),Q.createElement(ne,{color:wr},f,h&&h.isLocal&&h.branch&&` (${h.branch})`))):Q.createElement(te,{key:"header",marginBottom:1,flexDirection:"column"},Q.createElement(ix,null,d.trimEnd()),Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(te,null,Q.createElement(ne,{color:wr},"# "),Q.createElement(ne,{bold:!0},"Command Code"),Q.createElement(ne,{color:wr}," v",g)),Q.createElement(ne,{color:wr},"# models: ",y," · ",w,C,E),Q.createElement(te,null,Q.createElement(ne,{color:wr},"# ",f,h&&h.isLocal&&h.branch&&Q.createElement(ne,{color:wr}," ","(branch:"," ",h.branch,")")))));const t=e,n=renderFeedEntry(t,r);return Q.createElement(te,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ot(),_E(),ao(),Rr();var RA=K(__name(function LiveAgentStatusInner2({entry:e}){const t=SE(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,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=Y(".");return X(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),Q.createElement(te,{flexDirection:"column",marginBottom:1,width:"90%"},Q.createElement(te,null,Q.createElement(ne,{backgroundColor:hr.BG,color:hr.FG,bold:!0},` ${t} `),o&&Q.createElement(ne,null," ","(",o,")")),Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,null,"⎿"," "),Q.createElement(ne,{color:ar.GRAY},"Running (",formatTime2(i)," | ",formatTokens(s),")",l)),a.length>0&&Q.createElement(te,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=SE(e.name);return Q.createElement(te,{key:t,columnGap:1},Q.createElement(ne,{color:ar.GRAY},"⎿"),Q.createElement(ne,{color:ar.GRAY}," ",n),e.input&&Q.createElement(ne,{color:ar.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),MA=K(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:Q.createElement(RA,{entry:e})},"LiveAgentStatus"));Ot(),wn(),Qr(),Jr(),ao(),io(),Ot(),wn(),Rr();var LA=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o})=>{const s=dn[t],i=o??s?.showProviderLabelInSelector??!1,a=un[e.provider],l=e.id===cn?`${e.label} (default)`:e.label;return Q.createElement(te,null,Q.createElement(ne,{color:n?ar.CYAN:ar.GRAY},n?`${Pe.pointer} `:" "),Q.createElement(ne,{color:n?ar.CYAN:r?ar.GREEN:ar.WHITE},l.padEnd(32)),i&&Q.createElement(ne,{color:ar.DIM},a),e.description&&Q.createElement(ne,{color:ar.DIM},i?" · ":"",e.description),r&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick))},"ModelRow");function checkModelAccess({model:e,planId:t,purchasedCredits:n,freeCredits:r}){if(n>0||r>0)return{allowed:!0};if(!t)return{allowed:!0};const o=Xt[t];if(!o)return{allowed:!0};const s=getModelCategory({provider:e.provider,model:e.id});if(!s)return{allowed:!0};const i=`${e.provider}:${e.id}`;if(!o.allowedCategories.includes(s)){const t=getMinimumPlanForModel({fullModelId:i,category:s}),n=t?getPlanDisplayName(t):"Ultra";return{allowed:!1,errorMessage:`${e.name} available in ${n} and above plans or extra on demand usage\nRun /upgrade to check plans or /extra to buy on-demand credits`}}if(o.blockedModels?.includes(i)){const t=getMinimumPlanForModel({fullModelId:i,category:s}),n=t?getPlanDisplayName(t):"Ultra";return{allowed:!1,errorMessage:`${e.name} available in ${n} and above plans or extra on demand usage\nRun /upgrade to check plans or /extra to buy on-demand credits`}}return{allowed:!0}}Rr(),Ot(),wn(),__name(checkModelAccess,"checkModelAccess");var $A="Loading plan info…",DA=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function effortGlyph(e){return"low"===e?"▁▁":"medium"===e?"▃▃":"high"===e?"▆▆":"xhigh"===e?"██":"max"===e?"▣▣":"░░"}function searchGroups(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,DA);e.length>0&&n.push({...r,models:e})}return n}function flattenGroups(e){const t=[];for(const n of e)for(const e of n.models)t.push({providerId:n.providerId,model:e});return t}function groupByModelProvider(e,t){const n=new Map;for(const t of e){const e=un[t.provider]??t.provider,r=n.get(e)??[];r.push(t),n.set(e,r)}const r=[];for(const e of Object.values(un))n.has(e)&&!r.includes(e)&&r.push(e);return r.map(e=>({providerId:t,label:e,models:n.get(e)}))}__name(effortGlyph,"effortGlyph"),__name(searchGroups,"searchGroups"),__name(flattenGroups,"flattenGroups"),__name(groupByModelProvider,"groupByModelProvider");var OA=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0})=>{const[a,l]=Y(""),[u,d]=Y(null),[m,g]=Y(()=>new Set),h=Z(()=>isInternalTeamFlagEnforced(),[]),f=Z(()=>h?mn:groupByModelProvider(pn.flatMap(e=>e.models),dn["command-code"].id),[h]),y=Z(()=>searchGroups(f,a),[f,a]),w=Z(()=>flattenGroups(y),[y]),S=Z(()=>flattenGroups(f),[f]),E=void 0!==o,C=Z(()=>E?null:getCachedBillingContext(),[E]),[v,k]=Y(C),[T,_]=Y(!E&&!C);X(()=>{if(E)return;if(v)return;let e=!0;return getBillingContext().then(t=>{e&&(k(t),_(!1))}),()=>{e=!1}},[E,v]);const x=!E&&!0===v?.fetchFailed,A=E?o:v?.planId??null,P=E?s:v?.purchasedCredits??0,I=E?i:v?.freeCredits??0,N=h?dn.anthropic.id:dn["command-code"].id,R=r??N,M=n?Math.max(0,w.findIndex(e=>e.model.id===n&&e.providerId===R)):0,{cursor:L,error:$,setError:D}=useListNavigation({items:w,onSelect:__name(t=>e(t.model.id,t.providerId),"onSelect"),onCancel:t,initialIndex:M,searchQuery:a,onSearchChange:l,validate:__name(e=>{if(m.has(e.providerId))return`Run /provider to authenticate with ${getProviderConfig(e.providerId)?.displayName??e.providerId} first`;if(u&&!h){const t=dn[u]?.supportedModelProviders;if(t&&!t.includes(e.model.provider))return`${dn[u]?.label??u} does not support ${e.model.provider} models. Switch provider via /provider.`}if(T)return $A;const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:A,purchasedCredits:P,freeCredits:I});return t.allowed?null:t.errorMessage??"Model not available for your plan"},"validate")}),[O,F]=Y(()=>{const e={};for(const t of S)getSupportedEfforts(t.model.id)&&(e[t.model.id]=getReasoningEffort(t.model.id));return e});X(()=>{F(e=>{const t={...e};for(const e of S)getSupportedEfforts(e.model.id)&&(e.model.id in t||(t[e.model.id]=getReasoningEffort(e.model.id)));return t})},[S]);const q=__name((e,t)=>{const n=getSupportedEfforts(e);if(!n||0===n.length)return;const r=[void 0,...n],o=O[e],s=r.indexOf(o),i=r[((-1===s?0:s)+t+r.length)%r.length];F(t=>({...t,[e]:i})),setReasoningEffort({modelId:e,effort:i})},"cycleEffort");se((e,t)=>{if(!t.leftArrow&&!t.rightArrow)return;const n=w[L];n&&getSupportedEfforts(n.model.id)&&q(n.model.id,t.rightArrow?1:-1)}),X(()=>{if(T)return;if($!==$A)return;const e=w[L];if(!e||x)return void D(null);const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:A,purchasedCredits:P,freeCredits:I});D(t.allowed?null:t.errorMessage??"Model not available for your plan")},[T,x,$,D,w,L,A,P,I]),X(()=>{(async()=>{await isOAuthEnforced()&&d(await getConfiguredProvider())})()},[]),X(()=>{(async()=>{const e=new Set(f.map(e=>e.providerId)),t=new Set;for(const n of e){const e=getProviderConfig(n);e?.requiresAuth&&e.checkAuth&&(await e.checkAuth()||t.add(n))}g(t)})()},[f]);let j=0;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Select model")),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{dimColor:!0},h?"Select a model and provider. Applies to this session and future sessions.":"Switch between Command Code models. Applies to this session and future sessions.")),Q.createElement(te,{marginBottom:2,flexDirection:"column",width:"100%"},Q.createElement(mx,{query:a,resultCount:a?w.length:void 0,placeholder:"Type to search models..."})),0===w.length?Q.createElement(te,{marginY:1},Q.createElement(ne,{color:ar.GRAY},'No models match "',a,'"')):Q.createElement(te,{flexDirection:"column"},y.map((e,t)=>{const r=j;return j+=e.models.length,Q.createElement(te,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:t>0?1:0},h?Q.createElement(ne,{bold:!0,color:lr},e.label):Q.createElement(ne,{bold:!0,dimColor:!0},e.label),e.models.map((t,o)=>Q.createElement(LA,{key:`${e.providerId}-${e.label}-${t.id}`,model:t,providerId:e.providerId,isHighlighted:r+o===L,isCurrent:t.id===n&&e.providerId===R,showProviderLabel:!!h&&void 0})))})),$&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},$)),(()=>{const e=w[L];if(!e)return null;const t=getSupportedEfforts(e.model.id);if(!t||0===t.length)return null;const n=O[e.model.id],r=effortGlyph(n),o=n??"auto";return Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0,color:ar.CYAN},r),Q.createElement(ne,{bold:!0},` ${o} effort`),Q.createElement(ne,{dimColor:!0}," [←/→ adjust]"),void 0===n&&Q.createElement(ne,{dimColor:!0}," [provider default]"))})(),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"type to search . up/down navigate . Enter to select"),a?Q.createElement(ne,{color:ar.DIM}," . Esc to clear"):Q.createElement(ne,{color:ar.DIM}," . Esc to cancel")))},"ModelSelector");Ot(),io(),Rr();var FA=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");se((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,i=n&&-1===s;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Select AI Provider")),n&&Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:ar.DIM},"Current: "),Q.createElement(ne,{color:ar.GREEN},getProviderDisplayName(n)),i&&Q.createElement(ne,{color:ar.YELLOW}," [OAuth enforced]"))),Q.createElement(te,{marginBottom:0},Q.createElement(ne,{color:ar.DIM},"Available Providers:")),Q.createElement(mt,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:e?ar.CYAN:ar.GRAY,bold:e},e?Pe.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.CYAN:ar.GRAY,bold:e},` ${t}`)}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=Y(0);if(X(()=>{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(te,{marginBottom:1},Q.createElement(ne,{color:kr,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ot(),Rr(),__name(RetryMessage,"RetryMessage"),Ot(),as(),Hn(),Rr();var qA=[{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"}],jA=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=Z(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=Y(Math.max(0,r.length-1)),[i,a]=Y(Math.max(0,r.length-8)),[l,u]=Y("checkpoint"),[d,m]=Y(null),[g,h]=Y(0),f=Z(()=>{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]),y=Z(()=>f?qA:qA.filter(e=>"conversation"===e.mode),[f]);if(X(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),se((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[o]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:lr,bold:!0},"Rewind"),Q.createElement(ne,{color:ar.DIM},"No checkpoints available. Start a conversation to create checkpoints."),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to close")));if("mode"===l&&d)return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:lr,bold:!0},"Rewind"),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"Restore to: "),Q.createElement(ne,{color:ar.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),Q.createElement(te,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return Q.createElement(te,{key:e.mode,flexDirection:"column"},Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:n?lr:void 0},n?`${Dn} `:" "),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:n?lr:ar.WHITE},e.label),Q.createElement(ne,{color:ar.DIM},e.description))),!r&&Q.createElement(ne,null," "))})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Enter"),Q.createElement(ne,{color:ar.DIM}," to confirm, "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to go back")));const w=r.slice(i,i+8);return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:lr,bold:!0},"Rewind"),Q.createElement(ne,{color:ar.DIM},"Select a checkpoint to restore your session"),r.length>8&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),Q.createElement(te,{marginTop:1}),Q.createElement(te,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return Q.createElement(te,{key:e.messageId,flexDirection:"column"},Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:s?lr:void 0},s?`${Dn} `:" "),Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:s?lr:ar.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),Q.createElement(ne,{color:ar.DIM}," • "),Q.createElement(ne,{color:ar.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),Q.createElement(ne,{color:ar.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&Q.createElement(ne,null," "))})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Enter"),Q.createElement(ne,{color:ar.DIM}," to select, "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to cancel")))},"RewindSelector");Ot(),Kn(),Ot(),Ot();var UA=__name(e=>{const[t,n]=Y(e),[r,o]=Y(null);return X(()=>{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 Kk.on("reset",t),Kk.on("new-event",r),()=>{Kk.off("reset",t),Kk.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new jw({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o,s;try{const e=await getOAuthCredentials({provider:n});o=e.token,s=e.oauthProvider,validateOAuthToken({token:o,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[Ut.PROJECT_SLUG]:rk.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(i[Ut.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Ut.OAUTH_PROVIDER]=s)),{request:t,headers:i}}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}Ot(),Ot(),sS(),fS(),Kn(),Ot(),wn(),Kn(),Ot(),Ot(),wn(),sS(),fS(),Kn(),Jr(),ao(),__name(createRequestClient,"createRequestClient"),Ot(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ot(),Ot(),Kn(),Lo(),Ot();var BA="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Produce ${t} varied observations for these prompts:\n\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}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}`),Kk.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()}`),Kk.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${Bt.ALPHA.GENERATE} with model: ${BA}`);const r={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:BA,system:"You scan prompts and produce casual observations like a dev friend glancing at someone's 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 per observation\n- one observation per line\n- sound human, not robotic\n- output only the observations, no preamble",max_tokens:200,temperature:.7,stream:!0},threadId:Ae()},o=await e.post({endpoint:Bt.ALPHA.GENERATE,body:r,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const s=createInsightEmitter();await consumeSSEStream(o,{onText:__name(e=>{s.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${s.getChunkCount()} chunks received`),s.emitRemaining(),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 i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(Kk.observerHasRun)return;Kk.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r={...n,[Ut.SESSION_ID]:`observer-${Ae()}`},o=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${o.length} batches`);const s=Math.min(o.length,6);for(let t=0;t<s;t++){if(Kk.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const n=o[t];try{await processBatch(e,r,n,t+1,o.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),Kk.addEvent({type:"progress",message:"Continuing without live observations..."})}}wn(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var zA=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(w.homedir(),".claude","projects");await v.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await v.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await v.stat(s)).isDirectory())continue;const r=(await v.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),i=await v.stat(r),a=o.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{Kk.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Kk.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 findCursorSessions(e=0){try{Kk.addEvent({type:"progress",message:"Scanning Cursor sessions..."});const t=await findCursorSessions(process.cwd(),e);return dlog(`[Import] found ${t.length} Cursor sessions`),t}catch(e){return dlog("[Import] no cursor sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await v.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=[],o=[];try{Kk.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),i=s.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,o=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length},{name:"Cursor",count:n.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Kk.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${o.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&s.push({agent:"cursor",sessionIds:n.map(e=>e.id),displayName:"Cursor"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:r,learnedSessions:a+l+u,agentSessions:s,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));o.push(...e)}const y=n.length+r.length+o.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${o.length})`),Kk.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:o,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){Kk.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 S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Kk.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const s=getApiBaseUrl(),i=new jw({baseUrl:s});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&Kk.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),s=new Jk({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await s.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Kk.markLearningComplete(),await E,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`)}if(o.length>0){const e=o.map(e=>e.id);await markSessionsAsLearned("cursor",e),dlog(`[Import] marked ${e.length} cursor sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const l=await this.extractLearningSummary(),u=[];if(n.length>0&&u.push(`Claude Code (${n.length})`),r.length>0&&u.push(`Codex (${r.length})`),o.length>0&&u.push(`Cursor (${o.length})`),!a){const s=Kk.getEvents().some(e=>"error"===e.type&&e.message?.toLowerCase().includes("insufficient credits")),i="Learning failed - sessions not marked as learned";return e.push(i),s||Kk.addEvent({type:"error",message:i}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,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"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}return Kk.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,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"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),Kk.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 v.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")}},HA=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),WA=__name(e=>{const[t,n]=Y({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return X(()=>{Kk.reset(),Kk.markImportStarted(),(async()=>{try{const t=await Promise.race([zA.importAndLearn(),HA(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");Ot();var GA=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{se((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");Ot(),Kn();var VA=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=Y(null),[o,s]=Y(null),i=J(!1);return X(()=>{if(i.current)return;let n=null;return(async()=>{try{i.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),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{Kk.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{Kk.reset(),e()}}Ot(),Kn(),Ot(),Kn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var QA=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=J(n),o=ee(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ee(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ee(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ee(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ee(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Ot(),Kn();var KA=__name(({conditions:e,autoLearn:t})=>{const[n,r]=Y("checking"),o=J(!1);return X(()=>{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]),X(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ot(),Ot(),Rr();var YA=__name(({error:e})=>Q.createElement(te,{padding:1},Q.createElement(te,{flexDirection:"column",borderColor:ar.RED,padding:1},Q.createElement(te,{marginBottom:1},Q.createElement(ne,null,"Error initializing onboarding: ",e)),Q.createElement(te,null,Q.createElement(ne,null,"Continuing without onboarding...")))),"OnboardingError");Ot(),Ot(),Rr();var JA=__name(()=>Q.createElement(ne,null,"Skip"),"SkipOptionText"),XA=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=Y(1);return se((e,t)=>{t.escape?r():"n"!==e&&"N"!==e?t.upArrow||t.downArrow?s(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===o?n():r()):r():n():dismissOnboardingForeverForProject().then(()=>r())}),Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:cr.TEXT,paddingX:1,paddingY:0},Q.createElement(ne,{color:cr.TEXT,bold:!0},"Build Your Coding Taste"),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:1===o?cr.TEXT:ar.GRAY},1===o?Pe.pointer:" "," 1. Yes, learn (recommended)")),Q.createElement(te,null,Q.createElement(ne,{color:2===o?cr.TEXT:ar.GRAY},2===o?Pe.pointer:" "," 2."," ",Q.createElement(JA,null)))),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"↑↓ · "),Q.createElement(ne,{color:Tr.CODE},"enter"),Q.createElement(ne,{color:ar.DIM}," ok · "),Q.createElement(ne,{color:Tr.CODE},"esc"),Q.createElement(ne,{color:ar.DIM}," skip · "),Q.createElement(ne,{color:Tr.CODE},"n"),Q.createElement(ne,{color:ar.DIM}," never")))},"ImportChoice");Ot(),Ot(),Rr();var ZA=__name(({error:e})=>Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.RED,paddingX:2,paddingY:1,marginBottom:2},Q.createElement(ne,{color:ar.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,e))),"ErrorSection");Ot(),Ot(),Rr(),Ot(),Ot(),Ot(),Rr(),Ot(),Rr();var eP=__name(()=>Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG},bT),"TasteBadge");Ot(),Rr(),Ot();var tP=["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"],nP="⎿",rP=__name(()=>{const[e,t]=Y(()=>Math.floor(Math.random()*tP.length));return X(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*tP.length))},2e3);return()=>clearInterval(e)},[]),Q.createElement(ne,{color:ar.YELLOW},tP[e],"...")},"PulsingText");Ot(),Rr();var oP=[Pe.bullet,Pe.squareSmallFilled,Pe.lozenge,Pe.star,Pe.triangleRight,Pe.triangleUp,Pe.circleFilled,Pe.pointer],sP=__name(e=>String(e).padStart(3," "),"padNum"),iP=__name(e=>oP[e%oP.length],"getSymbol"),aP=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${sP(t)} ↓${sP(n)} (↑↓ scroll)`,"buildStatusLine"),lP=__name(({insights:e})=>{const[t,n]=Y(0),[r,o]=Y(!0),s=e.length,i=s>10,a=Math.max(0,s-10);if(X(()=>{r&&i&&n(a)},[s,r,i,a]),se((e,t)=>{if(i)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&o(!0),t}))}),0===s)return null;const l=e.slice(t,t+10),u=t,d=s-t-10;return Q.createElement(te,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&Q.createElement(ne,{color:ar.DIM},aP(s,u,d,r)),l.map((e,n)=>{const r=t+n;return Q.createElement(te,{key:r,marginBottom:0},Q.createElement(ne,{color:ar.DIM},iP(r)," ",e))}))},"ScrollableInsights");Ot(),Rr();var cP=__name(()=>{const[e,t]=Y(!0);return X(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),Q.createElement(ne,{color:ar.YELLOW},e?Pe.circleFilled:Pe.circle)},"PulsingDot"),uP=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return Q.createElement(te,{flexDirection:"column",marginBottom:0},Q.createElement(eP,null),Q.createElement(te,{marginTop:0},Q.createElement(ne,{color:ar.DIM},nP),Q.createElement(te,{marginLeft:2},a?Q.createElement(ne,{color:cr.TEXT},"learned your coding taste"):Q.createElement(rP,null))));const u=__name(()=>r?Q.createElement(ne,{color:pr.BG},Pe.square):n?Q.createElement(cP,null):Q.createElement(ne,{color:ar.DIM},Pe.circle),"getStatusIcon"),d=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||d?Q.createElement(te,{flexDirection:"column",marginBottom:0},(n||r)&&Q.createElement(te,{marginBottom:0},Q.createElement(te,{marginRight:1},u()),Q.createElement(ne,{color:r?ar.WHITE:n?ar.YELLOW:ar.DIM},e)),r&&t&&(!l||0===l.learningCount)&&Q.createElement(te,{marginLeft:3,marginBottom:0},Q.createElement(ne,{color:ar.DIM},t)),o.length>0&&Q.createElement(te,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>Q.createElement(ne,{key:t,color:ar.DIM},`${Pe.bullet} ${e}`))),s.length>0&&Q.createElement(lP,{insights:s}),r&&l&&l.learningCount>0&&Q.createElement(te,{flexDirection:"column",marginLeft:1,marginBottom:0},Q.createElement(te,{marginBottom:1,flexDirection:"row"},Q.createElement(ne,null,nP),Q.createElement(te,{marginLeft:2},Q.createElement(ne,{color:cr.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),Q.createElement(te,{flexDirection:"column",marginLeft:1},Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," Stored in"," ",l.storage),Q.createElement(ne,{color:ar.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),dP=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return Q.createElement(te,{flexDirection:"column",marginBottom:1},e.map((e,n)=>Q.createElement(te,{key:e.id,marginLeft:0===n?0:3},Q.createElement(uP,{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"),mP=__name(({steps:e})=>Q.createElement(dP,{steps:e}),"ProgressSection");Ot(),Rr();var pP=__name(({isImporting:e=!1,waitingForInput:t=!1})=>Q.createElement(Q.Fragment,null,e&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"ESC to cancel")),t&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ot();var gP=[{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"}}],hP=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=UA(gP),{isImporting:s,waitingForInput:i,error:a}=WA(t);return GA({onEscape:__name(()=>{i&&((a||o)&&n?n():e())},"onEscape"),onEnter:__name(()=>{i&&((a||o)&&n?n():e())},"onEnter"),enabled:s||i}),Q.createElement(te,{flexDirection:"column",padding:1},o&&Q.createElement(ZA,{error:o}),!o&&Q.createElement(mP,{steps:r}),Q.createElement(pP,{isImporting:s,waitingForInput:i}))},"ImportProgress"),fP=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?Q.createElement(XA,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?Q.createElement(hP,{onComplete:r,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),yP=__name(({onComplete:e,autoLearn:t=!1})=>{X(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=VA({autoLearn:t,onShouldSkip:e}),{step:s,setStep:i}=KA({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=QA({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?Q.createElement(YA,{error:r}):"done"===s?null:Q.createElement(fP,{step:s,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const o=[];for(const e of n)if(o.unshift(e),r-=getEntryCharCount(e),r<=0)break;return o}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var wP=K(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,transcriptMode:s,tasteOnboardingEntryId:i,autoLearnTaste:a,showTasteSkipBanner:l,retryAttempt:u,input:d,setInput:m,fileSearchQuery:g,setFileSearchQuery:h,showFileList:f,setShowFileList:y,showProviderSelector:w,showModelSelector:S,showMemorySelector:E,showMcpManager:C,showAgentsConfig:v,showRewindSelector:k,showLoginOverlay:T,showUsageOverlay:_,showAddDirModal:x,showCompactModeSelector:A,authComponentInfo:P,status:I,currentProvider:N,currentModel:R,showProviderNotification:M,shareInfo:L,showShareNotification:$,unshareNotificationMessage:D,updateStatus:O,updateFailedInfo:F,creditWarning:q,permissionMode:j,hintMessage:U,pendingExitKey:B,tasteLearningEnabled:z,interactionTokens:H,contextUsage:W,historyManagerRef:G,executionState:V,contextEngineRef:K,onSubmit:Y,onCommand:J,onToggleAutoAccept:X,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,onTasteOnboardingComplete:se,permissionPanel:ie,questionPanel:ae,onRewindSelect:le,onRewindCancel:ce,onLoginComplete:ue,onLoginCancel:de,setShowProviderSelector:me,setShowModelSelector:pe,setShowMemorySelector:ge,setShowMcpManager:he,setShowAgentsConfig:fe,setShowAddDirModal:ye,setShowUsageOverlay:we,handleProviderSelect:Se,handleProviderCancel:Ee,handleModelSelect:be,handleModelCancel:Ce,handleCompactModeSelect:ve,handleCompactModeCancel:ke,handleAuthSuccess:Te,handleAuthCancel:_e}){const xe=Z(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Ae=useTerminalWidth(),Pe=Z(()=>"off"===s?xe:getBudgetedFeed(xe,"limited"===s?15e3:5e4),[xe,s]),Ie=Z(()=>"off"===s?0:Math.max(0,xe.length-Pe.length),[xe.length,Pe.length,s]),Ne=Z(()=>0===Ie?Pe:Pe.filter(e=>"user"!==e.role),[Pe,Ie]),Re=ee(()=>fe(!1),[fe]),Me=ee(()=>ge(!1),[ge]),Le=ee(()=>he(!1),[he]),$e=ee(()=>ye(!1),[ye]),De=ee(()=>pe(!0),[pe]),Oe=!("off"!==s||ie||ae||w||S||P||E||C||v||k||T||_||x||A||i);return Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(NA,{staticKey:o,feed:Ne,showHeader:!0,expandedToolOutput:"off"!==s,currentModel:R,currentProvider:N,hiddenCount:Ie}),i&&Q.createElement(yP,{onComplete:se,autoLearn:a}),l&&Q.createElement(TasteSkipMessage,null),t.map(e=>e.metadata?.isAgent?Q.createElement(MA,{key:e.id,entry:e}):Q.createElement(te,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==s))),Q.createElement(RetryMessage,{attempt:u}),ae,ie,"off"!==s&&Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"─".repeat(Ae))),Q.createElement(te,{paddingRight:1},Q.createElement(ne,{backgroundColor:pr.BG,color:pr.FG,bold:!0},`${ET}DETAILED TRANSCRIPT${ET}`),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{bold:!0},"ctrl+o"),Q.createElement(ne,{color:ar.DIM}," to toggle"),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{bold:!0},"ctrl+e"),Q.createElement(ne,{color:ar.DIM}," ","to"," ","limited"===s?"show all":"collapse"))),Oe&&Q.createElement(vA,{queuedMessages:n,isProcessing:r,executionState:V,status:I,input:d,setInput:m,onSubmit:Y,showFileList:f,setShowFileList:y,fileSearchQuery:g,setFileSearchQuery:h,onCommand:J,outputTokens:H,contextUsage:W,tasteLearning:z,shareInfo:L,showShareNotification:$,unshareNotificationMessage:D,updateStatus:O,updateFailedInfo:F,creditWarning:q,currentProvider:N,showProviderInfo:M,permissionMode:j,onToggleAutoAccept:X,hintMessage:U,historyManager:G.current,pendingExitKey:B,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,retryAttempt:u,onAltP:De}),w&&Q.createElement(te,{marginY:1},Q.createElement(FA,{onSelect:Se,onCancel:Ee,currentProvider:N})),S&&Q.createElement(te,{marginY:1},Q.createElement(OA,{onSelect:be,onCancel:Ce,currentModel:R,currentProvider:N})),A&&Q.createElement(te,{marginY:1},Q.createElement(Qx,{onSelect:ve,onCancel:ke})),v&&Q.createElement(te,{marginY:1},Q.createElement(Gx,{onCancel:Re})),E&&Q.createElement(te,{marginY:1},Q.createElement(_A,{onClose:Me})),C&&Q.createElement(te,{marginY:1},Q.createElement(TA,{onClose:Le})),k&&K.current&&Q.createElement(te,{marginY:1},Q.createElement(jA,{checkpoints:K.current.listCheckpoints(),onSelect:le,onCancel:ce})),P&&Q.createElement(te,{marginY:1},Q.createElement(P.Component,{onSuccess:Te,onCancel:_e})),T&&Q.createElement(te,{marginY:1},Q.createElement(kA,{onComplete:ue,onCancel:de})),x&&Q.createElement(te,{marginY:1},Q.createElement(Ix,{onClose:$e})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:C,creditWarning:v,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:A,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return Q.createElement(L_,{staticKey:o.staticKey,onTrust:k,onExit:T});if(o.showSessionSelector)return Q.createElement(D_,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!s.projectTrusted)return null;const I=a.pendingQuestion?Q.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,N=a.pendingPermission?Q.createElement(V_,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null;return o.showLearningFeed?Q.createElement(LearningView,{setShowLearningFeed:o.setShowLearningFeed,setStaticKey:o.setStaticKey,onExit:()=>i.setShouldExit(!0)}):o.showTasteConfig?Q.createElement(TasteConfigView,{staticKey:o.staticKey,setShowTasteConfig:o.setShowTasteConfig,loadTasteStatus:P}):o.showSkillsConfig?Q.createElement(SkillsConfigView,{staticKey:o.staticKey,setShowSkillsConfig:o.setShowSkillsConfig}):o.showUsageOverlay?Q.createElement(UsageView,{staticKey:o.staticKey,setShowUsageOverlay:o.setShowUsageOverlay}):o.showContextView?Q.createElement(ContextConfigView,{staticKey:o.staticKey,contextEngineRef:u,setShowContextView:o.setShowContextView,setInput:w}):o.showStatusView?Q.createElement(StatusConfigView,{staticKey:o.staticKey,setShowStatusView:o.setShowStatusView,setInput:w}):Q.createElement(wP,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:o.staticKey,transcriptMode:o.transcriptMode,tasteOnboardingEntryId:s.tasteOnboardingEntryId,autoLearnTaste:s.autoLearnTaste,showTasteSkipBanner:o.showTasteSkipBanner,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:o.showFileList,setShowFileList:o.setShowFileList,showProviderSelector:o.showProviderSelector,showModelSelector:o.showModelSelector,showMemorySelector:o.showMemorySelector,showMcpManager:o.showMcpManager,showAgentsConfig:o.showAgentsConfig,showRewindSelector:o.showRewindSelector,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:C,creditWarning:v,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:A,permissionPanel:N,questionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel})}__name(renderView,"renderView");var SP=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u,sessionTitleHolder:d})=>{const{exit:m}=ae(),{stdout:g}=oe();X(()=>{prefetchBillingContext()},[]);const[h,f]=Y(""),[y,w]=Y(""),S=J(!1),E=J(!1),C=J(null),v=J(null),k=useUiOverlays(),T=useFeed(),_=useSession(),x=useStatus(s),A=useAuth(),P=usePendingOps(),I=useOnboarding(),N=useExit(),{executeBash:R,executionState:M}=Dk(),L=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:x.setStatus,contextEngineRef:v}),{createContextEngineCallbacks:$}=useContextEngine({sessionId:_.sessionId,sessionLoaded:_.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:I.projectTrusted,setFeed:T.setFeed,setLiveEntries:T.setLiveEntries,setQueuedMessages:T.setQueuedMessages,queuedMessagesRef:T.queuedMessagesRef,setStatus:x.setStatus,pinnedStatusRef:x.pinnedStatusRef,setRetryAttempt:x.setRetryAttempt,setInteractionTokens:x.setInteractionTokens,setContextUsage:x.setContextUsage,setCurrentProvider:A.setCurrentProvider,shareInfoRef:x.shareInfoRef,permissionsService:L.permissionsService,permissionModeRef:L.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:v}),{onCommand:D}=useCommandCtx({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:N,permissionState:L,contextEngineRef:v,isSubmittingRef:S,executeBash:R,createContextEngineCallbacks:$,setInput:f}),{loadTasteStatus:O,loadCurrentProvider:F,onSubmit:q}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:g,feedState:T,sessionState:_,statusState:x,authState:A,onboarding:I,uiOverlays:k,permissionState:L,contextEngineRef:v,isSubmittingRef:S,initialPromptSubmittedRef:E,historyManagerRef:C,executeBash:R,createContextEngineCallbacks:$,setInput:f,onCommand:D});useLifecycle({exit:m,feedState:T,exitState:N,statusState:x,authState:A,onboarding:I,uiOverlays:k,skipOnboarding:l,contextEngineRef:v,sessionTitleHolder:d});const{handleToggleAutoAccept:j,handleDoubleEscapeEmpty:U,handleTasteOnboardingComplete:B,handleTrust:z,handleNoTrust:H}=useHandlers({resume:e,feedState:T,onboarding:I,uiOverlays:k,exitState:N,pendingOps:P,permissionState:L,statusState:x,authState:A,contextEngineRef:v,loadTasteStatus:O,loadCurrentProvider:F,setInput:__name(e=>f(e),"setInput")}),W=useMainActionCallbacks({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,permissionState:L,contextEngineRef:v,createContextEngineCallbacks:$,setInput:f}),{creditWarning:G}=useCreditWarning({interactionTokens:x.interactionTokens});return renderView({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:N,pendingOps:P,permissionState:L,contextEngineRef:v,historyManagerRef:C,executionState:M,actionCallbacks:W,onSubmit:q,onCommand:D,input:h,setInput:f,fileSearchQuery:y,setFileSearchQuery:w,updateFailedInfo:i,creditWarning:G,handleTrust:z,handleNoTrust:H,handleToggleAutoAccept:j,handleDoubleEscapeEmpty:U,handleTasteOnboardingComplete:B,loadTasteStatus:O})},"InteractiveCLI");zr(),ir(),Rr();var EP=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),bP=ce.hex(ar.DIM),CP=__name(e=>{const t=getInvokedCommandName(),n=tt([e]);return`${bP("To continue this session, run:")}\n${bP(`${t} --resume ${n}`)}\n`},"formatResumeHint"),vP=__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"),kP=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),TP=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),_P=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{let r;return e.permissionMode?r=e.permissionMode:e.plan&&(r="plan"),{resume:"boolean"==typeof e.resume?e.resume:void 0,resumeSessionId:t,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:r,sessionTitleHolder:n}},"buildInteractiveCLIProps"),xP=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),AP=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),PP=__name(()=>{AP()},"initializeTerminal"),IP=__name(async(e={})=>{const t=vP(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),PP(),"string"==typeof e.resume){const t=e.resume;await rk.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await rk.findSessionByName(t);r||(console.error(`No session named "${t}" found.`),process.exit(1)),n=r.id}if(kP(e)&&!n){const e=await rk.isProjectInitialized(),t=e?await rk.listSessions():[],n=TP({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const r={},o=_P({options:e,resumeSessionId:n,sessionTitleHolder:r}),s=xP(),i=ie(Q.createElement(SP,{...o}),s);registerInkControl({clear:i.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await i.waitUntilExit();const a=await(r.loadTitle?.());if(a){const e=EP(a);e&&process.stdout.write(CP(e))}},"interactiveMode");Ao(),Ot(),wn(),fb(),tb();var NP=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${Pe.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${Pe.cross} Login failed: ${getErrorMessage2(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||NP()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated");var RP=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),MP=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),LP=__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"),$P=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:e.resume,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),DP=__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=DP(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:t.model,benchmarkOutput:t.benchmarkOutput})}const n=RP(e);await MP();const r=LP(t),o=$P({options:t,runtimeOptions:r,initialPrompt:n});await IP(o)}__name(interactiveModeAction,"interactiveModeAction"),Ot(),Kn(),hs(),Jr(),ZE(),fb(),globalThis.COMMAND_CODE_CWD=process.cwd();var OP=__name(()=>process.cwd(),"getCwd"),FP=__name(()=>process.argv.slice(2),"getArgs"),qP=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),jP=__name(()=>{const e=OP(),t=FP(),n=qP(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){if(jP(),process.argv.includes("--ide-setup")){const e=await runIDESetup();formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}"update"!==FP()[0]&&await maybeRunPendingUpdate(),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100).unref()}__name(preRun,"preRun"),Ot(),wn(),Kn(),Co(),io();var UP=getPackageJson(),BP=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=UP.version,t=getInvokedCommandName(),n=Uv.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ce.bold("Command Code")+ce.gray(` v${e}`)),console.log(ce.gray(Dv)),console.log(),console.log(ce.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ce.bold("Options"));for(const e of jv){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ov)+ce.gray(e.description))}console.log(),console.log(ce.bold("Commands"));for(const e of Bv){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ov)+ce.gray(e.description))}console.log(),console.log(ce.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Ov)+ce.gray(e.description));console.log(),console.log(ce.bold("Keyboard Shortcuts"));for(const e of qv)console.log(" "+e.key.padEnd(Ov)+ce.gray(e.description));console.log(),console.log(ce.bold("Examples"));for(const e of Hv){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ov)+ce.gray(e.description))}console.log(),console.log(ce.cyan("❯")+" "+ce.gray(Wv.replace(/cmd/,t))),console.log(),console.log(ce.bold("Links"));for(const e of zv)console.log(" "+e.key.padEnd(Ov)+ce.cyan(e.description));console.log()}function createProgram(){const e=new Ie;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(UP.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by name, or 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)").addOption(new Ne("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ne("--yolo","Bypass all permission prompts (alias for --dangerously-skip-permissions)").implies({dangerouslySkipPermissions:!0})).option("--plan","Start in plan mode (read-only exploration and planning)").addOption(new Ne("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Ne("--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("--max-turns <number>","Maximum conversation turns in print mode (default: 10)",e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new Error("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--ide-setup",Fv).option("--add-dir <directory>","Add directory to workspace context",BP,[]).addOption(new Ne("--model <model>","Override model for this run").hideHelp()).addOption(new Ne("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ne("--experimental","Enable experimental features").hideHelp()).addOption(new Ne(qt).hideHelp()).addOption(new Ne(jt).hideHelp()).addOption(new Ne("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ne("--local","Use local server").hideHelp()).addOption(new Ne("--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 i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ot(),hs(),Oo(),RE(),Eb(),WE(),Co(),fb(),Ot(),__name(isTTY,"isTTY");var zP=!1;function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=w.platform(),t=w.arch();let n,r,o,s;try{const e=await getAuthenticatedEntity();e.success&&(n=e.user?.userName,r=e.user?.id,o=e.org?.login,s=e.org?.id)}catch{}if(!r)try{const e=await loadCredentials();r=e?.userId}catch{}systemInfo({userName:n,userId:r,orgLogin:o,orgId:s,platform:e,arch:t})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){zP||(zP=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=w.platform(),r=w.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Re("Opening GitHub issues...").start();try{await pe(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"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),fb(),Ot(),ro(),__name(openGitHubIssue,"openGitHubIssue");var HP=new Ie("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ot();var WP=new Ie("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const t=getSystemInfo(),{waitUntilExit:n}=ie(Q.createElement(GT,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}Ot(),Ot(),__name(runInfo,"runInfo");var GP=new Ie("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=ie(Q.createElement(hP,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}Ot(),wn(),Ot(),__name(runLearnTaste,"runLearnTaste"),Kn(),hs();var VP=new Ie(tn.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:cs.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 Ie("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 Ne("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ce.red(`Error: Invalid server name '${e}'`)),console.error(ce.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(ce.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ce.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ce.red("Error: URL is required for http transport")),console.error(ce.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ce.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(ce.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ce.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ce.cyan("Server requires OAuth authentication.")),isSecureOrLoopback(t)||(console.error(ce.red(`Error: Server '${e}' requires OAuth, but URL '${t}' is not secure.`)),console.error(ce.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ce.gray("Switch the URL to https:// or use a non-OAuth server.")),process.exit(1));let n,o="command-code";if(r.metadata.registrationEndpoint){console.log(ce.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${RS}/callback`]});e&&(o=e.clientId,n=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},console.log(ce.gray("A browser window will open for authentication.\n"));const a=await performOAuthFlow(e,t,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ce.gray(` ${e}`))},"onStatus")});a.success?console.log(ce.green("✓ Successfully authenticated")):(i=!0,console.log(ce.yellow(`Warning: Authentication failed: ${a.error}`)),console.log(ce.gray("You can retry with: cmd mcp auth "+e)),console.log(ce.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(ce.red("Error: Command is required for stdio transport")),console.error(ce.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(ce.red("Error: Command is required for stdio transport")),console.error(ce.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ce.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);s={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:s,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(ce.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ce.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===s.transport)console.log(ce.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ce.gray(` Command: ${e}`))}console.log(""),console.log(ce.cyan("Next steps:")),console.log(ce.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ce.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(ce.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(ce.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(ce.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new Ie("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ce.yellow("\nNo MCP servers configured\n")),console.log(ce.gray("Add a server with:")),console.log(ce.gray(" cmd mcp add --transport http <name> <url>")),console.log(ce.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ce.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ce.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ce.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ce.green("enabled"):ce.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ce.green(Pe.tick):ce.red(Pe.cross):o.config.headers||o.config.env?ce.green(Pe.tick):ce.gray("-"),console.log(` ${ce.white(o.name.padEnd(t))} ${ce.cyan(o.config.transport.padEnd(n))} ${ce.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ce.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ie("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(ce.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ce.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ce.dim("Scope:")} ${r}`),console.log(` ${ce.dim("Transport:")} ${n.transport}`),console.log(` ${ce.dim("Status:")} ${n.enabled?ce.green("enabled"):ce.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ce.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ce.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(` ${ce.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ce.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ce.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(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ie("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ne("-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(ce.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ce.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ce.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ce.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ie("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 Ne("-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(ce.red(`Error: Invalid server name '${e}'`)),console.error(ce.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(ce.red("Error: Invalid JSON")),console.error(ce.gray("Make sure to quote the JSON string properly")),console.error(ce.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 i=bS.safeParse(o);if(!i.success){console.error(ce.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ce.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ce.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ce.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ce.cyan("Starting OAuth authentication...")),console.log(ce.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,a.url??"",t,{...s&&{port:s},onStatus:__name(e=>{console.log(ce.gray(` ${e}`))},"onStatus")});n.success?console.log(ce.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ce.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ce.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ce.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(ce.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ce.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ce.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ce.gray(` Command: ${e}`))}console.log(""),console.log(ce.cyan("Next steps:")),console.log(ce.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ie("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(ce.yellow("No servers with stored authentication."));console.log(ce.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ce.yellow("expired"):ce.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ce.red("Error: Server name is required")),console.error(ce.gray(`Usage: ${n} mcp auth <server>`)),console.error(ce.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ce.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ce.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ce.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ce.gray(" A refresh token is available for re-authentication"));else{if(console.log(ce.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ce.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ce.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ce.green(`✓ Cleared authentication for '${e}'`)):console.log(ce.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ce.red(`Error: MCP server '${e}' not found`)),console.error(ce.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(ce.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(ce.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(ce.cyan(`Authenticating with '${e}'...`)),console.log(ce.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,r.config.url??"",o,{onStatus:__name(e=>{console.log(ce.gray(` ${e}`))},"onStatus")});if(s.success)return console.log(ce.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ce.gray("Restart the session to connect with the authenticated server."));console.error(ce.red(`\nError: Authentication failed: ${s.error}`)),console.log(ce.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ie("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}async function runCommand(e){return new Promise((t,n)=>{const r=be(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let o="",s="";r.stdout.on("data",e=>{o+=String(e)}),r.stderr.on("data",e=>{s+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${s?`: ${s.trim()}`:""}`)):t({stdout:o,stderr:s})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await v.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await v.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const o=parseGitHubSource({source:n});if(!o){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const s=String(t.maxCommits??200),i=`https://github.com/${o.owner}/${o.repo}.git`,a=await v.mkdtemp(e.join(w.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",s,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await v.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${o.owner}/${o.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${o.owner}/${o.repo}`,repoDir:a,repoName:o.repo,github:o,cleanup:__name(async()=>{await v.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),o=new jw({baseUrl:r}),s=new Jk({request:o,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await s.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(ce.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let o=0;for(let s=0;shouldContinueExtraction({offset:s,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:o});s+=10){const i=t.slice(s,s+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;o++;const s=groupCrossFilePatterns(t);for(const t of s.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const o=[`Commit: ${e.subject}`];o.push(`File: ${t.file}`),t.context&&o.push(`In: ${t.context}`);const s=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(s&&o.push(s),r.push({text:`${truncate2(t.removed,60)} → ${truncate2(t.added,60)}`,evidence:o,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${o} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],o=e.branch?[e.branch]:[],s=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...o,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(s)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",o=""]=e.split("");return{hash:t.trim(),subject:o.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let o="",s="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:o,context:s||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),o=e.match(/b\/(.+)$/)?.[1]??"",s="",l=[],isNoiseFile(o)&&(o="");continue}if(e.startsWith("@@")){g(),m(),s=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!o)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Ot(),Ot(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ot(),__name(listMcpCommand,"listMcpCommand"),Ot(),__name(getMcpCommand,"getMcpCommand"),Ot(),__name(removeMcpCommand,"removeMcpCommand"),Ot(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ot(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ot(),wn(),Ot(),Sb(),Ot(),wn(),Ot(),__name(runCommand,"runCommand"),Ot(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Ot(),sS(),fS(),Jr(),ao(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Ot(),Ot(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var QP=5,KP=3;function buildSnippet(e,t,n){const r=e??[],o=n??[],s=t.split("\n").map(e=>e.trimEnd());if(0===s.length&&0===r.length&&0===o.length)return;let i,a=0;s.length>KP?(i=s.slice(0,KP-1),a=s.length-i.length):i=s;const l=i.length+(a>0?1:0),u=Math.max(0,QP-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(o.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of o.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var YP=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return YP.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var JP=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),XP=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!JP.has(n)||!(!n.includes("[bot]")||!XP.some(e=>e.test(t)))}function truncate2(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let o=0;const s=__name(async()=>{for(;o<t.length;){const e=o++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>s())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:o}=e,s=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${s}Commits analyzed: ${o}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){Kk.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await Kk.waitForAuth()}catch{return Kk.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),Kk.markLearningComplete(),{summary:n()}}}t.isLocalSource||Kk.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const o="github"===r.type,s=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=o?e.resolve(process.cwd(),s):i;o&&Kk.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await v.mkdir(a,{recursive:!0}),Kk.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{Kk.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");Kk.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),Kk.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:s,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};Kk.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return Kk.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),Kk.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate2,"truncate"),__name(runBounded,"runBounded"),Ot(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Ot(),Ot(),Ot();var ZP=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return ZP.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Ot(),as(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Ot(),Ot();var eI=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],tI=[{id:"cloning",label:"Cloning repository"},...eI],nI=[Pe.bullet,Pe.squareSmallFilled,Pe.lozenge,Pe.star,Pe.triangleRight,Pe.triangleUp];function createInitialRepoLearnSteps(e){return(e??eI).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Ot();var rI={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var oI=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),sI=__name(e=>e??rI,"withBase");function useRepoLearnState(e){const t=e??eI,[n,r]=Y(()=>createInitialRepoLearnSteps(t)),[o,s]=Y(""),[i,a]=Y([]),[l,u]=Y(null),[d,m]=Y(!1),[g,h]=Y(!1),[f,y]=Y(null),[w,S]=Y(0),E=J(null),[C,v]=Y(null),k=ee(()=>{E.current=Date.now()},[]);return X(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),s(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,v(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(oI),void s("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),s(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=sI(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=sI(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):s(e.message):u(t=>{const n=sI(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),o=__name(()=>{h(e=>e||(r(oI),!0)),s(""),E.current&&v(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return Kk.on("reset",e),Kk.on("new-event",n),Kk.on("learning-complete",o),()=>{Kk.off("reset",e),Kk.off("new-event",n),Kk.off("learning-complete",o)}},[t]),{steps:n,currentMessage:o,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:C,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Ot(),Ot(),Rr();var iI=__name(({isComplete:e,hasError:t})=>Q.createElement(te,{flexDirection:"column",marginTop:1,marginBottom:0},Q.createElement(eP,null),Q.createElement(te,{marginTop:0},Q.createElement(ne,{color:ar.DIM},nP),Q.createElement(te,{marginLeft:2},t?Q.createElement(ne,{color:ar.DIM},"learning interrupted"):e?Q.createElement(ne,{color:cr.TEXT},"learned your coding taste"):Q.createElement(rP,null)))),"RepoLearnTastePill");Ot(),Rr();var aI=__name(({status:e})=>"active"===e?Q.createElement(te,null,Q.createElement(ne,{color:ar.YELLOW},Q.createElement(je,{type:"dots"})),Q.createElement(ne,null," ")):"complete"===e?Q.createElement(ne,{color:pr.BG},Pe.square," "):Q.createElement(ne,{color:ar.DIM},Pe.circle," "),"StepStatusIndicator"),lI=__name(({steps:e,currentMessage:t})=>Q.createElement(te,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return Q.createElement(te,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},Q.createElement(te,null,Q.createElement(te,{marginRight:1},Q.createElement(aI,{status:e.status})),Q.createElement(ne,{bold:n,color:"complete"===e.status?ar.WHITE:n?ar.YELLOW:ar.DIM},e.label)),n&&t?Q.createElement(te,{marginLeft:3},Q.createElement(ne,{color:ar.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ot(),Rr();var cI=__name(({insights:e,insightCount:t})=>0===e.length?null:Q.createElement(te,{flexDirection:"column",marginTop:1,marginLeft:4},Q.createElement(ne,{color:ar.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>Q.createElement(ne,{key:`${t}-${e}`,color:ar.DIM},nI[t%nI.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ot(),Rr();var uI=__name(({message:e})=>Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.RED,paddingX:2,paddingY:1,marginTop:1},Q.createElement(ne,{color:ar.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,e))),"RepoLearnErrorPanel");Ot(),Rr(),Xr();var dI=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return Q.createElement(te,{flexDirection:"column",marginLeft:3},Q.createElement(te,{marginBottom:1,flexDirection:"row"},Q.createElement(ne,{color:ar.DIM},nP),Q.createElement(te,{marginLeft:2},Q.createElement(ne,{color:cr.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),Q.createElement(te,{flexDirection:"column",marginLeft:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," Taste stored in"," "),Q.createElement(Kr,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:ar.CYAN})),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," Share your coding taste: ",Q.createElement(ne,{color:ar.CYAN},"npx taste push --all")))),Q.createElement(te,{marginTop:1,marginLeft:1},Q.createElement(ne,{color:ar.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ot(),Rr();var mI=__name(({done:e,error:t})=>t?Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0},"Press ESC to exit")):e?Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0},"Press ENTER to continue")):Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"ESC to cancel")),"RepoLearnFooter");Ot(),Rr();var pI=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=Z(()=>ex(n),[n]);return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ix,null,r.trimEnd())),e?Q.createElement(ne,{color:ar.WHITE},e):Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.WHITE},"Learning your coding taste from ",Q.createElement(ne,{bold:!0,color:ar.CYAN},t??"repository")),Q.createElement(ne,{color:ar.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?Q.createElement(uI,{message:e}):t?Q.createElement(dI,{summary:n,elapsedSeconds:r}):Q.createElement(cI,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=J(!1);return X(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),se((e,n)=>{if(s.showLogin)return;const r=n.escape||""===e,o=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(s.done||s.error)&&o&&t({published:!1,cancelled:!!s.error})}),s.showLogin?Q.createElement(te,{flexDirection:"column"},Q.createElement(pI,{text:r,repoName:o}),Q.createElement(kA,{onComplete:(e,t)=>{s.setShowLogin(!1),e?Kk.resolveAuth():Kk.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),Kk.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):Q.createElement(te,{flexDirection:"column"},Q.createElement(pI,{text:r,repoName:o}),Q.createElement(iI,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),Q.createElement(lI,{steps:s.steps,currentMessage:s.currentMessage}),Q.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),Q.createElement(mI,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{Kk.reset();const r=new AbortController;let o,s,i=!1,a=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,Kk.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),Kk.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),Kk.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=ie(Q.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{Kk.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),fb();var gI=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new Ie("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",gI("--max-commits"),200).addOption(new Ne("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(gI("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await v.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),o=await resolveDisplayName(t.source),s=!await getAuthKey();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:o}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:s,signal:e});return i=o?.cleanup,r},"runTask");if(r){const t=n?void 0:[...tI];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:o,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),yb(),await IP({skipOnboarding:!0})}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(w.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")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ot(),Ot(),Ot(),wn(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ot(),Ot();var hI=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||hI.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:hI.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(hI.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:i}}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(!hI.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)),i=s.length>0?s[s.length-1]:null;if(!i)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?o.substring(0,i.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:`${Pe.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&i.push(`${o.length} warning${o.length>1?"s":""}`);const a=r.length>0?Pe.cross:Pe.warning;return{valid:s,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ce.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ce.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`${ce.green(e)} ${ce.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?ce.red(t.summary):ce.yellow(t.summary),"",...formatIssueGroup(r,ce.red,ce.bold(ce.red("Errors:"))),...formatIssueGroup(o,ce.yellow,ce.bold(ce.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"),Ot(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var fI=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:o}=e;fI.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 yI=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,wI=/^\[cmd\]: https:\/\/commandcode\.ai\/$/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}):yI.test(s)||wI.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),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:i,rawLines:o});return checkFinalCategory({state:i,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var SI=__name(e=>"local-global"===e?"global":"project","locationLabel"),EI=__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 D(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${SI(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});D(o)&&r.push({path:o,displayName:"taste.md"});const s=(await v.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>D(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 v.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await v.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,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:i}}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 EI({file:"all",error:`No taste files found in ${SI(n)}`});const s=await Promise.all(r.map(lintFile)),i=s.reduce((e,t)=>e+t.errors,0),a=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return EI({file:"all",error:`No taste files found in ${SI(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),i=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return D(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):EI({file:"all",error:`No taste directory found in ${SI(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"),Ot(),hs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var bI=ce.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(`${ce.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?`${ce.dim(t[1])}${ce.green(t[2])}${ce.white(t[3]??"")}${t[4]?ce.dim(t[4]):""}`:ce.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ce.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 CI=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return St(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:CI})}function getProfileLink(e){return St(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:CI})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return wt(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(ce.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(`${ce.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(ce.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ie("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 ${ce.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(`${ce.green(Pe.tick)} All ${ce.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ce.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ce.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(ce.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,n=await v.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await v.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){if(!e)return Db+"\n\n";const t=e.trim();return t.startsWith(Lb)||t.startsWith(Ob)||t.startsWith(Fb)?e:Db+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Ot(),Ns(),Ot(),Ot(),Ot(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ot(),__name(formatPackage,"formatPackage"),Ot(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var vI="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:vI,category:e.name});return D(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await v.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:vI});if(!D(e))return[];const t=await v.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:vI,category:t});return D(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:vI});await v.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:vI,category:n.category}),s=e.dirname(o);await v.mkdir(s,{recursive:!0});const i=formatPackage({pkg:n});await v.writeFile(o,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Ot(),Ot();var kI="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!D(n))return null;const r=migrateHeader({content:await v.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),i=o.end<r.length-1?r.slice(o.end+1):[],a={before:s.join("\n").trim(),after:i.join("\n").trim()},l=[...s,...i].join("\n").trim();return""===l&&await v.rm(n,{force:!0}),""!==l&&await v.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:kI}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:kI,category:n}),i=e.dirname(s);return D(i)&&await v.rm(i,{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=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=o.trim()+t,void await v.writeFile(n,e.trim()+"\n","utf-8")}let s="";D(n)&&(s=await v.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await v.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:kI,category:n.category}),i=e.dirname(s);await v.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await v.writeFile(s,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=ensureHeader(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=l.trim()+t,void await v.writeFile(r,e.trim()+"\n","utf-8")}let u="";D(r)&&(u=await v.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await v.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var TI="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:TI,category:e.name});return D(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:TI});if(!D(e))return[];const t=[],n=getRootTasteFile({target:TI});if(D(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await v.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:TI});await v.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:TI}),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 exists2(){const e=getTastePath({target:TI});return D(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!D(n))return;const r=await v.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:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),o&&l.append("description",o),l.append("type",s),l.append("isPublic",String(i)),l.append("overwrite",String(a));const u=formatPackage({pkg:r}),d=new Blob([u],{type:"text/markdown"}),m=new File([d],"taste.md",{type:"text/markdown"});if(l.append("files[taste.md]",m),"category"===s)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!D(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!D(f))return l;const y=await v.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1,overwrite:s=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(o)),i.append("overwrite",String(s));const a=getRootTasteFile({target:"local-project"});if(D(a)){const e=await v.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}const l=t.map(e=>appendCategoryFile(i,e));return await Promise.all(l),i}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,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:cs.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),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}${Bt.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}${Bt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:cs.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()}${Bt.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:cs.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,overwrite:o=!1}=e,s=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:o}),a=`${getApiBaseUrl()}${Bt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:l.status}),await l.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o=!1,overwrite:s=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o,overwrite:s}),l=`${getApiBaseUrl()}${Bt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:a});u.ok||throwTrackedError({message:await parseApiError({response:u,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:u.status,extra:{"package.count":t.length}}),await u.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${Bt.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 v.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 Ie("list").alias("ls").option("-g, --global","List global packages").addOption(new Ne("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ne("--staging","Use staging environment").hideHelp()).description(`List available packages ${ce.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Ot(),fS(),Ot(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),wn(),Ot(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),Eb(),hs(),Ot(),fb(),hs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ot(),fS(),fb(),wn(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),Kn(),__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 _I={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?_I.remote:e.global?_I.global:_I.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Pe.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Pe.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` ${ce.white(e.category)}${e.isPublic?ce.green(" [public]"):""}${e.isPublic&&e.starCount?ce.yellow(` ${Pe.star}${e.starCount}`):""}${e.downloadCount?ce.gray(` ${Pe.arrowDown}${e.downloadCount}`):""}${n}${ce.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?Re(`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${bI} Packages`),console.log(`${ce.gray("⎿")} ${ce.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(ce.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(ce.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 v.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 ft([{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"),Ot(),Ot(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var xI=new Set(["local-project","local-global","remote-project","remote-user"]);async function open11(e){const{package:t,target:n}=e;if(!xI.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=Et.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 Ie("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 ${ce.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 pe(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ce.green(Pe.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open11({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ce.green(Pe.tick)} Opened ${ce.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open11,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Ot(),Ot(),Ot(),Ot();var AI=null,PI=!1;function setActiveSpinner(e){AI=e}function stopActiveSpinner(e){AI&&(AI.stop(e),AI=null)}function setPrompted(e){PI=e}function wasPrompted(){return PI}function beginPrompt(e,t){stopActiveSpinner(),Ue.intro(ce.dim(e)),t&&Ue.log.message(ce.dim(t)),setPrompted(!0)}function handleCancel(e){Ue.isCancel(e)&&(Ue.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ue.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ue.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),Ue.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ce.green(`'${t}'`)} from ${n}`,s),Ue.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ce.dim(`(from ${n})`)}`);const i=await Ue.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(i);const a=i;return startStrategySpinner(a),a}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),Ue.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ce.green(`'${t}'`)} to global`,o),Ue.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Ue.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 i=s;return startStrategySpinner(i),i}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),Ue.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ce.green(`'${t}'`)} from global`,o),Ue.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Ue.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 i=s;return startStrategySpinner(i),i}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),Ue.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=St(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ce.green(`'${t}'`)} to ${n}`,s),Ue.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Ue.log.info(`Current package: ${ce.cyan(i)} ${ce.dim("(review)")}`);const a=await Ue.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ue.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=St(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ce.green(`'${t}'`)} to ${n}`,s),Ue.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Ue.log.info(`Current package: ${ce.cyan(i)} ${ce.dim("(review)")}`);const a=await Ue.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(a);const l=a;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 i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{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,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void s.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});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:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:o,flagStrategy:s,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:o,flagStrategy:s,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:o,flagStrategy:s,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Ot(),Ot(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ot(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var II=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),NI=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),RI=__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,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void s.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});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 II({pkg:"all",error:`Invalid source: ${n}`});const s=RI(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return II({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return II({pkg:"all",error:`No taste packages found in ${s}`});const a=validatePackages({packages:i,label:s});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=NI();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,i=await downloadPackage({owner:t,packageName:n});if(!i)return II({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:o,result:s};return"project"===a?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=NI();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return II({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Ue.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,i=wasPrompted()?"":`${Pe.tick} `,a=r?ce.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ce.green(i)}Replaced ${ce.green(`'${t}'`)} taste package in project`+a;if(s){const e=formatMergeParts(s);return`${ce.green(i)}Pulled ${ce.green(`'${t}'`)} taste package from ${n} ${ce.gray(`(${e.join(", ")})`)}`+a}return`${ce.green(i)}Pulled ${ce.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const o=t.packagesPulled[0],s=t.filePaths?.[o],i=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+o.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return s.length>0&&l.push(wrapLine(`${ce.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ce.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${ce.dim("Skipped")} (${o.length}) ${ce.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Ue.log.message(l.join("\n")),Ue.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ce.green(Pe.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ce.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ie("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 Ne("--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 Ne("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ce.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(Re("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(Re("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 jw({baseUrl:e}),n=await t.get({endpoint:Bt.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 Ue.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()?"":`${Pe.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ce.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${Pe.tick} `;if(!a)return logResult2(`${ce.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?` ${ce.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ce.green(l)}Replaced ${s} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ce.green(l)}Pushed ${s} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${ce.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${ce.green(l)}Pushed ${s} to ${a}${h}`),(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,i=s?o:"global",a=wasPrompted()?"":`${Pe.tick} `,l=!s&&o?ce.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ce.green(a)}Replaced ${ce.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ce.green(a)}Pushed ${ce.green(`'${r}'`)} taste package to ${i} ${ce.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ce.green(a)}Pushed ${ce.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",o=wasPrompted()?"":`${Pe.tick} `;return logResult2(wrapLine(`${ce.green(o)}Pushed ${ce.green(t.packagesPushed.length)} taste packages ${ce.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 i=getPackageLink({owner:o,packageName:s});r.has(i)||(r.add(i),console.log(ce.gray(` ${i}`)))}}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,i=[];o.length>0&&i.push(wrapLine(`${ce.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ce.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ce.dim("Skipped")} (${r.length}) ${ce.dim(r.join(", "))}`,4)),i.length>0&&Ue.log.message(i.join("\n"));const a=`${s} ${1===s?"package":"packages"}`;Ue.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),o=[];r.length>0&&o.push(wrapLine(`${ce.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ce.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ce.dim("Skipped")} (${n.length}) ${ce.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"),Ot(),__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"),Ot(),Kn(),Ot(),fS(),sS(),wn(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ot(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ot(),Eb(),Ot();var MI=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),LI=__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:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=o.reduce((e,t)=>e+t.learnings.length,0),u=LI(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l}),m=await resolvePushAllStrategy({flagStrategy:a,overwrite:o,existingProject:d,packagesToPush:n,projectName:l,owner:r});if("skip"===m)return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?s:d?.isPublic??!1,overwrite:"overwrite"===m});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 MI({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var $I=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),DI=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o,overwrite:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o,overwrite:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var OI=__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:i,result:a}=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 a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:s,isPublic:i,overwrite:!0}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:s,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=OI({target:n,category:t.category,owner:s});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e;if(!exists2())return $I({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return $I({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:i}):$I({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return $I({pkg:"all",error:`Invalid target: ${r}`});const m=DI();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,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:i}=e,a=await getPackage2({category:r});if(!a)return $I({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return $I({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:o,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?s:u?.isPublic??!1,g=DI();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,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(!exists2())return $I({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return $I({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 Ue.select({message:"Owner",options:r,initialValue:t});return Ue.isCancel(o)&&(Ue.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new Ie("push").description(`Push taste packages to remote ${ce.dim("(commandcode.ai)")} or global ${ce.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 Ne("--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 Ne("--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"),Ot(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var FI=__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};Ue.intro(ce.dim(`pushing ${t}`)),setPrompted(!0);const o=Ue.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Ue.outro(ce.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"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ce.dim(` Pushing ${s} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Re("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:FI(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 i=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:FI(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ue.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Re("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),i=o.length>0?o.length:s.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(ce.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Re("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 Ie(tn.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()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?ue.bold(ue.green(t)):ue.white(t);return`${ue.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ue.bold(ue.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ue.dim(`Run ${ue.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ue.dim("Try updating manually:")),console.log(ue.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ue.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Re("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(`${ue.green(Pe.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ue.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Re("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${Pe.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),trackError({error:sanitizeErrorForTelemetry({error:new Error("Update failed"),label:"cli_update_failed"}),context:{component:cs.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 ${ue.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"),Jr(),__name(createTasteCommand,"createTasteCommand"),Ot(),wn(),hs(),__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 qI=new Ie("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ot(),fb(),Eb();var jI=__name((e,t)=>`${Pe.info} ${e}: ${ue.cyan(t)}`,"formatInfoLine"),UI=__name(e=>ue.bold(`${e}:`),"formatSectionHeader"),BI=__name(e=>ue.red(e),"formatError"),zI=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),HI=__name(e=>["",UI("User Information"),jI("Name",e.name),jI("Email",e.email),jI("Username",e.userName)],"buildUserOutput"),WI=__name(e=>["",UI("Organization"),jI("Name",e.name),jI("Login",e.login)],"buildOrgOutput"),GI=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),VI=__name((e,t)=>{GI(HI(e)),t&&GI(WI(t)),console.log("")},"displayUserInfo"),QI=__name(e=>null!==e&&e.length>0,"validateApiKey"),KI=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Re("Fetching user information...").start();try{const t=await getAuthKey();QI(t)||(e.fail(BI('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();KI(n)||(e.fail(BI("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),VI(n.user,n.org)}catch(t){e.fail(BI(`Error: ${zI(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var YI=new Ie("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function normalizeGitUrl(e){let t=e.trim();const n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);return n?`https://${n[1]}/${n[2]}`:(t=t.replace(/\.git$/,""),t)}function validateGitRepo(){try{if("true"!==Se("git rev-parse --is-inside-work-tree",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error("Not inside a git repository.")}catch{throw new Error("Sandbox requires a git repository with a GitHub remote.")}let e;try{e=Se("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("No GitHub remote found. Add one with: git remote add origin https://github.com/you/repo")}const t=normalizeGitUrl(e);let n;try{n=Se("git branch --show-current",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("Failed to determine current branch.")}if(!n)throw new Error("Detached HEAD state. Please checkout a branch first.");if(!/^[\w./-]+$/.test(n))throw new Error("Branch name contains invalid characters. Please use a simpler branch name.");try{if(!Se(`git ls-remote --heads origin ${n}`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}catch(e){if(e instanceof Error&&e.message.includes("not found on remote"))throw e;throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}return{repoUrl:t,branch:n,isClean:""===Se("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}Ot(),Ot(),wn(),sS(),Rs(),fS(),Rn(),io(),Ot(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ot(),fS(),fb(),Ot();var JI=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return JI.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var XI={setting_up:"Setting up sandbox...",cloning:"Cloning repository..."};function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusEvent({event:e,state:t}){const n=e.data.status,r=XI[n],o="setup"===t.phase;if(t.isResume&&o&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&o&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=Re({stream:process.stderr,text:r}).start()),"running"===n)return t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="running",void(t.workingSpinner||(t.workingSpinner=Re({stream:process.stderr}).start()));if("completed"===n){t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="done";const n=e.data.prUrl;return void(n&&console.error(`PR: ${ue.cyan(n)}`))}if("failed"===n){const n=e.data.message||"Unknown error";return t.workingSpinner&&(t.workingSpinner.fail(n),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(n),t.currentSpinner=null),void(t.phase="done")}if("timed_out"===n)return t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null),void(t.phase="done");"cancelled"===n&&(stopAllSpinners({state:t}),t.phase="done",console.error(`\n${ue.yellow("Cancelled.")}`))}}function renderEvent({event:e,state:t}){if("status"!==e.type){if("pty"===e.type){const n=e.data.content;return void(n&&(t.workingSpinner&&t.workingSpinner.stop(),process.stdout.write(n),t.workingSpinner&&t.workingSpinner.start()))}if("error"===e.type){t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null);const n=e.data.message;console.error(`${Pe.cross} ${ue.red(n)}`)}}else renderStatusEvent({event:e,state:t})}function setupInputHandling({callbacks:e}){const t=__name(t=>{3===t[0]?e.onCancel():4===t[0]&&e.onDetach()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({ws:e}){const t=__name(()=>{e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({action:"resize",cols:process.stdout.columns,rows:process.stdout.rows}))},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}function sendTerminalSize({ws:e}){e.send(JSON.stringify({action:"resize",cols:process.stdout.columns||120,rows:process.stdout.rows||30}))}async function streamSession({sessionId:e,prompt:t,lastEventId:n=0,isResume:r=!1}){const o=getApiBaseUrl().replace(/^http/,"ws"),s=await getAuthKey();if(!s)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:s,...n>0?{lastEventId:String(n)}:{}}),a=`${o}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,o)=>{const s=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=Re({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.close(),console.error(`\n${ue.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${ue.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.readyState===WebSocket.OPEN&&s.send(JSON.stringify({action:"cancel"})),s.close(),console.error(`\n${ue.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:s}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");s.addEventListener("open",()=>{sendTerminalSize({ws:s}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${ue.yellow("[Ctrl+C]")} ${ue.dim("stop")} ${ue.yellow("[Ctrl+D]")} ${ue.dim("detach")}`),console.error(`${ue.dim("Session:")} ${ue.gray(e)}`),console.error(""),r&&(i.workingSpinner=Re({stream:process.stderr}).start())}),s.addEventListener("message",e=>{try{const n="string"==typeof e.data?e.data:e.data.toString(),r=JSON.parse(n);renderEvent({event:r,state:i}),void 0!==r.id&&(i.lastEventId=r.id),"status"===r.type&&isTerminalStatus(r.data.status)&&(s.close(),g(),t())}catch{}}),s.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),o(new Error("WebSocket connection failed"))}),s.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${ue.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${ue.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=L.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=L.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=at.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function startSandboxSession({repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}){return new jw({baseUrl:getApiBaseUrl()}).post({endpoint:Bt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateGitRepo();n.isClean||console.error(ue.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),s=e||await askQuestion(`${ue.bold("What do you want to do?")}\n${ue.cyan(">")} `);if(!s.trim())return void console.error(ue.yellow("No prompt provided. Aborting."));const i=s.trim().slice(0,nn.MAX_PROMPT_CHARS),a=Re({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:i,isInternalTeam:r,configFiles:o});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:i}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=e instanceof Ss,r=t?e.code:void 0;if(401===(t?e.status:void 0)||"UNAUTHORIZED"===r)console.error(ue.red("\nAuthentication failed. Try logging in again: cmd login"));else if("GITHUB_APP_NOT_INSTALLED"===r){const e=ue.cyan(ue.underline(n.repoUrl)),t=ue.cyan(ue.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${ue.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(ue.dim(" Then run this command again."))}else{const n=t&&"string"==typeof e.message?e.message:"Something went wrong. Please try again.";console.error(ue.red(`\n${n}`))}process.exit(1)}}function createSandboxCommand(){return new Ie("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(ue.red(t)),process.exit(1)}})}function validateSafeString(e,t){if(e.includes("..")||e.includes("\\"))throw new Error(`Invalid ${t}: path traversal sequences are not allowed.\nExpected format: owner/repo or owner/repo/path`);if(!/^[a-zA-Z0-9._/-]+$/.test(e))throw new Error(`Invalid ${t}: contains unsupported characters.\nOnly letters, numbers, hyphens, underscores, dots, and slashes are allowed.`)}function parseGitHubRepo(e){let t,n=e.replace(/^https?:\/\/github\.com\//,"");const r=n.lastIndexOf("@");r>0&&r<n.length-1&&(t=n.slice(r+1),n=n.slice(0,r),validateSafeString(t,"branch name"));const o=n.split("/");if(o.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[s,i,...a]=o;validateSafeString(s,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:s,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:o}=e;let s=`gh:${t}/${n}`;return r&&(s+=`/${r}`),o&&(s+=`#${o}`),s}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:o,path:s}=n;let i;if(s){const e=s.split("/").filter(Boolean);i=e[e.length-1]}else i=o;const a=t.join(S.tmpdir(),`commandcode-skill-${M()}`);await k.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:s}=await import("giget");try{await s(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,o),await s(e,{dir:a,force:!0,silent:!0})}const l=t.join(a,"SKILL.md"),u=t.join(a,"skill.md");let d=!1;try{await k.access(l),d=!0}catch{}if(!d)try{await k.access(u),d=!0}catch{}if(!d)throw new Error(`SKILL.md not found in ${e}. Make sure the repository contains a SKILL.md file.`);return{tempDir:a,skillName:i}}catch(e){if(await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,o)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:o,path:s,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(Ab(),xb)),u=await l({owner:r,repo:o,path:s,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${o}${s?` at path "${s}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await k.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await k.access(r),r}catch{}throw new Error(`SKILL.md not found in ${e}`)}function validateSkillName(e){const t=e.trim();if(!t||0===t.length)throw new Error("Invalid skill name: name cannot be empty");if(t.includes("/")||t.includes("\\"))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain path separators (/ or \\).`);if(t.includes(".."))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain parent directory references (..).`);if(t.startsWith("."))throw new Error(`Invalid skill name: "${e}". Skill names cannot start with a dot.`);if(!/^[a-z0-9-]+$/.test(t))throw new Error(`Invalid skill name: "${e}". Skill names must contain only lowercase letters, numbers, and hyphens.`);return t}async function validateSkillContent(e){const t=await resolveSkillMdPath(e),n=await k.readFile(t,"utf-8"),{data:r}=Ke(n),o=hf.parse(r);return{name:validateSkillName(o.name),description:o.description}}async function skillExists(e){const{skillName:n,location:r}=e,o="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),s=t.join(o,n);try{return await k.access(s),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:o=!1,force:s=!1,skillName:i,discoveredSkill:a,cachedTempDir:l}=r;let u,d,m=n;if(i){let e;if(a)e=a;else{const t=await discoverSkillsInRepo(n);if(0===t.skills.length)throw new Error(`No skills found in repository: ${n}`);const r=t.skills.find(e=>e.name.toLowerCase()===i.toLowerCase());if(!r){const e=t.skills.map(e=>e.name).join(", ");throw new Error(`Skill "${i}" not found in repository. Available skills: ${e}`)}e=r}const t=parseGitHubRepo(n),r=[t.path,e.path&&"."!==e.path?e.path:void 0].filter(Boolean).join("/"),o=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${o}@${t.branch}`:o}if(l&&a){u=a.path&&"."!==a.path?t.join(l,a.path):l,d=!1;try{await resolveSkillMdPath(u)}catch{const e=a.path&&"."!==a.path?`at ${a.path}`:"at root";throw new Error(`SKILL.md not found in cached directory ${e}. Make sure the repository contains a SKILL.md file.`)}}else u=(await fetchSkillFromGitHub(m)).tempDir,d=!0;try{const{name:e,description:n}=await validateSkillContent(u),r=e,i=o?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!s)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await k.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await k.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&s&&await k.rm(d,{recursive:!0,force:!0}),await k.rename(g,d)}catch(e){if(await k.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await k.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),o=n?"global":"project",s="global"===o?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(s,r);if(!await skillExists({skillName:r,location:o}))throw new Error(`Skill "${r}" not found in ${"global"===o?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===o?"":" Use -g/--global to check global skills."}`);await k.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t}=await loadAllSkillSummaries();return{global:e.map(e=>({name:e.name,description:e.description,location:"global",path:e.filePath})),project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath}))}}__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusEvent,"renderStatusEvent"),__name(renderEvent,"renderEvent"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(sendTerminalSize,"sendTerminalSize"),__name(streamSession,"streamSession"),__name(readLocalConfigFiles,"readLocalConfigFiles"),__name(askQuestion,"askQuestion"),__name(startSandboxSession,"startSandboxSession"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),Jr(),Ot(),Ot(),Ot(),Ot(),_b(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),Rf(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),wn();var ZI=[`${ue.dim("Usage:")}`,` ${ue.cyan("cmd skills add")} ${ue.white("<owner/repo>")}`,"",`${ue.dim("Examples:")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/my-skills")} ${ue.dim("# single-skill repo")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/skills/path/to/skill")} ${ue.dim("# specific path in repo")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/multi-skills -s my-skill")} ${ue.dim("# pick one from multi-skill repo")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/repo@branch")} ${ue.dim("# specific branch")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/repo --global")} ${ue.dim("# install to ~/.commandcode/skills/")}`],eN=__name((e,t)=>`${ue.green(Pe.tick)} Installed ${ue.cyan(e)} ${ue.dim(`${Pe.arrowRight} ${t}/`)}`,"formatInstalled"),tN=__name(e=>`${ue.red(Pe.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await x(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(tN("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),ZI.forEach(e=>console.log(e)),process.exit(1));const t=e.replace(/^https?:\/\/github\.com\//,""),n=t.lastIndexOf("@");(n>0?t.slice(0,n):t).split("/").filter(Boolean).length<2&&(console.error(tN(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${ue.cyan("owner/repo")} or ${ue.cyan("owner/repo/path")}`),console.log(""),ZI.forEach(e=>console.log(e)),process.exit(1))}async function addAction(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let o;validateRepoFormat(e);const s=Re({text:`Fetching ${ue.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(o=u,s.stop(),0===l.length&&(console.error(tN(`No skills found in ${ue.cyan(e)}`)),console.log(ue.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(tN(`Skill "${t.skill}" not found in ${ue.cyan(e)}`)),console.log(""),console.log(ue.dim("Available skills:")),l.forEach(e=>console.log(` ${ue.cyan(e.name)}`)),await cleanupAndExit(o,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await Be({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(ue.dim("Cancelled")),await cleanupAndExit(o,0));const n=t;i=l.filter(e=>n.includes(e.name))}else i=l;let d=0;for(const n of i)try{const s=Re({text:`Installing ${ue.cyan(n.name)}...`,color:"cyan"});s.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:o}});s.stop(),console.log(eN(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(tN(`Failed to install "${n.name}"`)),console.log(ue.dim(` ${t}`))}await cleanupAndExit(o,d>0?1:0)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(tN(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var nN=new Ie("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${ZI.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(tN("No repository specified.")),console.log(""),ZI.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ot(),wn();var rN=__name((e,t)=>`${ue.green(Pe.tick)} Removed ${ue.cyan(e)} from ${t} skills`,"formatRemoved"),oN=__name(e=>`${ue.red(Pe.cross)} ${e}`,"formatError");function validateSkillNameEarly(e){return e.includes("/")||e.includes("\\")?`"${e}" is not a valid skill name — it cannot contain path separators.`:e.includes("..")?`"${e}" is not a valid skill name — it cannot contain "..".`:e.startsWith(".")?`"${e}" is not a valid skill name — it cannot start with a dot.`:/^[a-z0-9-]+$/.test(e.trim())?null:`"${e}" is not a valid skill name — use only lowercase letters, numbers, and hyphens.`}async function removeAction(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",o=validateSkillNameEarly(e);if(o&&(console.error(oN(o)),console.log(ue.dim(`Run ${ue.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await ze({message:`Remove ${ue.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(ue.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(rN(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(oN(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(ue.dim(`Try ${ue.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(ue.dim(`Run ${ue.cyan("cmd skills list")} to see installed skills.`))):console.error(oN(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var sN=new Ie("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction);Ot(),jE(),wn();var iN=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${ue.cyan(e)} ${ue.dim(`· ${n}`)}`},"formatSkillLine"),aN=__name((e,t)=>`${ue.bold(ue.white(e))} ${ue.dim(`(${t})`)}`,"formatSectionHeader"),lN=__name(()=>{const e=process.cwd(),n=t.join(e,".commandcode","skills"),r=t.join(e,".agents","skills"),o=getProjectSkillsDir(),s=getProjectAgentsCompatSkillsDir(),i=["",ue.dim("No skills installed."),"",ue.dim("Looking in:"),ue.dim(` ${getGlobalSkillsDir()} ${ue.white("(global)")}`),ue.dim(` ${getGlobalAgentsCompatSkillsDir()} ${ue.white("(global, .agents)")}`)];return n!==o&&i.push(ue.dim(` ${n} ${ue.white("(cwd)")}`)),r!==s&&i.push(ue.dim(` ${r} ${ue.white("(cwd, .agents)")}`)),i.push(ue.dim(` ${o} ${ue.white("(project)")}`),ue.dim(` ${s} ${ue.white("(project, .agents)")}`),"",`Install a skill: ${ue.cyan("cmd skills add")} ${ue.dim("<owner/repo>")}`,""),i},"formatEmptyHint"),cN=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){try{const{global:e,project:t}=await listSkills(),n=e.length+t.length;0===n&&(cN(lN()),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:ue.dim(`${n} installed`)})),t.length>0&&(console.log(""),console.log(aN("Project",t.length)),t.forEach(e=>{console.log(iN(e.name,e.description))})),e.length>0&&(console.log(""),console.log(aN("Global",e.length)),e.forEach(e=>{console.log(iN(e.name,e.description))})),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${ue.red(Pe.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var uN=new Ie("list").description("List all installed skills").action(listAction),dN=new Ie("skills").description("Manage skills from GitHub repositories").addCommand(nN).addCommand(sN).addCommand(uN);handleUnhandledErrors(),setupTelemetry(),await preRun();var mN=createProgram();mN.action(interactiveModeAction),mN.addCommand(WP),mN.addCommand(GP),mN.addCommand(YI),mN.addCommand(qI),mN.addCommand(HP),mN.addCommand(createTasteCommand()),mN.addCommand(createMcpCommand()),mN.addCommand(VP),mN.addCommand(ys),mN.addCommand(XE),mN.addCommand(ab),mN.addCommand(dN),isExperimentalEnabled()&&mN.addCommand(createSandboxCommand()),setupCommanderHooks(mN),mN.parse();
|
|
295
|
+
`,ox=getMaxLineWidth(rx),sx=ex,ix=__name(e=>{const t=e??getTerminalWidth();return t>=Z_?"full":t>=sx?"compact":"minimal"},"getHeaderLayout");Ot(),Rr();var ax=__name(({children:e})=>{const t=[];let n="",r=!0;const o=__name(()=>{0!==n.length&&(t.push({text:n,panel:r}),n="")},"flush");for(const t of e){const e="░"===t;0===n.length?r=e:e!==r&&(o(),r=e),n+=t}return o(),Q.createElement(ne,null,t.map((e,t)=>Q.createElement(ne,{key:t,color:e.panel?Pr.BG:Pr.TEXT},e.text)))},"CommandLogoBanner");Ot(),Rr();var lx=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:o=0,titleColor:s=ar.GRAY,dividerChar:i="─",dividerColor:a=ar.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*o),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return Q.createElement(te,{paddingLeft:o,paddingRight:o,marginBottom:1,...l},(t||n)&&Q.createElement(ne,{color:a},d),e&&Q.createElement(ne,{color:s},m),Q.createElement(ne,{color:a},f),r&&Q.createElement(ne,{color:ar.DIM},g))},"Divider");Eb(),Rr(),Ot(),Rr();var cx=[{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}],ux=__name(({onComplete:e,onExit:t})=>{const[n,r]=Y(0),[o,s]=Y(!1),i=n>=cx.length;return X(()=>{if(n>=cx.length)return;if(o)return;const e=cx[n],t=setTimeout(()=>{r(e=>Math.min(e+1,cx.length))},e.duration);return()=>clearTimeout(t)},[n,o]),se((n,o)=>{""===n||o.ctrl&&"c"===n?t?t():e():o.escape?e():i?(o.return||" "===n)&&e():" "===n?s(e=>!e):o.return&&r(e=>Math.min(e+1,cx.length))}),Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Meet Your Coding Taste")),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"Command Code learns your coding style as you work.")),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"Here's how your preferences evolve in real-time:")),Q.createElement(te,{flexDirection:"column",marginY:1},cx.slice(0,n).map((e,t)=>"user"===e.type?Q.createElement(te,{key:t},Q.createElement(ne,null,Pe.pointer," ",e.text)):Q.createElement(te,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"⎿ "),Q.createElement(ne,{color:cr.TEXT},e.text)),e.details&&Q.createElement(te,{marginLeft:3},Q.createElement(ne,{color:ar.DIM},"Saved(",e.details,")"))))),i?Q.createElement(te,{flexDirection:"column",marginY:1},Q.createElement(te,null,Q.createElement(ne,{bold:!0,color:cr.TEXT},"Demo Complete!")),Q.createElement(te,null,Q.createElement(ne,null,"Command Code will now use these preferences to generate")),Q.createElement(te,null,Q.createElement(ne,null,"better suggestions tailored to your coding style. The")),Q.createElement(te,null,Q.createElement(ne,null,"more you code, the smarter it gets.")),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press Enter to get started →"))):Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(o?" (paused)":""))))},"TasteDemoComponent"),dx=__name(({onClose:e,onExit:t})=>{const[n,r]=Y(Yk.getEvents()),[o,s]=Y(0);se((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),X(()=>{const e=__name(()=>{r(Yk.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return Yk.on("new-event",e),Yk.on("cleared",t),()=>{Yk.off("new-event",e),Yk.off("cleared",t)}},[]),X(()=>{const e=__name(()=>{wb(),s(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=Z(()=>n.find(e=>"analyzing"===e.type),[n]),l=Z(()=>n.find(e=>"analyzed"===e.type),[n]),u=Z(()=>n.find(e=>"no_learnings"===e.type),[n]),d=Z(()=>n.find(e=>"learned"===e.type||"refactored"===e.type),[n]),m=u?n.indexOf(u):1/0,g=d?n.indexOf(d):1/0,h=!!u&&m<g,f=!!a||!!l||h,y=Z(()=>n.filter(e=>"analyzing"!==e.type&&"analyzed"!==e.type&&"no_learnings"!==e.type),[n]),w=Z(()=>[...y].reverse(),[y]),S=__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 i={learned:"LEARNED",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),E=__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"),C=__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"),v=Z(()=>(process.stdout.rows??24)-1,[o]);return Q.createElement(te,{flexDirection:"column",width:"100%",height:v,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ax,null,tx())),Q.createElement(lx,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),Q.createElement(te,{flexDirection:"column"},0===n.length?Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(te,null,Q.createElement(ne,null,"Start using Command Code and it will begin recording your coding taste.")),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"Your preferences, patterns, and style will appear here in real-time."))),Q.createElement(le,{count:2}),Q.createElement(lx,{title:"DEMO",titleColor:"white",subPrefix:!0}),Q.createElement(ux,{onComplete:()=>{e()},onExit:t})):Q.createElement(te,{flexDirection:"column"},y.length>0&&Q.createElement(te,{flexDirection:"column",gap:1},w.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:o}=S(e.message),s="moved"===t?C(e.details):null,i="upgraded"===t||"downgraded"===t?E(r):null,a=s?.fullPath??e.details;let l=Q.createElement(Q.Fragment,null,Q.createElement(ne,null," ",r),o&&Q.createElement(ne,{color:ar.DIM}," ","(",o,")"));return i&&(l=Q.createElement(Q.Fragment,null,Q.createElement(ne,null," ",i.text," ("),Q.createElement(ne,{color:ar.DIM},"confidence:"," "),Q.createElement(ne,{color:ar.DIM},i.oldPercent,"%"),Q.createElement(ne,null," ",Pe.arrowRight," "),Q.createElement(ne,{color:i.diff>0?ar.GREEN:ar.RED},i.newPercent,"%"),Q.createElement(ne,null,")"))),s&&(l=Q.createElement(Q.Fragment,null,Q.createElement(ne,null," ",s.category," package ("),Q.createElement(ne,{color:ar.DIM},s.oldPath),Q.createElement(ne,null," ",Pe.arrowRight," ",s.newPath),Q.createElement(ne,null,")"))),Q.createElement(te,{key:e.id},Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG,bold:!0},`${bT}${n}${bT}`)),a&&Q.createElement(ne,{color:ar.DIM}," ","(",a,")")),Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM},"⎿"," "),l)))}return Q.createElement(te,{key:e.id},Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",e.message))})),f&&Q.createElement(te,{flexDirection:"column",marginTop:y.length>0?1:0},a&&Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",a.message)),l&&Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",l.message)),h&&u&&Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," ",u.message))))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return Q.createElement(dx,{onClose:()=>{wb(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ot(),Rr(),Ot(),Rr(),Eb(),Jr();var mx=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=Y(!1),[s,i]=Y(!0);X(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),se((t,n)=>{if(!n.return&&" "!==t)return n.escape?(wb(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?Q.createElement(te,{key:n,borderStyle:"single",borderColor:ar.BLUE,padding:1,flexDirection:"column"},Q.createElement(ne,{color:ar.BLUE,bold:!0},"Taste Settings"),Q.createElement(ne,{color:ar.DIM},"Loading configuration...")):Q.createElement(te,{key:n,borderStyle:"single",borderColor:ar.GRAY,padding:1,flexDirection:"column"},Q.createElement(ne,{bold:!0},"Taste Learning"),Q.createElement(ne,{color:ar.DIM},"Configure taste learning preferences for this project"),Q.createElement(te,{marginTop:1}),Q.createElement(te,{justifyContent:"space-between"},Q.createElement(ne,null,"Taste learning",Q.createElement(ne,{color:ar.DIM}," - Learn from your interactions")),Q.createElement(ne,{color:r?ar.GREEN:ar.GRAY},r?"enabled":"disabled")),Q.createElement(te,{marginTop:1}),Q.createElement(ne,{color:ar.DIM},"Taste data stored in .commandcode/taste/taste.md"),Q.createElement(ne,{color:ar.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return Q.createElement(Q.Fragment,null,Q.createElement(M_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"Press Esc to return to conversation")),Q.createElement(mx,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}function fuzzyMatch(e,t){let n=0;for(const r of e)if(r===t[n]&&(n++,n===t.length))return!0;return!1}function fuzzyScore(e,t){let n=0;for(const r of e)fuzzyMatch(r.text.toLowerCase(),t)&&(n+=r.weight);return n}function fuzzyFilter(e,t,n){if(!t.trim())return e;const r=t.toLowerCase().split("");return e.map(e=>({item:e,score:fuzzyScore(n(e),r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score).map(({item:e})=>e)}__name(TasteConfigView,"TasteConfigView"),Ot(),Ot(),wn(),Ot(),__name(fuzzyMatch,"fuzzyMatch"),__name(fuzzyScore,"fuzzyScore"),__name(fuzzyFilter,"fuzzyFilter"),Eb(),Rr(),Ot(),Rr();var px=__name(({query:e,resultCount:t,placeholder:n="Type to search..."})=>Q.createElement(te,{width:"100%"},Q.createElement(ne,{color:ar.GRAY},Pe.pointerSmall," "),Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},e||n),e&&void 0!==t&&Q.createElement(ne,{dimColor:!0}," (",t," found)")),"SearchInput");function useListNavigation({items:e,onSelect:t,onCancel:n,validate:r,initialIndex:o=0,searchQuery:s,onSearchChange:i}){const[a,l]=Y(o),[u,d]=Y(null);X(()=>{s||l(o)},[o,s]);const m=e.length-1,g=__name(e=>{i(e),l(0)},"updateSearch");return se((o,i)=>{if(i.escape&&s)g("");else if(i.escape)n();else if(i.backspace||i.delete)g(s.slice(0,-1));else if(0!==e.length){if(i.upArrow)return d(null),void l(e=>e>0?e-1:m);if(i.downArrow)return d(null),void l(e=>e<m?e+1:0);if(i.return){const n=e[a];if(!n)return;if(r){const e=r(n);if(e)return void d(e)}return void t(n)}!i.ctrl&&!i.meta&&!i.tab&&o&&1===o.length&&o>=" "&&g(s+o)}}),{cursor:a,error:u,setError:d}}Ot(),__name(useListNavigation,"useListNavigation"),Ot(),wn(),Rr();var gx=__name(()=>Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ne,{color:lr,bold:!0},"Skills"),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"No skills found")),Q.createElement(ne,{color:ar.DIM},"Create skills in:"),Q.createElement(ne,{color:ar.DIM}," ","~/",".commandcode","/","skills","/ (user)"),Q.createElement(ne,{color:ar.DIM}," ","~/.agents/","skills","/ (user, .agents)"),Q.createElement(ne,{color:ar.DIM}," ",".commandcode","/","skills","/ (project)"),Q.createElement(ne,{color:ar.DIM}," ",".agents/","skills","/ (project, .agents)"),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press ",Q.createElement(ne,{bold:!0},"Esc")," to close"))),"SkillsConfigEmpty");Ot();var hx=__name(e=>Math.ceil(e.length/4),"estimateTokens"),fx=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),yx={user:"user settings",projectShared:"project shared",projectLocal:"project local"},wx=__name(()=>"win32"===process.platform?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===process.platform?"~/.zshrc":"~/.bashrc"),"getEditorSetupMessage");Ot(),Rr();var Sx=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(te,null,Q.createElement(ne,{color:wr,bold:!0},e," "),Q.createElement(ne,{color:wr},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=fx(e.filePath);return Q.createElement(te,{key:e.filePath},Q.createElement(ne,{color:ar.GREEN},n?"▸ ":" "),Q.createElement(ne,{color:i?ar.DIM:ar.GREEN},i?"[off] ":"[on] "),Q.createElement(ne,{color:i?ar.DIM:ar.WHITE},e.label),a&&Q.createElement(ne,{color:ar.DIM}," [.agents]"),Q.createElement(ne,{color:ar.DIM}," · ~",hx(e.description)," tokens"))})),"SkillSection");Ot();var Ex=__name(e=>[{text:e.label,weight:100}],"SKILL_SEARCH_FIELDS"),bx=__name(({onClose:e})=>{const[t,n]=Y([]),[r,o]=Y(!0),[s,i]=Y(null),[a,l]=Y(""),[u,d]=Y(new Set),[m,g]=Y(new Map),[h,f]=Y(!1),[y,w]=Y(null),S=J(!1);X(()=>{__name(async()=>{try{const e=findGitRoot(),[{global:t,project:r},o]=await Promise.all([loadAllSkillSummaries(),loadDisabledSkills({projectRoot:e})]),s=[...r.map(e=>({label:e.name,location:"project",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,location:"user",description:e.description,filePath:e.filePath}))];s.sort((e,t)=>e.location!==t.location?"project"===e.location?-1:1:e.label.localeCompare(t.label)),n(s),d(new Set(o.names)),g(new Map(o.bySkill)),f(o.noProjectRoot)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{o(!1)}},"load")()},[]);const E=Z(()=>fuzzyFilter(t.filter(e=>"project"===e.location),a,Ex),[t,a]),C=Z(()=>fuzzyFilter(t.filter(e=>"user"===e.location),a,Ex),[t,a]),v=Z(()=>[...E,...C],[E,C]),k=__name(async e=>{if(S.current)return;const t=u.has(e.label),n=m.get(e.label);if(t&&void 0!==n&&"projectLocal"!==n&&!h)return void w(`Cannot enable: "${e.label}" is disabled in ${yx[n]}. Edit that file to override.`);S.current=!0;const r=new Set(u);t&&r.delete(e.label),t||r.add(e.label),d(r),w(null);try{const n=findGitRoot(),r=await setSkillEnabled(e.label,t,{projectRoot:n}),o=new Map(m);t&&o.delete(e.label),t||o.set(e.label,r),g(o),"user"===r&&w("Saved to user settings — no project found.")}catch(e){d(u),w(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{S.current=!1}},"toggleSkill"),{cursor:T}=useListNavigation({items:v,onSelect:k,onCancel:__name(()=>{wb(),e()},"onCancel"),searchQuery:a,onSearchChange:l,initialIndex:0});if(se((t,n)=>{if(!n.tab)return;const r=v[T];r&&(async()=>{try{await ft([{file:r.filePath,line:1}]),wb(),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void i(wx());i(e instanceof Error?e.message:"Failed to open skill in editor")}})()}),r)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ne,{color:lr,bold:!0},"Skills"),Q.createElement(ne,{color:ar.DIM},"Loading skills..."));if(s)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ne,{color:ar.RED,bold:!0},"Skills"),Q.createElement(ne,{color:ar.DIM},s),Q.createElement(te,{marginTop:1}),Q.createElement(ne,{color:ar.DIM},"Press ",Q.createElement(ne,{bold:!0},"Esc")," to close"));if(0===t.length)return Q.createElement(gx,null);const _=t.filter(e=>u.has(e.label)).length;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Skills"," "),Q.createElement(ne,{color:ar.DIM},t.length," skill",1===t.length?"":"s"),_>0&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:ar.YELLOW},_," off"))),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{dimColor:!0},h?"No project found — toggles will be saved to user settings.":"Toggle skills on or off for this project.")),Q.createElement(te,{marginBottom:1,flexDirection:"column",width:"100%"},Q.createElement(px,{query:a,resultCount:a?v.length:void 0,placeholder:"Type to search skills..."})),0===v.length?Q.createElement(te,{marginY:1},Q.createElement(ne,{color:ar.GRAY},'No skills match "',a,'"')):Q.createElement(Q.Fragment,null,E.length>0&&Q.createElement(Sx,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:E,baseIndex:0,cursor:T,disabled:u}),C.length>0&&Q.createElement(Sx,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:C,baseIndex:E.length,cursor:T,disabled:u})),y&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.YELLOW},y)),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},a?"type to search · ↑/↓ navigate · enter to toggle · tab to edit · esc to clear":"type to search · ↑/↓ navigate · enter to toggle · tab to edit · esc to close"),Q.createElement(ne,{color:ar.DIM},"add skills:"," ",Q.createElement(ne,{color:ar.CYAN},"cmd skills add ","<owner/repo>"))))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return Q.createElement(Q.Fragment,null,Q.createElement(M_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(bx,{onClose:()=>t(!1),staticKey:e})))}function useTerminalWidth(){const{stdout:e}=oe(),[t,n]=Y(()=>e.columns??80);return X(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function getUsageColor(e){return e>=80?ar.RED:e>=50?ar.YELLOW:ar.GREEN}function buildBlockBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e));let r=Math.round(n/100*t);n>.5&&0===r&&(r=1),n<99.5&&r===t&&(r=t-1);const o=t-r;return{filled:"█".repeat(r),empty:"░".repeat(o)}}function getStudioUsageUrl(e){const t=e?.org?.login??e?.user?.userName;return t?`https://commandcode.ai/${t}/settings/usage`:null}__name(SkillsConfigView,"SkillsConfigView"),Ot(),Ot(),Qr(),Eb(),Rr(),Ot(),__name(useTerminalWidth,"useTerminalWidth"),Ot(),Rr(),__name(getUsageColor,"getUsageColor"),__name(buildBlockBar,"buildBlockBar"),Xr(),__name(getStudioUsageUrl,"getStudioUsageUrl");var Cx=__name(e=>e.replace(/^https?:\/\//,""),"stripScheme");function getProgressBarWidth({terminalWidth:e}){return e<50?Math.max(10,e-10):e<70?Math.max(15,e-15):Math.min(30,e-15)}function getDaysColor(e){if(null!==e)return e<3?ar.RED:e<7?ar.YELLOW:void 0}__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var vx=__name(({plan:e,status:t})=>Q.createElement(te,{marginBottom:0},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:ar.BLUE,color:"#f4f4f4",bold:!0},`${bT}USAGE${bT}`)),e&&Q.createElement(Q.Fragment,null,Q.createElement(ne,null," "),Q.createElement(ne,{color:ar.GRAY},`${e.name} Plan`)),t&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:"active"===t?ar.GREEN:ar.YELLOW},t))),"UsageBadge"),kx=__name(({showRetry:e})=>Q.createElement(te,{marginTop:1},e&&Q.createElement(ne,{color:ar.DIM},Q.createElement(ne,{bold:!0},"r")," to retry · "),Q.createElement(ne,{color:ar.DIM},"Press ",Q.createElement(ne,{bold:!0},"Esc")," to close")),"UsageFooter"),Tx=__name(({models:e,grandTotal:t})=>{if(0===e.length)return null;const n=e.map(e=>({...e,displayName:getModelDisplayName(e.model),costLabel:formatCredits(e.totalCost)})),r=Math.max(...n.map(e=>e.displayName.length)),o=Math.min(24,Math.max(10,r)),s=Math.max(...n.map(e=>e.costLabel.length)),i=Math.max(8,s+2);return Q.createElement(te,{flexDirection:"column",marginTop:1},n.map(({model:e,displayName:n,costLabel:r,totalCost:s})=>{const a=t>0?Math.round(s/t*100):0,l=n.length>o?n.slice(0,o-1)+"…":n;return Q.createElement(te,{key:e},Q.createElement(ne,null,l.padEnd(o+2)),Q.createElement(ne,null,r.padEnd(i)),Q.createElement(ne,{color:ar.DIM},`${a}%`))}))},"ModelBreakdownRows"),_x=__name(({onClose:e})=>{const[t,n]=Y("loading"),[r,o]=Y(null),[s,i]=Y(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ee(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return i(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),u=Q.useRef(null);se((r,o)=>{if(o.escape&&(wb(),e()),"r"===r&&"error"===t){n("loading"),u.current?.abort();const e=new AbortController;u.current=e,l(e.signal)}}),X(()=>{const e=new AbortController;return u.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?.subscription?.data??null,m=d?getPlanInfo({planId:d.planId??""}):null;if("loading"===t)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(vx,{plan:m,status:d?.status??null}),Q.createElement(ne,{color:ar.DIM},"Loading…"),Q.createElement(kx,null));if("error"===t)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(vx,{plan:m,status:d?.status??null}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),Q.createElement(kx,{showRetry:!s}));if(!r)return null;const g=r.credits||r.subscription,h=getStudioUsageUrl(r.whoami);if(!g)return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(vx,{plan:m,status:d?.status??null}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"No billing data found."),h&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," Visit "),Q.createElement(Kr,{url:h,text:"Studio",color:ar.CYAN}),Q.createElement(ne,{color:ar.DIM}," ","for usage details."))),Q.createElement(kx,null));const f=r.credits?.credits,y=r.summary,w=r.modelBreakdown,S=null!=w&&w.length>0,E=Math.max(0,f?.monthlyCredits??0)+Math.max(0,f?.purchasedCredits??0)+Math.max(0,f?.freeCredits??0),C=Math.max(0,y?.totalCost??0),v=getUsagePercent({used:C,total:C+E}),k=E>0||C>0,T=d?.currentPeriodEnd?getDaysRemaining(d.currentPeriodEnd):null,_=getDaysColor(T),x=getUsageColor(v),A=buildBlockBar({percentage:v,width:a}),P=S?w.reduce((e,t)=>e+t.totalCost,0):0;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{marginBottom:1},Q.createElement(vx,{plan:m,status:d?.status??null})),k?Q.createElement(te,null,Q.createElement(ne,{color:x},A.filled),Q.createElement(ne,{color:wr},A.empty),Q.createElement(ne,{bold:!0,color:x},` ${Math.round(v)}% used`)):Q.createElement(ne,{color:ar.DIM},"Plan details unavailable"),k&&Q.createElement(te,null,d?.currentPeriodEnd&&Q.createElement(ne,{color:ar.DIM},"Cycle: "),Q.createElement(ne,null,formatCredits(E)),Q.createElement(ne,{color:ar.DIM}," left"),y&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,null,y.totalCount.toLocaleString()),Q.createElement(ne,{color:ar.DIM}," requests")),null!==T&&Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.DIM}," · "),0===T?Q.createElement(ne,{color:_},"renewal today"):Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:_},`${T} day${1===T?"":"s"}`),Q.createElement(ne,{color:ar.DIM}," to renewal")))),S&&Q.createElement(Tx,{models:w,grandTotal:P}),h&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Full breakdown at "),Q.createElement(Kr,{url:h,text:Cx(h),color:ar.CYAN})),Q.createElement(kx,null))},"UsageOverlay");function UsageView({staticKey:e,setShowUsageOverlay:t}){return Q.createElement(Q.Fragment,null,Q.createElement(M_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(_x,{onClose:()=>t(!1)})))}__name(UsageView,"UsageView"),Ot(),Ot(),wn(),BS(),Jr();var xx="System prompt",Ax="Messages";function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&!isHiddenTranscriptMessage({message:r})&&t++,"assistant"===r.message.role&&n++;return{user:t,assistant:n}}function countToolCalls({messages:e}){let t=0,n=0;for(const r of e){if(isHiddenTranscriptMessage({message:r}))continue;const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)isHiddenTranscriptMessage({message:n})||(t+=estimateTokens(n.message));return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:hn.TIER_1_THRESHOLD,description:`Prune to last ${hn.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:hn.TIER_2_THRESHOLD,description:`Prune to last ${hn.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:hn.TIER_3_THRESHOLD,description:"Full summarization"}];let o=0;const s=r.map(r=>{const s=Math.round(r.threshold*t),i=Math.max(0,s-e);let a="upcoming";return n>=r.threshold&&(a="passed",o=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:s,description:r.description,status:a,tokensAway:i}}),i=s.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?s.map((e,t)=>t===i?{...e,status:"current"}:e):s,currentTier:o,keepRecentTokens:hn.KEEP_RECENT_TOKENS}}function getPrimaryTip({percentage:e,conversationPct:t}){return e>=90?"Tier 3 auto-compact imminent — /compact now to control what gets summarized":e>=80?"Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in":t>60&&e>40?`${t}% is conversation — /compact to reclaim tokens`:e>=50?"/compact to free space · /model to switch models":null}function getSecondaryTip({mcpToolCount:e,imageCount:t,messageCount:n,percentage:r}){return e>0&&r>30?`${e} MCP tools loaded — disconnect unused servers to save tokens`:t>0&&r>30?`${t} image${t>1?"s":""} in context — images use ~1.5k tokens each`:n>50&&r>40?`${n} messages — consider starting a new session for a fresh context`:null}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:o,imageCount:s}){if(0===n)return[];const i=getPrimaryTip({percentage:e,conversationPct:Math.min(100,Math.round(t/n*100))}),a=getSecondaryTip({mcpToolCount:r,imageCount:s,messageCount:o,percentage:e}),l=[];return i&&l.push(i),a&&l.push(a),0===l.length&&l.push("/compact to summarize and free context · /model to switch models"),l}async function collectMemoryItems(){const e=(await discoverMemoryFiles(process.cwd())).filter(e=>e.exists),t=[];for(const n of e){const e=await loadMemoryFile(n.path),r=e?estimateTokens(e):0,o=process.env.HOME??"",s=o&&n.path.startsWith(o)?`~${n.path.slice(o.length)}`:n.path;t.push({name:n.description,tokens:r,source:s})}return t}function collectBuiltInTools(){const e=[];for(const t of fk){const n=JSON.stringify(t.input_schema??{}),r=estimateTokens(`${t.name} ${t.description??""} ${n}`);e.push({name:t.name,tokens:r})}for(const t of yk){const n=estimateTokens(`${t.name} ${t.type}`);e.push({name:t.name,tokens:n})}return e}function collectMcpTools(){const e=getMcpConnectionManager().getConnectedServers(),t=[];for(const n of e)if("connected"===n.status)for(const e of n.tools){const r=JSON.stringify(e.inputSchema??{}),o=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:o,source:n.name})}return t}async function collectSkillItems(){const e=await loadAllSkillSummaries(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.global){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"user"})}return t}async function collectAgentItems(){const e=await loadAllAgents(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.personal){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"user"})}return t}function sumTokens(e){let t=0;for(const n of e)t+=n.tokens;return t}async function analyzeContext({contextEngine:e}){const t=e.getContextTokensUsed(),n=e.getSystemPromptBreakdown(),r=getConfiguredModel(),o=getContextLimit(r),s=e.getHistory(),i=countMessagesByRole({messages:s}),a=countToolCalls({messages:s}),l=countImages({messages:s}),u=estimateConversationTokens({messages:s}),d=collectBuiltInTools(),m=collectMcpTools(),[g,h,f]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),y=sumTokens(d),w=sumTokens(m),S=sumTokens(g),E=sumTokens(h),C=sumTokens(f),v=t>0,k=n?n.memory:C,T=null!==n&&Math.abs(C-n.memory)>50,_=n?n.taste:0,x=y+w+S+E,A=v?t:u+x+k+_,P=!v&&s.length>0,I=Math.min(A/o*100,100),N=Math.max(0,o-A),R=[];if(A>0){const e=n?n.systemPrompt:Math.max(0,A-u-x-k-_);if(e>0&&R.push({name:xx,tokens:e,detail:n?"identity":"identity + taste"}),k>0&&R.push({name:"Memory",tokens:k,detail:T?"memory files (modified, refreshes next request)":"memory files"}),_>0&&R.push({name:"Taste",tokens:_,detail:"taste.md"}),y>0&&R.push({name:"System tools",tokens:y,detail:`${d.length} built-in`}),w>0){const e=Array.from(new Set(m.map(e=>e.source).filter(e=>"string"==typeof e)));let t=`${m.length} tools`;e.length>3&&(t=`${e.length} servers`),e.length>=1&&e.length<=3&&(t=e.join(", ")),R.push({name:"MCP",tokens:w,detail:t})}S>0&&R.push({name:"Skills",tokens:S,detail:`${g.length} loaded`}),E>0&&R.push({name:"Subagents",tokens:E,detail:`${h.length} loaded`});const r=e+k+_+x,o=v?Math.max(0,t-r):u;o>0&&R.push({name:Ax,tokens:o,detail:`${i.user} user · ${i.assistant} assistant`})}R.sort((e,t)=>e.name===xx?-1:t.name===xx||e.name===Ax?1:t.name===Ax?-1:t.tokens-e.tokens);const M=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:A,tokenLimit:o,percentage:I,tokensRemaining:N,isEstimated:P,model:r,breakdown:R,autoCompact:buildAutoCompactStatus({tokensUsed:A,tokenLimit:o}),stats:{messageCount:s.length,userMessages:i.user,assistantMessages:i.assistant,toolCalls:a.calls,toolResults:a.results,imageCount:l,sessionStartTime:M},tips:generateTips({percentage:I,conversationTokens:u,totalTokens:A,mcpToolCount:m.length,messageCount:s.length,imageCount:l})}}function formatK(e){if(e<1e3)return String(e);const t=e/1e3;return Number.isInteger(t)?`${t}k`:`${t.toFixed(1)}k`}function formatBreakdownValue(e){return e<1e3?String(e):`${(e/1e3).toFixed(1)}k`}function getLayoutSizes({terminalWidth:e}){const t=Math.max(20,e),n=Math.min(50,Math.max(30,Math.floor(.5*t)));return{labelWidth:16,progressBarWidth:Math.max(10,Math.min(n,t-10)),showBreakdownDetail:t>=70}}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildBlockBar({percentage:e.percentage,width:t});return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{marginBottom:1},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:ar.BLUE,color:"#f4f4f4",bold:!0},`${bT}CONTEXT${bT}`)),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:ar.GRAY},getModelDisplayName(e.model))),Q.createElement(te,null,Q.createElement(ne,{color:n},r.filled),Q.createElement(ne,{color:wr},r.empty),Q.createElement(ne,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),Q.createElement(te,null,Q.createElement(ne,null,formatK(e.tokensUsed)),Q.createElement(ne,{color:ar.GRAY},` / ${formatK(e.tokenLimit)}`),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:n},formatK(e.tokensRemaining)),Q.createElement(ne,{color:ar.GRAY}," remaining"),e.isEstimated&&Q.createElement(ne,{color:ar.DIM}," (estimated)")))}function CompactionDistance({analysis:e}){if(e.percentage<40)return null;const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const{tokensAway:n}=t;let r=ar.GRAY;return n<=5e4&&(r=ar.YELLOW),n<=2e4&&(r=ar.RED),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:r},`~${formatK(n)}`),Q.createElement(ne,{color:ar.DIM}," until auto-compact"))}function BreakdownRow({item:e,labelWidth:t,numWidth:n,showDetail:r}){return Q.createElement(te,null,Q.createElement(ne,null,e.name.padEnd(t)),Q.createElement(ne,{bold:!0},formatBreakdownValue(e.tokens).padStart(n)),Q.createElement(ne,{color:ar.GRAY}," tokens"),r&&e.detail&&Q.createElement(ne,{color:ar.DIM},` · ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,showBreakdownDetail:n}){const r=e.breakdown.filter(e=>e.tokens>0);if(0===r.length)return null;const o=Math.max(4,...r.map(e=>formatBreakdownValue(e.tokens).length));return Q.createElement(te,{flexDirection:"column",marginTop:1},r.map(e=>Q.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t,numWidth:o,showDetail:n})))}function ContextTips({tips:e}){return 0===e.length?null:Q.createElement(te,{flexDirection:"column",marginTop:1},e.map(e=>Q.createElement(te,{key:e},Q.createElement(ne,{color:ar.CYAN},Pe.pointer),Q.createElement(ne,{color:ar.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return Q.createElement(te,{flexDirection:"column",paddingTop:1},Q.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),Q.createElement(CompactionDistance,{analysis:e}),Q.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,showBreakdownDetail:t.showBreakdownDetail}),Q.createElement(ContextTips,{tips:e.tips}))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[o,s]=Y(null),[i,a]=Y(null);return X(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&s(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),se((e,t)=>{t.escape&&(wb(),r(""),n(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(M_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},i?Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Context"),Q.createElement(ne,{color:ar.DIM},i)):o?Q.createElement(ContextMessage,{analysis:o}):Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Context"),Q.createElement(ne,{color:ar.DIM},"Loading context analysis...")),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press Esc to return to conversation"))))}__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(getPrimaryTip,"getPrimaryTip"),__name(getSecondaryTip,"getSecondaryTip"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),Eb(),Ot(),Qr(),Rr(),__name(formatK,"formatK"),__name(formatBreakdownValue,"formatBreakdownValue"),__name(getLayoutSizes,"getLayoutSizes"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),Rr(),__name(ContextConfigView,"ContextConfigView"),Ot(),Ot(),wn(),Ns(),Co(),io(),Jr();var Px="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson().version,updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkAuthStatus(),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(){try{const e=await getSelectedModel(),t=getProviderDisplayName((await loadUserConfig()).provider||null);return{id:e,displayName:getModelDisplayName(e),provider:t}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}async function getSkillsAgentsStatus(){let e=0,t=0,n=0,r=0;try{const n=await loadAllSkillSummaries();e=n.global.length,t=n.project.length}catch{}try{const e=await loadAllAgents();n=e.personal.length,r=e.project.length}catch{}return{personalSkills:e,projectSkills:t,personalAgents:n,projectAgents:r}}function execGitAsync(e){return new Promise(t=>{ve("git",e,{encoding:"utf8",cwd:process.cwd(),timeout:3e3},(e,n)=>{t(e?null:n.trim()||null)})})}async function getGitStatus2(){const e=await execGitAsync(["rev-parse","--abbrev-ref","HEAD"]);if(!e)return{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null};const[t,n]=await Promise.all([execGitAsync(["rev-parse","--show-toplevel"]),execGitAsync(["remote","get-url","origin"])]);return{branch:e,worktreePath:t,remoteUrl:n?formatRemoteUrl(n):null,remoteHttpUrl:n?buildHttpUrl(n):null}}function parseSSHUrl(e){const t=e.match(/@([^:]+):(.+?)(?:\.git)?$/);return t?.[1]&&t[2]?{host:t[1],path:t[2]}:null}function formatRemoteUrl(e){const t=parseSSHUrl(e);if(t)return t.path;const n=e.match(/\/\/[^/]+\/(.+?)(?:\.git)?$/);return n?.[1]?n[1]:e}function buildHttpUrl(e){const t=parseSSHUrl(e);if(t)return`https://${t.host}/${t.path}`;const n=e.match(/^ssh:\/\/[^@]+@([^/]+)\/(.+?)(?:\.git)?$/);return n?.[1]&&n[2]?`https://${n[1]}/${n[2]}`:/^https?:\/\//.test(e)?e.replace(/\.git$/,""):e}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}async function hasTasteMdFiles(e){if(!D(e))return!1;try{return(await I(e,{recursive:!0,encoding:"utf-8"})).some(e=>e.endsWith(".md"))}catch{return!1}}async function getTasteStatus(){const e=t.join(process.cwd(),".commandcode","taste"),n=t.join(e,"taste.md"),r=D(n),o=r||await hasTasteMdFiles(e);let s=!0;try{s=await isTasteLearningEnabled()}catch{}return{fileExists:o,filePath:r?n:e,learningEnabled:s}}function detectProxy(){const e=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy;return e?sanitizeProxyUrl(e):null}function sanitizeProxyUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString().replace(/\/$/,"")}catch{return"[malformed proxy URL]"}}function getSystemStatus(){let e,t,n,r;try{e=OT(S.platform()),t=ZT(),n=e_(),r=t_()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:S.arch(),shell:n,terminal:t,nodeVersion:process.version,ide:"N/A"!==r?r:null,proxy:detectProxy()}}async function gatherStatusData(){const e=safeSync(getVersionStatus,{current:"Unknown",updateAvailable:null}),t=safeSync(getSystemStatus,{cwd:process.cwd(),os:"Unknown",arch:S.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,o,s,i]=await Promise.all([safeAsync(getAuthStatus,{authenticated:!1,username:null}),safeAsync(getModelStatus,{id:"Unknown",displayName:"Unknown",provider:"Unknown"}),safeAsync(getTasteStatus,{fileExists:!1,filePath:"",learningEnabled:!1}),safeAsync(getSkillsAgentsStatus,{personalSkills:0,projectSkills:0,personalAgents:0,projectAgents:0}),safeAsync(getGitStatus2,{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null})]),a=safeSync(()=>getPrStatus(i.branch),null);return{version:e,auth:n,model:r,git:i,pr:a,taste:o,skillsAgents:s,system:t}}function safeSync(e,t){try{return e()}catch{return t}}async function safeAsync(e,t){try{return await e()}catch{return t}}function formatCountValue(e,t){const n=e+t;return 0===n?"None":`${n} (${e} user, ${t} project)`}function formatSystemValue({system:e}){const t=[`${e.os} ${e.arch}`];return e.ide&&t.push(e.ide),!e.terminal||e.ide&&e.ide.toLowerCase().startsWith(e.terminal.toLowerCase())||t.push(e.terminal),t.push(e.shell),t.push(`Node ${e.nodeVersion}`),t.join(" · ")}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getSkillsAgentsStatus,"getSkillsAgentsStatus"),__name(execGitAsync,"execGitAsync"),__name(getGitStatus2,"getGitStatus"),__name(parseSSHUrl,"parseSSHUrl"),__name(formatRemoteUrl,"formatRemoteUrl"),__name(buildHttpUrl,"buildHttpUrl"),__name(getPrStatus,"getPrStatus"),__name(hasTasteMdFiles,"hasTasteMdFiles"),__name(getTasteStatus,"getTasteStatus"),__name(detectProxy,"detectProxy"),__name(sanitizeProxyUrl,"sanitizeProxyUrl"),__name(getSystemStatus,"getSystemStatus"),__name(gatherStatusData,"gatherStatusData"),__name(safeSync,"safeSync"),__name(safeAsync,"safeAsync"),Ot(),wn(),kE(),Rr(),Xr(),__name(formatCountValue,"formatCountValue"),__name(formatSystemValue,"formatSystemValue");var Ix=__name(({label:e,value:t,valueColor:n,dimValue:r})=>Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},`${e}:`.padEnd(14)),r?Q.createElement(ne,{dimColor:!0},t):Q.createElement(ne,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=e,n=t.version.updateAvailable?`v${t.version.current} → v${t.version.updateAvailable} available`:`v${t.version.current}`,r=`${t.model.provider} · ${t.model.displayName}`,o=t.git.branch||"N/A",s=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?Pe.tick:Pe.cross,a=t.auth.authenticated?ar.WHITE:fr.ERROR,l=t.skillsAgents.personalSkills+t.skillsAgents.projectSkills,u=t.skillsAgents.personalAgents+t.skillsAgents.projectAgents,d=t.taste.fileExists?"Active · "+(t.taste.learningEnabled?"Learning on":"Learning off"):"No taste.md";return Q.createElement(te,{flexDirection:"column",paddingX:0},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Command Code"," "),Q.createElement(ne,{dimColor:!0},n)),Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},"Visit "),Q.createElement(Kr,{url:Px,text:Px,color:ar.CYAN}),Q.createElement(ne,{dimColor:!0}," for usage and billing")),Q.createElement(te,{marginTop:1},Q.createElement(ne,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?Q.createElement(Q.Fragment,null,Q.createElement(Kr,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:ar.CYAN}),Q.createElement(ne,{color:a}," ",i)):t.auth.authenticated?Q.createElement(Q.Fragment,null,Q.createElement(ne,null,"Authenticated"),Q.createElement(ne,{color:a}," ",i)):Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:fr.WARNING},"Not signed in"),Q.createElement(ne,{color:a}," ",i),Q.createElement(ne,{dimColor:!0}," — run "),Q.createElement(ne,{bold:!0},"/login"))),Q.createElement(Ix,{label:"Model",value:r}),Q.createElement(Ix,{label:"Branch",value:o,dimValue:!t.git.branch}),s?Q.createElement(Ix,{label:"Worktree",value:s}):null,t.git.remoteUrl?Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},"Repository:".padEnd(14)),Q.createElement(Kr,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:ar.CYAN}),t.pr?Q.createElement(Q.Fragment,null,Q.createElement(ne,{dimColor:!0}," · "),Q.createElement(Kr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?ar.CYAN:ar.GRAY}),Q.createElement(ne,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null):t.pr?Q.createElement(te,null,Q.createElement(ne,{dimColor:!0},"Pull Request:".padEnd(14)),Q.createElement(Kr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?ar.CYAN:ar.GRAY}),Q.createElement(ne,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,Q.createElement(Ix,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),Q.createElement(Ix,{label:"Directory",value:toRelativePath(t.system.cwd)}),Q.createElement(Ix,{label:"Skills",value:formatCountValue(t.skillsAgents.personalSkills,t.skillsAgents.projectSkills),dimValue:0===l}),Q.createElement(Ix,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),Q.createElement(Ix,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?Q.createElement(Ix,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,o]=Y({phase:"loading"});return X(()=>{let e=!1;return gatherStatusData().then(t=>{e||o({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";o({phase:"error",message:n})}),()=>{e=!0}},[]),se((e,r)=>{r.escape&&(n(""),t(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(M_,{staticKey:e}),Q.createElement(te,{flexDirection:"column",width:"100%"},"ready"===r.phase?Q.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?Q.createElement(ne,{dimColor:!0},"Could not load status: ",r.message):Q.createElement(ne,{dimColor:!0},"Gathering status…"),Q.createElement(te,{marginTop:1},Q.createElement(ne,{dimColor:!0},"Press Esc to return to conversation"))))}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 $.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"}__name(StatusMessage,"StatusMessage"),__name(StatusConfigView,"StatusConfigView"),Ot(),Ot(),Ao(),Ot(),Ao(),__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"),Rr(),$r();var Nx=__name(({onClose:e})=>{const[t,n]=Y(""),[r,o]=Y(null),[s,i]=Y([]),[a,l]=Y(getAdditionalDirectories()),[u,d]=Y({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=Y(0);X(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),X(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__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"),f=__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");se((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&s[u.suggestionIndex]?void h(s[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[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:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),X(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,s.length]),X(()=>{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>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[s.length,a.length]);const y=s.slice(m,m+8),w=getFooterText({focusZone:u.zone});return Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.CYAN,paddingX:1,paddingY:0},Q.createElement(ne,{bold:!0,color:ar.CYAN},"Add directory to workspace"),Q.createElement(ne,{color:ar.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,{color:ar.GRAY},"Added directories"),0===a.length?Q.createElement(ne,{color:ar.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return Q.createElement(ne,{key:e,color:n?ar.YELLOW:ar.GREEN,bold:n},n?` ${Pe.pointer} `:" ",formatDirectoryForDisplay(e))})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0,color:ar.WHITE},"Path")),Q.createElement(te,null,Q.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?Pe.pointer:" "} `,prefixColor:"input"===u.zone?ar.CYAN:ar.GRAY,onChange:e=>{n(e),o(null)},onSubmit:h})),!t&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:{error:ar.RED,warning:ar.YELLOW,success:ar.GREEN}[r.tone]},r.text)),s.length>0&&Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return Q.createElement(ne,{key:e,color:r?ar.CYAN:ar.GRAY,bold:r},r?` ${Pe.pointer} `:" ",e)})),Q.createElement(te,{marginTop:1},Q.createElement(BracketedText,{text:w,color:ar.DIM})))},"AddDirModal");Ot(),Ot(),wn(),Ot(),Ot(),wn(),Rr();var Rx=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),Mx=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Lx=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=Y("idle"),[i,a]=Y(""),l=[...fk.map(e=>e.name),...yk.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void a("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?Rx():Mx();await k.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),i=Array.from(e.selectedTools).map(e=>Ek[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await k.writeFile(s,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");se((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>Ek[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return Q.createElement(te,{flexDirection:"column",gap:1},Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Name:"),Q.createElement(ne,{color:ar.GRAY},e.agentType)),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Location:"),Q.createElement(ne,{color:ar.GRAY},m)),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Tools:"),Q.createElement(ne,{color:ar.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Description"),Q.createElement(ne,{color:ar.GRAY},"(Tells ","Command Code"," when to use this agent):")),Q.createElement(ne,{color:ar.GRAY},e.ccToolDefinition),Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"System Prompt:")),Q.createElement(ne,{color:ar.GRAY},e.sysPrompt),!r&&Q.createElement(te,{marginTop:1},"idle"===o&&Q.createElement(te,{gap:1},Q.createElement(ne,{color:ar.GREEN,dimColor:!0},"Press"),Q.createElement(ne,{color:ar.GREEN,bold:!0},"Enter"),Q.createElement(ne,{color:ar.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===o&&Q.createElement(ne,{color:ar.YELLOW},"Saving agent..."),"saved"===o&&Q.createElement(ne,{color:ar.GREEN},Pe.tick," ",i),"error"===o&&Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.RED},Pe.cross," Error: ",i),Q.createElement(ne,{color:ar.GRAY},"Press Enter to retry"))))},"AgentSummary");Rr();var $x=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=Y("menu"),i=[...fk.map(e=>e.name),...yk.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>bk[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(se((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return Q.createElement(te,{flexDirection:"column"},Q.createElement(Lx,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Press Enter to go back")));if("edit"===o)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.YELLOW},"Edit functionality coming soon..."),Q.createElement(ne,{color:ar.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 k.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return Q.createElement(te,{flexDirection:"column",gap:1},Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.RED},"Delete agent"),Q.createElement(ne,{color:ar.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),Q.createElement(te,null,Q.createElement(mt,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)})))}return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE,bold:!0},e.name),Q.createElement(te,{marginTop:1},Q.createElement(mt,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");Rr();var Dx=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=Y([]),[s,i]=Y([]),[a,l]=Y([]),[u,d]=Y(!0),[m,g]=Y(!1),[h,f]=Y(null),[y,w]=Y(!1),E=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),C=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),v=__name(async(e,n)=>{try{g(!1);const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=Ke(s);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");X(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([v(E(),"personal"),v(C(),"project")]),n=Kv.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),i(t),l(n),d(!1)},"loadAgents")()},[m]);const T=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{T.push({label:e.name,value:e.filePath})}),s.forEach(e=>{T.push({label:e.name,value:e.filePath})});const _=r.length+s.length,x=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(f(e),w(!0))}},"handleAgentSelect");if(u)return Q.createElement(ne,{color:ar.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return Q.createElement($x,{agent:h,onBack:()=>{w(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const A=__name(({isSelected:e,label:t})=>{const n=T.find(e=>e.label===t),o=n?.value||"",i=r[0]?.filePath===o,a=s[0]?.filePath===o;return Q.createElement(te,{flexDirection:"column"},i&&r.length>0&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY,bold:!0},"User agents")),a&&s.length>0&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY,bold:!0},"Project agents")),Q.createElement(te,null,Q.createElement(ne,{color:ar.WHITE},e?">":" "),Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY}," ",t)))},"CustomItemComponent");return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Agents"),_>0?Q.createElement(ne,{color:ar.GRAY}," ","(",_," agent",_>1?"s":"",")"):Q.createElement(ne,{color:ar.GRAY}," (No custom agents)")),n&&Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{color:ar.GREEN,dimColor:!0},"Created agent: ",n)),Q.createElement(mt,{items:T,onSelect:x,indicatorComponent:()=>null,itemComponent:A}),a.length>0&&Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(ne,{color:ar.GRAY,bold:!0},"Default agents"),a.map(e=>Q.createElement(ne,{key:e.filePath,color:ar.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(ne,{color:ar.GRAY},"Create specialized subagents that Command Code can delegate to."),Q.createElement(ne,{color:ar.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ot(),wn(),Ds(),Rr(),Ot(),Ot(),wn(),Rr();var Ox=__name(({onSelect:e})=>Q.createElement(mt,{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(ne,{color:e?ar.WHITE:ar.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)}),"LocationSelector");Ot(),$r(),wn(),qr(),zr(),Rr();var Fx=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=Y(!1),[g,h]=Y(!1),f=ee(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]),y=ee(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(Ek).some(e=>Fe(e)===Fe(t))||Object.keys(Ek).some(e=>Fe(e)===Fe(t)))&&Q.createElement(ne,{color:ar.RED},Pe.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Fe(t))&&Q.createElement(ne,{color:ar.RED},Pe.warning," This name is reserved. Reserved names:"," ",Qv.join(", "))),Q.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Fe(t);Object.values(Ek).some(t=>Fe(t)===e)||Object.keys(Ek).some(t=>Fe(t)===e)||isReservedAgentName(e)||a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE},"Enter the system prompt for your agent:"),Q.createElement(ne,{color:ar.GRAY},"Be comprehensive for best results.")),Q.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.WHITE},"When should ","Command Code"," use this agent?"),Q.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ot(),Rr();var qx=__name(({onSelect:e})=>Q.createElement(mt,{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(ne,{color:e?ar.WHITE:ar.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY},` ${t}`)}),"MethodSelector");Ot(),$r(),Ot(),Sb(),Rr();var jx=["·","○","◇","☆","✧","☆","◇","○","⌘"],Ux=[12,5,4,4,4,4,4,5,16],Bx=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<Ux.length;e++)if(n+=Ux[e],t<n)return jx[e];const r=t-58;n=0;for(let e=0;e<Bx.length;e++)if(n+=Bx[e],r<n)return jx[7-e];return jx[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=Z(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<_r.length?_r[n]:xr},"getCharColor");return Q.createElement(ne,null,r.map((e,t)=>Q.createElement(ne,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return Q.createElement(ne,{color:t??lr,bold:!0},`${getWaveSymbol(e)} `)}function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var zx=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=Y(0),[s,i]=Y(0),a=J(n);a.current=n;const l=getTerminalWidth(),[u,d]=Y(()=>l>=72?"all":l>=42?"medium":"none");X(()=>{d(e=>"all"===e?l<68?l>=42?"medium":"none":"all":"medium"===e?l>=72?"all":l<38?"none":"medium":l>=72?"all":l>=42?"medium":"none")},[l]),X(()=>{const e=setInterval(()=>{o(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const m=r%(e.length+10),g="all"===u,h="medium"===u;return hb.statusRender({width:l,layoutMode:u,status:e,frame:r}),Q.createElement(te,{width:l,height:1,paddingLeft:0,marginLeft:0},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:gr.BG,color:gr.FG}," "),Q.createElement(ne,{backgroundColor:gr.BG},Q.createElement(CMDIcon,{frame:4*r})),Q.createElement(ShimmerText,{text:e,offset:m,bg:gr.BG}),Q.createElement(ne,{backgroundColor:gr.BG,color:gr.FG}," ")),g&&Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,{bold:!0,color:ar.GRAY},"esc"),Q.createElement(ne,{color:ar.DIM},"to interrupt"),Q.createElement(ne,{color:ar.DIM},"•"),Q.createElement(ne,{color:ar.DIM},formatTime3(t)),Q.createElement(ne,{color:ar.DIM},"•"),Q.createElement(ne,{color:ar.GRAY},Pe.arrowDown),Q.createElement(ne,{color:ar.DIM},formatToken(Math.round(s)))),h&&Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM},formatToken(Math.round(s)))))},"Status");zr(),qr(),Rr();var Hx=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=Y(!1),[a,l]=Y(0),[u,d]=Y(0);X(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=ee(()=>{0!==e.trim().length&&n()},[e,n]),g=ee(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return Q.createElement(te,{flexDirection:"column"},r?Q.createElement(te,null,Q.createElement(CMDIcon,{frame:u}),Q.createElement(ne,{color:ar.WHITE},"Generating agent from description...")):Q.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),o&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.RED},`${Pe.warning} ${o}`)))},"RecommendedFlow");Ot(),Rr();var Wx=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=Y(!1),[i,a]=Y(0),l=Z(()=>[...fk.map(e=>e.name),...yk.map(e=>e.name)],[]),u=Z(()=>[{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=Z(()=>{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]":"[ ]"} ${Ek[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 se((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?g.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=g.length?0:t});else if(l.return||" "===e){const e=g[i];if(e){const i=d[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(s(!o),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),Q.createElement(te,{flexDirection:"column"},m.map((e,t)=>{const n=g.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return Q.createElement(te,{key:`divider-${t}`},Q.createElement(ne,{color:ar.GRAY}," ",e.label));if("spacer"===e.type)return Q.createElement(te,{key:`spacer-${t}`,height:1});if("label"===e.type)return Q.createElement(te,{key:`label-${t}`},Q.createElement(ne,{color:ar.GRAY}," ",e.label));const o="continue"===e.type;return Q.createElement(te,{key:`item-${t}`},Q.createElement(ne,{color:r?ar.WHITE:ar.GRAY,bold:o&&r},r?">":" "," ",e.label))}),Q.createElement(te,{marginTop:1},e.size===l.length&&Q.createElement(ne,{color:ar.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&Q.createElement(ne,{color:ar.GRAY},e.size," tools selected"),0===e.size&&Q.createElement(ne,{color:ar.GRAY},"No tools selected")))},"ToolsSelector");ao(),fS(),sS(),Rs(),kb(),Jr();var Gx=__name(({onComplete:e})=>{const[t,n]=Y("location"),[r,o]=Y(!1),[s,i]=Y(null),[a,l]=Y("agentType"),u=Z(()=>[...fk.map(e=>e.name),...yk.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=Y(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[Ut.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[Ut.OAUTH_TOKEN]=`Bearer ${r}`,s&&(a[Ut.OAUTH_PROVIDER]=s));const l=getApiBaseUrl(),u=new jw({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:Bt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:Fe(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof bs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/settings/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Fe(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),C=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),v=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__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(te,{flexDirection:"column",gap:1},Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.WHITE,bold:!0},"Create new agent"),Q.createElement(ne,{color:ar.GRAY},f())),Q.createElement(te,null,"location"===t&&Q.createElement(Ox,{onSelect:y}),"method"===t&&Q.createElement(qx,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&Q.createElement(Hx,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:S}),"configuration"===t&&"manual"===m.method&&Q.createElement(te,{flexDirection:"column",gap:1},Q.createElement(Fx,{step:a,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:C,onCCToolDefinitionSubmit:v})),"tools"===t&&Q.createElement(Wx,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&Q.createElement(Lx,{config:m,onSaveComplete:h})))},"AgentNew");Rr();var Vx=__name(({onCancel:e})=>{const[t,n]=Y(null),[r,o]=Y(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return se((t,n)=>{n.escape&&e()}),Q.createElement(te,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:ar.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&Q.createElement(Dx,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&Q.createElement(Gx,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");Rr(),Ot(),Jr(),Rr();var Qx=[{label:"Compact Normal (default)",value:"default",description:"Summarize session when context limit reached."},{label:"Compact Fast",value:"fast",description:"Fast tiered compaction. Higher quality, uses more tokens."}],Kx=__name(({onSelect:e,onCancel:t})=>{const[n,r]=Y(null);X(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(se((e,n)=>{n.escape&&t()}),null===n)return null;const s=Qx.findIndex(e=>e.value===n);return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Select a compact mode to compact sessions")),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"Choose how Command Code handles automatic context compaction.")),Q.createElement(mt,{items:Qx,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.CYAN},e?Pe.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=Qx.find(e=>e.label===t),o=r?.value===n,s=Qx.findIndex(e=>e.label===t);return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:e?ar.CYAN:o?ar.GREEN:ar.WHITE},` ${s+1}. ${r?.label??t}`),o&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick)),Q.createElement(ne,{color:ar.DIM},` ${r?.description??""}`))}}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to cancel")))},"CompactModeSelector");Ot(),Rr(),Ot(),$r(),wn(),qr(),Bn(),Ot();var Yx=n(E(),"commandcode-images"),Jx={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{D(Yx)||j(Yx,{recursive:!0});const r=Jx[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(Yx,o),i=Buffer.from(e.data,"base64");return U(s,i),s}catch{return null}}function stripInputAfterSuffix(e,t){return t&&e.endsWith(t)?e.slice(0,e.length-t.length):e}function extractAppendedChunk(e,t,n){const r=t+n;return e.length>=r.length&&e.startsWith(r)?e.slice(r.length):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:i,setInitialCursor:a}=e,l=ee((e,t,n="")=>{o(t=>[...t,e]),r(t+n),a(t.length),i()},[o,r,a,i]),u=J(!1),d=J(""),m=J(null),g=J(""),h=J(""),f=ee(async(e,t,o)=>{let u=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const d=await detectDroppedImageFile(u);if(d)return void l(d,t,o);const m=await detectClipboardImage();if(m)return void l(m,t,o);let g=u;if(0===g.length){const e=await detectClipboardText();g=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(!g&&!o)return;if(!g)return r(t+o),a(t.length),void i();if(g.length>300){const e=t+`[Text#${n.length+1}]`;return s(e=>[...e,g]),r(e+o),a(e.length),void i()}const h=t+g;r(h+o),a(h.length),i()},[l,n.length,s,r,a,i]),y=ee(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(async()=>{if(u.current){const e=d.current,t=g.current,n=h.current;d.current="",g.current="",h.current="",u.current=!1,m.current=null,e?await f(e,t,n):n&&await f("",t,n)}},500)},[f]);return{handlePaste:ee(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return u.current&&(u.current=!1,d.current="",g.current="",h.current="",m.current&&(clearTimeout(m.current),m.current=null)),await f(n.pastedContent??n.cleanedContent,n.textBeforePaste??"",n.textAfterPaste??""),!0;if(n.isPasteStart&&!u.current){u.current=!0;const e=n.textBeforePaste??t,r=t.slice(e.length);g.current=e,h.current=r;const o=n.pastedContent??n.cleanedContent;return d.current=stripInputAfterSuffix(o,r),y(),!0}if(u.current&&!n.isPasteEnd){const e=g.current,t=h.current;if(void 0!==n.pastedContent)d.current=stripInputAfterSuffix(n.pastedContent,t);else if(n.cleanedContent){const r=extractAppendedChunk(n.cleanedContent,e,t);d.current=null!==r?d.current+r:accumulateDelta(n.cleanedContent,d.current,e)}return y(),!0}if(u.current&&n.isPasteEnd){m.current&&(clearTimeout(m.current),m.current=null);const e=g.current,t=h.current,r=n.textAfterPaste??"";let o=n.cleanedContent??"";if(r&&o.endsWith(r)&&(o=o.slice(0,o.length-r.length)),void 0!==n.pastedContent)d.current=stripInputAfterSuffix(n.pastedContent,t);else if(o){const n=extractAppendedChunk(o,e,t);d.current=null!==n?d.current+n:accumulateDelta(o,d.current,e)}const s=d.current,i=e,a=r||t;return d.current="",g.current="",h.current="",u.current=!1,await f(s,i,a),!0}if(n.isPasteEnd&&!n.isPasteStart&&!u.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return l(e,t),!0}return!1},[t,f,y,l]),resetPasteState:ee(()=>{u.current=!1,d.current="",g.current="",h.current="",m.current&&(clearTimeout(m.current),m.current=null)},[]),isPasting:ee(()=>u.current,[])}}__name(saveTempImage,"saveTempImage"),er(),ao(),Ot(),zr(),qr(),__name(stripInputAfterSuffix,"stripInputAfterSuffix"),__name(extractAppendedChunk,"extractAppendedChunk"),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),zr(),Ot(),Ot();var Xx=["code --wait","cursor --wait","nano"],Zx=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return Zx.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 Se(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of Xx)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var eA=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 eA;t=ensureWaitFlag(t);const r=n(E(),`commandcode-${Date.now()}.md`);return await _(r,e),new Promise((e,n)=>{const o=t.split(" ").filter(e=>e.length>0),s=o[0],i=o.slice(1),a=be(s,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await A(r,"utf-8");await P(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await P(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=Y(!1),[l,u]=Y(null),d=ee(async()=>{if(!i){a(!0),u(null);try{let i=e.replace(/\n+$/,"");r.forEach((e,t)=>{const n=`[Text#${t+1}]`;i.includes(n)&&(i=i.replace(n,e))});const a=await openInEditor2(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){u(e instanceof eA?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{a(!1)}}},[e,t,n,r,o,s,i]),m=ee(()=>{u(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:m}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),Ot();var tA=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=Y(null),o=J(!1);return X(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,AT().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=nt(),r=n(e,".gitignore");if(D(r))try{const e=F(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}Rr(),Ot(),Rr(),__name(loadGitignore,"loadGitignore");var nA=__name(({onSelectFile:e,onClose:t,searchQuery:o=""})=>{const[i,l]=Y(process.cwd()),[u,d]=Y([]),[m,g]=Y(0),[h,f]=Y(0),y=o.trim()?15:10,w=ee((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const o=n(t,e);try{const e=B(o),i=[];return e.forEach(e=>{const a=n(o,e);try{const e=z(a),n=s(t,a);if(r.ignores(n))return;i.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}),i.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i.slice(0,50)}catch{}}if(e.includes("/")){const o=e.split("/"),i=o.pop()||"",a=n(t,o.join("/"));try{const e=B(a),o=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=z(i),n=s(t,i);if(r.ignores(n))return;o.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),o.slice(0,50)}catch{}}const o=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{B(e).forEach(u=>{const d=n(e,u);try{const e=z(d),n=s(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&o.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&a(d,l+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),o.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),o=n===i,s=r===i;if(o&&!s)return-1;if(!o&&s)return 1;const a=n.split("/").pop()||"",l=r.split("/").pop()||"",u=a.includes(i),d=l.includes(i);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,g=t.name.split("/").length;return m!==g?m-g:e.name.localeCompare(t.name)}),o.slice(0,50)},[]),S=ee(e=>{try{const t=B(e),o=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&o.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=z(r),n=s(i,r);if(a.ignores(n))return;o.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(o),g(0),f(0)}catch{}},[]);X(()=>{if(o.trim()){const e=w(o);d(e),g(0),f(0)}else S(i)},[i,S,o,w]),se((n,r)=>{if(r.escape)t();else if(r.upArrow)g(e=>{const t=Math.max(0,e-1);return t<h&&f(t),t});else if(r.downArrow)g(e=>{const t=Math.min(u.length-1,e+1);return t>=h+y&&f(t-y+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!o.trim()&&l(a(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const E=u.slice(h,h+y);return Q.createElement(te,{flexDirection:"column",paddingLeft:1},Q.createElement(te,{marginBottom:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},o.trim()?`Searching for: "${o}"`:`Files: ${i}`),Q.createElement(ne,{color:ar.DIM},o.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?Q.createElement(ne,{color:ar.DIM},o.trim()?`No files found matching "${o}"`:"No files found in this directory"):E.map((e,t)=>{const n=h+t,r=e.name,o=n===m;return Q.createElement(ne,{key:e.path,color:o?ar.GREEN:ar.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ot(),wn(),io(),Rr(),Ot(),Rr();var rA=__name(e=>{if(e>=1e6){const t=e/1e6;return`${t%1==0?t.toFixed(0):t.toFixed(1)}M`}return`${Math.round(e/1e3)}k`},"formatTokens"),oA=__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&&e.current>=18e4)return Q.createElement(te,{paddingRight:3},Q.createElement(ne,{color:ar.DIM},"~",rA(e.current)," tokens in context · try"," "),Q.createElement(ne,{color:ar.DIM,bold:!0},"/compact"));if(n>20)return null;const r=__name(e=>e>=90?ar.RED:e>=70?ar.YELLOW:ar.DIM,"getColor"),o=t>=90?6:Math.round(t/100*6),s=6-o,i=Pe.square.repeat(o),a=Pe.squareLightShade.repeat(s),l=r(t);return Q.createElement(te,{paddingRight:3},Q.createElement(ne,{color:l},`Context left before auto-compact ${n}% `),Q.createElement(ne,{color:l},i),s>0&&Q.createElement(ne,{color:ar.DIM},a))},"ContextUsage");Ot(),as(),Rr();var sA=__name(()=>{const[e,t]=Y("continuous learning"),[n,r]=Y(!1),[o,s]=Y(!1),i=J([]),a=J(0),l=J(null),u=J(!1);X(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),s(!1),i.current=[],a.current=0,l.current&&(clearTimeout(l.current),l.current=null),void t(e.message)):u.current&&"analyzed"!==e.type?void i.current.push(e):"analyzed"===e.type?(u.current=!1,void(i.current.length>0?(a.current=0,n()):(r(!1),s(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),s(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const o="learned"===e.type||"refactored"===e.type;s(o);const u="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;l.current=setTimeout(()=>{a.current++,n()},u)},"cycleThroughNextEvent");return Yk.on("new-event",e),()=>{Yk.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?Pe.squareSmallFilled:Pe.squareSmall} TASTE`,m=9+e.length+d.length>Jo;let g=e;g=truncateString(m?{text:e,maxChars:Jo}:{text:e,maxChars:Jo-d.length-9-10});const h=o?void 0:ar.DIM;return Q.createElement(te,{paddingRight:2},!m&&Q.createElement(Q.Fragment,null,Q.createElement(BracketWrap,{color:ar.DIM},"ctrl+t"),Q.createElement(ne,{color:ar.DIM}," ")),Q.createElement(ne,{color:h},g),!m&&Q.createElement(ne,{color:cr.TEXT},d))},"LearningFeedMini");Ot(),Rr();var iA=__name(({mode:e,pendingExitKey:t})=>t?Q.createElement(ne,{color:ar.DIM},"Press Ctrl+C again to exit"):"bypass"===e?Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:ar.RED},"» permission bypass on "),Q.createElement(BracketWrap,{color:ar.DIM},"shift+tab")):"auto-accept"===e?Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:Cr},"» accept edits on "),Q.createElement(BracketWrap,{color:ar.DIM},"shift+tab")):"plan"===e?Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:br},"plan mode "),Q.createElement(BracketWrap,{color:ar.DIM},"shift+tab")):Q.createElement(ne,{color:ar.DIM},"? for shortcuts"),"ModeIndicator");Ot(),Rr(),Xr();var aA=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?ar.DIM:vr.MERGED;return Q.createElement(Q.Fragment,null,t&&Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:n},"PR "),Q.createElement(Kr,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),lA=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?Q.createElement(Q.Fragment,null,t&&Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{color:"connected"===e.type?ar.GREEN:ar.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),cA=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const C=e>=60;return Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r||l?Q.createElement(te,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(te,{flexDirection:"row",columnGap:0},n&&!l?Q.createElement(ne,{color:yr},t):Q.createElement(iA,{mode:r,pendingExitKey:l}),!l&&Q.createElement(aA,{prInfo:o}),!l&&Q.createElement(lA,{indicator:a})),C&&Q.createElement(te,{flexDirection:"column",alignItems:"flex-end"},s&&Q.createElement(sA,null),i&&Q.createElement(oA,{usage:i}))):Q.createElement(Q.Fragment,null,Q.createElement(te,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(iA,{mode:r}),C&&s&&Q.createElement(sA,null)),Q.createElement(te,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(te,{flexDirection:"row",columnGap:0},Q.createElement(ne,{color:n?yr:ar.DIM},t),Q.createElement(aA,{prInfo:o}),Q.createElement(lA,{indicator:a})),C&&i&&Q.createElement(oA,{usage:i}))),(u||d||g&&m)&&Q.createElement(te,{flexDirection:"row",columnGap:1},u&&Q.createElement(ne,null,Pe.tick," ","Command Code"," updated:"," ",Q.createElement(ne,{color:ar.DIM},"v",u.updatedFrom),Q.createElement(ne,{color:ar.DIM}," ",Pe.arrowRight," "),Q.createElement(ne,null,"v",u.updatedTo)),!u&&d&&Q.createElement(ne,{color:ar.YELLOW,dimColor:!0},Pe.info," Update available:"," ",d.currentVersion," ",Pe.arrowRight," ",d.latestVersion),g&&m&&Q.createElement(ne,{color:ar.GREEN,dimColor:!0},Pe.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:ar.GREEN},"! for bash mode")),y&&f&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:lr},"SHARED: ",f.url," (copied to clipboard)")),w&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:w.includes("NOT SHARED")?ar.RED:lr},w)),S&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:lr},S)),E&&Q.createElement(te,{paddingLeft:2},Q.createElement(ne,{color:ar.YELLOW},Pe.warning," ",E)))},"BottomIndicator");Ot(),as(),Rr();var uA=12,dA=__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"),mA=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),pA=__name(e=>truncateString({text:mA(e),maxChars:Yo}),"truncateMessage"),gA=__name(e=>e.title?mA(e.title):pA(e.firstMessage),"getSessionSummary"),hA=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=Y([]),[o,s]=Y(0),[i,a]=Y(0),[l,u]=Y(!0),[d,m]=Y(!1),[g]=Y(()=>getCurrentGitBranch());X(()=>{__name(async()=>{u(!0);const e=await ok.listSessions();r(e),u(!1)},"loadSessions")()},[]);const h=d&&g?n.filter(e=>e.gitBranch===g):n;if(se((n,r)=>{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),s(0),void a(0)):void(r.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?s(e=>{const t=Math.min(h.length-1,e+1);return t>=i+uA&&a(t-uA+1),t}):r.return&&h.length>0&&o<h.length&&e(h[o].id));t()}),l)return Q.createElement(te,{flexDirection:"column",paddingLeft:2},Q.createElement(ne,{color:ar.GRAY},"Loading sessions..."));if(0===h.length)return Q.createElement(te,{flexDirection:"column",paddingLeft:2},Q.createElement(ne,{color:ar.GRAY},d&&g?`No sessions found for branch "${g}"`:"No previous sessions found"),Q.createElement(ne,{color:ar.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const f=h.slice(i,i+uA);return Q.createElement(te,{flexDirection:"column",paddingLeft:1,width:"100%"},Q.createElement(ne,{color:ar.CYAN,bold:!0},"Resume Session"),Q.createElement(te,{marginTop:1}),Q.createElement(te,{columnGap:2,marginBottom:1},Q.createElement(te,{width:5},Q.createElement(ne,{color:ar.GRAY}," ")),Q.createElement(te,{width:13},Q.createElement(ne,{color:ar.GRAY},"Modified")),Q.createElement(te,{width:20},Q.createElement(ne,{color:ar.GRAY},"Git Branch")),Q.createElement(te,{width:11},Q.createElement(ne,{color:ar.GRAY},"# Messages")),Q.createElement(te,null,Q.createElement(ne,{color:ar.GRAY},"Summary"))),Q.createElement(te,{columnGap:2},Q.createElement(te,{flexDirection:"column",width:5},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`sel-${n}`,color:o===n?ar.WHITE:ar.GRAY},o===n?`${Pe.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(te,{flexDirection:"column",width:13},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`mod-${e.id}`,color:o===n?ar.WHITE:ar.GRAY},dA(e.lastModified))})),Q.createElement(te,{flexDirection:"column",width:20},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`branch-${e.id}`,color:o===n?ar.WHITE:ar.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(te,{flexDirection:"column",width:11},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`msg-${e.id}`,color:o===n?ar.WHITE:ar.GRAY},e.messageCount)})),Q.createElement(te,{flexDirection:"column"},f.map((e,t)=>{const n=i+t;return Q.createElement(ne,{key:`summary-${e.id}`,color:o===n?ar.WHITE:ar.GRAY,wrap:"truncate-end"},gA(e))}))),Q.createElement(te,{marginTop:1}),h.length>uA&&Q.createElement(ne,{color:ar.DIM},"Showing ",i+1,"–",Math.min(i+uA,h.length)," ","of ",h.length,i>0?" · ↑ more":"",i+uA<h.length?" · ↓ more":""),Q.createElement(ne,{color:ar.DIM},"↑↓ navigate · Enter select · ctrl+b ",d?`[branch: ${g??"unknown"}]`:"branch filter"," · ESC cancel"))},"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,i=e+(r.length>0?1:0);r.length>0&&o+i>t?(n.push(r),r=[s],o=e):(r.push(s),o+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return Q.createElement(ne,null,r?" ":"",t?Q.createElement(ne,{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}),i=Math.max(1,r-(s.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return Q.createElement(te,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>Q.createElement(te,{key:r,flexDirection:"row"},Q.createElement(te,{flexShrink:0,marginRight:1},0===r&&Q.createElement(ne,{color:ar.DIM},s)),Q.createElement(te,{flexDirection:"row"},e.map((e,r)=>Q.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ot(),Rr(),Ot(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),ro(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ot();var fA=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=Y(null),[s,i]=Y(!1),a=J(!1),l=J(null),u=J(n),[d,m]=Y(!1),[g,h]=Y("connected"),f=J(null),y=J(null),w=ee((e,t)=>{y.current&&(clearTimeout(y.current),y.current=null),h(e),m(!0),void 0!==t&&(y.current=setTimeout(()=>{m(!1)},t))},[]),S=ee(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),E=ee(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Mv,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=f.current;if(null===r?n&&w("connected",3e3):r!==n&&(n?w("connected",2e3):w("disconnected",5e3)),f.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),o(r)}else o(null)}catch{!0===f.current&&w("disconnected",5e3),f.current=!1,i(!1),o(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[w]);X(()=>{const e=u.current;u.current=n,e&&!n&&t&&null!==vv()&&E(!1)},[n,t,E]),X(()=>{if(!t)return;if(null===vv())return;let e=null,n=!1,r=0;function schedule(t){n||(e=setTimeout(()=>{tick(!1)},t))}async function tick(e){if(u.current)return void schedule(500);if(await E(e),n)return;if(l.current?.isConnected)return r=0,void schedule(500);r+=1;const t=Math.min(r,6);schedule(Math.min(3e4,500*2**t)+250*Math.random())}return __name(schedule,"schedule"),__name(tick,"tick"),tick(!0),()=>{n=!0,e&&clearTimeout(e),S(),l.current?.disconnect(),l.current=null}},[t,E,S]);const C=vv(),v={visible:d,message:"connected"===g?`${C?LT[C]??"IDE":"IDE"} ${Pe.tick}`:"run /ide",type:g};return{context:r,connected:s,refresh:E,connectionIndicator:v}},"useVSCodeContext");Ot();var yA=__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 i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"</ide-context>").replace(/[\u202A-\u202E\u2066-\u2069\u200B-\u200D\uFEFF]/g,"");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Ot();var wA=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),SA=__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"),EA=["","[118;5u","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var bA=__name(()=>Q.createElement(te,{flexDirection:"column",paddingLeft:1},Q.createElement(ne,{color:ar.DIM,bold:!0},"Available Shortcuts:"),Q.createElement(te,{columnGap:4},Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},"! for bash mode"),Q.createElement(ne,{color:ar.DIM},"/ for commands"),Q.createElement(ne,{color:ar.DIM},"@ for file paths"),Q.createElement(ne,{color:ar.DIM},"shift + tab to toggle auto-accept")),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},"double tap esc to clear input"),Q.createElement(ne,{color:ar.DIM},"ctrl + j / shift + ⏎ for newline"),Q.createElement(ne,{color:ar.DIM},"ctrl + g to open in editor"),Q.createElement(ne,{color:ar.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),CA=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:C,updateFailedInfo:v,currentProvider:k,showProviderInfo:T,permissionMode:_="standard",onToggleAutoAccept:x,hintMessage:A,historyManager:P,pendingExitKey:I=null,onOverlayVisibilityChange:N,onDoubleEscapeEmpty:R,onAltP:M,isProcessing:L=!1,ideContextEnabled:$=!0})=>{const[D,O]=Y(0),[F,q]=Y(!1),[j,U]=Y(!1),[B,z]=Y(!1),[H,W]=Y(!1),[G,V]=Y(""),[K,re]=Y(!1),ie=J(0),ae=J(0),[le,ce]=Y([]),[ue,de]=Y([]),[me,pe]=Y(-1),[ge,he]=Y(""),fe=J(!1),ye=J(!1),we=J(void 0),[Se,Ee]=Y(-1),[be,Ce]=Y(""),ve=J(0),{isEditorOpen:ke,editorError:Te,handleOpenInEditor:_e,clearEditorError:xe}=useExternalEditor({input:e,setInput:n,setInputKey:O,detectedContent:le,setDetectedContent:ce,onEditorClose:__name(()=>{fe.current=!1},"onEditorClose")}),{handlePaste:Ae,resetPasteState:Ie,isPasting:Ne}=useBracketedPaste({input:e,detectedContent:le,setInput:n,setDetectedImages:de,setDetectedContent:ce,incrementInputKey:__name(()=>O(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{we.current=e},"setInitialCursor")}),{context:Re,connected:Me,refresh:Le,connectionIndicator:$e}=fA({enabled:$,paused:L}),{stdout:De}=oe(),Oe=De?.columns??80,{pr:Fe}=tA();X(()=>{const e=i||H||K;N?.(e)},[i,H,K,N]);const qe=ee(()=>{de([]),pe(-1)},[]),je=ee(()=>{n(""),U(!1),W(!1),V(""),re(!1),ce([]),qe(),he(""),Ie(),Ee(-1),Ce(""),O(e=>e+1)},[n,Ie,qe]),Ue=ee(()=>{fe.current=!0;const{text:t,cursor:r}=insertTextAt(e,ve.current,"\n");n(t),we.current=r,O(e=>e+1),setTimeout(()=>{fe.current=!1},0)},[e,n]);se(async(t,r)=>{if(-1!==me&&r.leftArrow)return void pe(prevImageIndex({currentIndex:me,imageCount:ue.length}));if(-1!==me&&r.rightArrow)return void pe(nextImageIndex({currentIndex:me,imageCount:ue.length}));if(r.upArrow){if(i||H||K)return;const t=e.indexOf("\n"),r=-1===t||ve.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ue.length,selectedImageIndex:me,historyIndex:Se}))return void pe(ue.length-1);if(-1!==me&&pe(-1),0!==e.length&&-1===Se&&!r)return;const o=P?.count()??0;if(0===o)return;-1===Se&&Ce(e);const s=Math.min(Se+1,o-1);return void(s!==Se&&(Ee(s),n(P?.getAt(s)||""),O(e=>e+1)))}if(r.downArrow){if(i||H||K)return;if(-1===Se)return;const t=e.lastIndexOf("\n");if(!(-1===t||ve.current>t))return;const r=Se-1;return Ee(r),n(-1===r?be:P?.getAt(r)||""),void O(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void qe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return fe.current=!0,void _e();if(getIsExpandToolShortcut(r,t))return fe.current=!0,n(e),O(e=>e+1),void setTimeout(()=>{fe.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ne()}))return ye.current=!0,Ue(),void setTimeout(()=>{ye.current=!1},0);if(r.meta&&r.backspace)return void je();if(r.meta&&"w"===t)return fe.current=!0,void je();const o=r.ctrl&&"v"===t||EA.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e;fe.current=!0;const r=await detectClipboardImage();return r&&(de(e=>[...e,r]),n(t),O(e=>e+1)),void(fe.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return z(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==me&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ue,index:me});return de([...e]),void pe(t)}if(r.escape){if(-1!==me)return void pe(-1);if(H)return;if(K)return re(!1),n(ge),void O(e=>e+1);const t=Date.now();return t-ie.current<500?(e.length>0?je():R?.(),ie.current=0,ae.current=0):(ie.current=t,F||j||(ae.current=t)),q(!1),void U(!1)}F&&(r.backspace||r.delete)&&0===e.length&&q(!1)}});const Be=ee(async t=>{if(ke)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void M?.();const o=processBracketedPaste(t);if((o.isPasteStart||o.isPasteEnd||Ne())&&await Ae(t))return;if(fe.current)return void(fe.current=!1);-1!==Se&&Ee(-1);const s=1===t.length,l=t.slice(-1);if(s){if("?"===l&&!F)return q(!0),n(""),void O(e=>e+1);if("!"===l&&!j)return q(!1),U(!0),n(""),void O(e=>e+1)}if("/"!==l||H||"/"!==t||(W(!0),V("")),H&&!t.startsWith("/")&&(W(!1),V("")),H&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(W(!1),V("")):V(e)}"@"!==l||i||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(a(!0),u(""));const d=t.lastIndexOf("@");if(t.length<e.length&&-1!==d&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(d+1),n=!e.includes(" "),r=d>0?t[d-1]:"";n&&isPrecededByWhitespace(r)&&(a(!0),u(e))}if(i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!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),a(!1)}else u(n)}}F&&(t!==e||t.length<e.length)&&q(!1),Te&&xe(),0===t.length&&(U(!1),W(!1),V(""),re(!1),ce([]),u(""),he(""),Ie()),n(t)},[F,e,n,i,a,H,j,ue,Se,Ae,Ie,M,Te,xe,ke]),ze=ee(async()=>{if(Le(),ae.current=0,F)return void q(!1);let n=e.trim();if(!j&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return P?.add(n),U(!1),W(!1),V(""),qe(),ce([]),Ee(-1),void Ce("");Ee(-1),Ce("");let r=[];const o=ue.length>0,s=le.length>0;if(!j&&o&&(r=[...ue]),!j&&s){let e=n;le.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}n.length>0&&P?.add(n);const i=Re?.selection?{lines:Re.selection.lineCount,file:Re.activeFile?.relativePath?.split("/").pop()??Re.activeFile?.path?.split("/").pop()??"unknown",ide:LT[vv()??""]??"IDE"}:void 0;t({input:n,role:j?"bash":"user",images:r,ideContext:Re?yA(Re):void 0,ideHint:i}),U(!1),W(!1),V(""),qe(),ce([])},[t,d,F,e,j,ue,le,P,Le,qe]),He=ee(t=>{const r=s(process.cwd(),t);let o;if(i&&""!==l){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),a(!1),u(""),O(e=>e+1)},[n,a,e,i,l,u]),We=ee(()=>{a(!1),u("")},[a,u]),Ge=ee(t=>{if("/resume"===t)P?.add(t),Ee(-1),Ce(""),he(e),W(!1),V(""),re(!0),n(""),O(e=>e+1);else{const e=Object.values(__).includes(t),r=x_.has(t);W(!1),V(""),e&&r?(P?.add(t),Ee(-1),Ce(""),n(""),O(e=>e+1),d&&d(t)):(n(t+" "),O(e=>e+1))}},[d,n,e,P]),Ve=ee(e=>{W(!1),V(""),n(e+" "),O(e=>e+1)},[n]),Qe=ee(()=>{W(!1),V(""),n(""),Ee(-1),Ce(""),O(e=>e+1)},[n]),Ke=ee(e=>{re(!1),n(""),he(""),Ee(-1),Ce(""),O(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ye=ee(()=>{re(!1),n(ge),Ee(-1),Ce(""),O(e=>e+1)},[ge,n]),Je=ee(e=>{ve.current=e,we.current=void 0},[]),Xe=Z(()=>{const t=Fe&&("OPEN"===Fe.state||"MERGED"===Fe.state);return"auto-accept"===_||"plan"===_||"bypass"===_||Me||t?!F&&!K:!F&&0===e.length&&!j&&!K},[F,e,j,K,_,Me,Fe]),Ze=J(new Map),et=Z(()=>ue.map((e,t)=>{if(Ze.current.has(e))return Ze.current.get(e)??null;const n=saveTempImage(e,t+1);return Ze.current.set(e,n),n}),[ue]),tt=__name(()=>F||i||H||K||B?0:Xe||I||j?3:4,"getBottomMargin");return Q.createElement(te,{width:"100%",flexDirection:"column",marginBottom:tt()},!K&&Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(ImageRowsDisplay,{detectedImages:ue,selectedImageIndex:me,imageTempPaths:et,termWidth:Oe,inHistory:-1!==Se}),Q.createElement(ne,{color:j?ar.GREEN:ar.GRAY},Pe.line.repeat(Oe)),Q.createElement(TextInput,{key:D,value:e,placeholder:ke?"Save and close the editor to continue...":o,onChange:Be,onSubmit:()=>{if(!ye.current)return Date.now()-ae.current<100?(ae.current=0,void Ue()):void(i||H||K||ke||ze());ye.current=!1},showCursor:!ke&&r&&-1===me,onCursorChange:Je,initialCursor:we.current,prefix:`${j?"!":Pe.pointer} `,prefixColor:j?ar.GREEN:ar.WHITE}),Q.createElement(ne,{color:j?ar.GREEN:ar.GRAY},Pe.line.repeat(Oe))),F&&Q.createElement(bA,null),B&&Q.createElement(te,{paddingTop:1},Q.createElement(ne,{color:ar.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&Q.createElement(nA,{onSelectFile:He,onClose:We,searchQuery:l}),H&&Q.createElement(I_,{onSelectCommand:Ge,onInsertCommand:Ve,onClose:Qe,searchQuery:G}),K&&Q.createElement(hA,{onSelectSession:Ke,onClose:Ye}),!H&&(Xe||I)&&Q.createElement(cA,{termWidth:Oe,indicatorText:SA(Me,Re,Oe),isIDEIndicator:wA(Me,Re),permissionMode:_,prInfo:Fe,tasteLearning:g,contextUsage:m,connectionIndicator:$e,pendingExitKey:I,updateStatus:C,updateFailedInfo:v,currentProvider:k,showProviderInfo:T,isBashMode:j,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),Te&&Q.createElement(te,{paddingLeft:1,flexDirection:"column"},Q.createElement(ne,{color:ar.YELLOW},Te)))},"InputBox");Ot(),as(),Rr();var vA=__name(({messages:e})=>0===e.length?null:Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(te,{marginBottom:0},Q.createElement(ne,{color:dr,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>Q.createElement(te,{key:t},Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," "),Q.createElement(ne,{color:ar.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),kA=Q.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:C,updateStatus:v,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:A,onToggleAutoAccept:P,hintMessage:I,historyManager:N,pendingExitKey:R,onResetPendingExitKey:M,onDoubleEscapeEmpty:L,retryAttempt:$,onAltP:D})=>{const[O,F]=Y(0),q=J(o);return X(()=>{R&&o!==q.current&&o.length>0&&M?.(),q.current=o},[o,R,M]),X(()=>{if(!t)return void F(0);const e=setInterval(()=>{F(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),Q.createElement(te,{flexDirection:"column"},Q.createElement(vA,{messages:e}),Q.createElement(te,{flexDirection:"row",justifyContent:"space-between"},Q.createElement(te,{flexDirection:"column"},(t||n.isExecuting)&&null===$&&Q.createElement(zx,{tokens:g,timeElapsed:O,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),I&&Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM}," ","⎿"," ","Tip: ",I)))),Q.createElement(CA,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:C,updateStatus:v,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:A,onToggleAutoAccept:P,hintMessage:I,historyManager:N,pendingExitKey:!R||t||n.isExecuting?null:R,onDoubleEscapeEmpty:L,onAltP:D,isProcessing:t}))});Ot(),LE(),qE(),Zr(),io();var TA=__name(({onComplete:e,onCancel:t})=>{const[n,r]=Y(!1),[o,s]=Y(""),{authState:i,statusMessage:a,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 se((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(Yr,{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(DE,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");function buildOAuthMetadataUrl(e){const t=new g(e),n="/"===t.pathname?"":t.pathname.replace(/\/+$/,"");return t.pathname=`/.well-known/oauth-authorization-server${n}`,t.search="",t.hash="",t.toString()}function buildOidcMetadataUrl(e){const t=new g(e),n=t.pathname.replace(/\/+$/,"");return t.pathname=`${n}/.well-known/openid-configuration`,t.search="",t.hash="",t.toString()}async function tryFetchAsMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.authorization_endpoint&&n.token_endpoint?{authorizationEndpoint:n.authorization_endpoint,tokenEndpoint:n.token_endpoint,registrationEndpoint:n.registration_endpoint,scopes:n.scopes_supported}:null}catch(t){return dlog(`[MCP] OAuth metadata fetch failed for ${e}`,t),null}}async function discoverOAuthMetadataFromIssuer(e){return await tryFetchAsMetadata(buildOAuthMetadataUrl(e))||await tryFetchAsMetadata(buildOidcMetadataUrl(e))}async function discoverOAuthMetadata(e){const t=new g(e),n=`${t.protocol}//${t.host}`;return await tryFetchAsMetadata(`${n}/.well-known/oauth-authorization-server`)||await tryFetchAsMetadata(`${n}/.well-known/openid-configuration`)}function parseResourceMetadataUrl(e){if(!e)return null;const t=e.match(/resource_metadata\s*=\s*"([^"]+)"|resource_metadata\s*=\s*([^\s,]+)/i);return t?t[1]??t[2]??null:null}async function fetchProtectedResourceMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{authorizationServers:n.authorization_servers,scopesSupported:n.scopes_supported}}catch(e){return dlog("[MCP] Protected resource metadata fetch failed",e),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:pS,capabilities:{},clientInfo:gS}})});if(401===t.status||403===t.status){const n=parseResourceMetadataUrl(t.headers?.get?.("www-authenticate")??null);if(n){const e=await fetchProtectedResourceMetadata(n),t=e?.authorizationServers?.[0];if(t){const n=await discoverOAuthMetadataFromIssuer(t);if(n)return e?.scopesSupported&&(n.scopes=e.scopesSupported),{requiresAuth:!0,metadata:n}}}return{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}}return{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}async function discoverAndAuthenticate({serverName:e,serverUrl:t,onStatus:n}){const r=n??(()=>{});r("Probing server for OAuth requirements...");const o=await checkServerAuthRequirements(t);if(o.error)return{success:!1,error:o.error};if(!o.requiresAuth)return{success:!1,error:"Server does not require authentication"};if(!o.metadata)return{success:!1,error:"Server returned 401 but did not advertise OAuth metadata. Add `oauth` config manually via `mcp add-json`."};const{authorizationEndpoint:s,tokenEndpoint:i,registrationEndpoint:a,scopes:l}=o.metadata;if(!a)return{success:!1,error:"Server requires pre-registered OAuth credentials (no Dynamic Client Registration endpoint advertised). Register an OAuth client with the server, then add it via `mcp add-json` with an `oauth.clientId` field."};const u=`http://${LS}:${MS}/callback`;r("Registering OAuth client...");const d=await registerOAuthClient({registrationEndpoint:a,clientName:gS.name,redirectUris:[u]});if(!d)return{success:!1,error:"Dynamic client registration failed at "+a};const m={authorizationUrl:s,tokenUrl:i,clientId:d.clientId,clientSecret:d.clientSecret,scopes:l},g=await performOAuthFlow(e,t,m,{onStatus:n});return g.success&&(await storeDiscoveredClient(e,{authorizationUrl:s,tokenUrl:i,clientId:d.clientId,scopes:l}),d.clientSecret?await storeClientSecret(e,d.clientSecret):await deleteClientSecret(e)),g}Ot(),Ot(),TS(),wS(),PS(),_S(),IS(),US(),BS(),zS(),Ot(),BS(),zS(),CS(),jS(),Ot(),RS(),wS(),Kn(),__name(buildOAuthMetadataUrl,"buildOAuthMetadataUrl"),__name(buildOidcMetadataUrl,"buildOidcMetadataUrl"),__name(tryFetchAsMetadata,"tryFetchAsMetadata"),__name(discoverOAuthMetadataFromIssuer,"discoverOAuthMetadataFromIssuer"),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(parseResourceMetadataUrl,"parseResourceMetadataUrl"),__name(fetchProtectedResourceMetadata,"fetchProtectedResourceMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),Ot(),wS(),jS(),CS(),__name(discoverAndAuthenticate,"discoverAndAuthenticate"),Rr(),Xr();var _A=__name(({onClose:e})=>{const[t,n]=Y([]),[r,o]=Y(!0),[s,i]=Y(0),[a,l]=Y("list"),[u,d]=Y(null),m=ee(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!1===e.config.enabled?s="disabled":n&&"connected"===n.status?(s="connected",r=n.tools.length):n&&"error"===n.status?(s="error",o=n.error):(e.config.oauth||"http"===e.config.transport)&&(await hasTokens(e.name)?s="authenticated":e.config.oauth&&(s="requires_auth")),{name:e.name,config:e.config,scope:e.scope,status:s,toolCount:r,error:o}}));n(r)}catch{}finally{o(!1)}},[]);X(()=>{m()},[m]);const g=Z(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),h=g[s]??null;se((t,n)=>{if(n.ctrl&&"c"===t)e();else if(n.escape)"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e();else if("list"===a){if(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow){if(0===g.length)return;const e=Math.max(0,g.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&h&&(l("actions"),d(null))}});const f=__name(e=>{switch(e){case"connected":return Q.createElement(ne,{color:ar.GREEN},Pe.tick);case"authenticated":return Q.createElement(ne,{color:ar.CYAN},Pe.tick);case"requires_auth":return Q.createElement(ne,{color:ar.YELLOW},Pe.warning);case"error":return Q.createElement(ne,{color:ar.RED},Pe.cross);default:return Q.createElement(ne,{color:ar.GRAY},Pe.circle)}},"getStatusIcon"),y=__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";case"disabled":return"disabled";default:return"not connected"}},"getStatusText"),w=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),S=__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(h)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)if("remove"!==e.value)if("disable"!==e.value)if("enable"!==e.value);else{d({text:`Enabling ${h.name}...`,color:ar.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:h.name,enabled:!0,scope:h.scope}))return void d({text:`${Pe.cross} Failed to enable ${h.name}, server may no longer exist in ${h.scope} scope`,color:ar.YELLOW});await m(),d({text:`${Pe.tick} Enabled ${h.name}`,color:ar.GREEN})}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else{d({text:`Disabling ${h.name}...`,color:ar.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:h.name,enabled:!1,scope:h.scope}))return void d({text:`${Pe.cross} Failed to disable ${h.name}, server may no longer exist in ${h.scope} scope`,color:ar.YELLOW});await e.disconnectServer(h.name),await m(),d({text:`${Pe.tick} Disabled ${h.name}`,color:ar.GREEN})}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else l("confirm-remove");else{if(!(h.config.oauth||"http"===h.config.transport&&h.config.url))return void d({text:"Authentication requires an http server with a url",color:ar.YELLOW});d({text:`Authenticating ${h.name}...`,color:ar.CYAN,loading:!0});try{let e;if(h.config.oauth){const t={authorizationUrl:h.config.oauth.authorizationUrl,tokenUrl:h.config.oauth.tokenUrl,clientId:h.config.oauth.clientId,clientSecret:h.config.oauth.clientSecret,scopes:h.config.oauth.scopes};e=await performOAuthFlow(h.name,h.config.url??"",t,{onStatus:__name(()=>{},"onStatus")})}else e=await discoverAndAuthenticate({serverName:h.name,serverUrl:h.config.url});if(e.success){d({text:`${Pe.tick} Authenticated with ${h.name}`,color:ar.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name)}catch{}await m()}else d({text:`${Pe.cross} Auth failed: ${e.error}`,color:ar.RED})}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else{d({text:`Connecting ${h.name}...`,color:ar.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name),d({text:`${Pe.tick} Connected to ${h.name}`,color:ar.GREEN}),await m()}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED})}}else d({text:"Already authenticated",color:ar.GREEN});else d({text:"Already connected",color:ar.GREEN});else l("list")},"handleActionSelect"),C=__name(async e=>{if(h)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===h.status&&await e.disconnectServer(h.name),await removeMcpServer({name:h.name,scope:h.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,g.length-2)))}catch(e){d({text:`${Pe.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:ar.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Manage MCP servers"),Q.createElement(ne,{color:ar.DIM},"Loading..."));if("confirm-remove"===a&&h)return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:ar.RED,bold:!0},"Remove ",h.name,"?"),Q.createElement(ne,{color:ar.DIM},"This will remove the server from ",h.scope," config."),Q.createElement(te,{marginTop:1},Q.createElement(mt,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:C,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY}," ",t)})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&h){const e=[],t="disabled"===h.status,n="connected"===h.status,r="authenticated"===h.status||n;t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"});const o=!t&&(h.config.oauth||"http"===h.config.transport);return o&&r&&e.push({label:"Authenticated",value:"authenticated"}),o&&!r&&e.push({label:"Authenticate",value:"auth"}),t||e.push({label:"Disable",value:"disable"}),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},h.name),Q.createElement(te,null,f(h.status),Q.createElement(ne,{color:ar.DIM}," ",y(h))),Q.createElement(te,{marginTop:1},Q.createElement(mt,{items:e,onSelect:E,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:ar.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.WHITE:ar.GRAY}," ",t)})),u&&Q.createElement(te,{marginTop:1},u.loading&&Q.createElement(ne,{color:u.color},Q.createElement(je,{type:"dots"})," "),Q.createElement(ne,{color:u.color},u.text)),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let v=null;return Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:lr,bold:!0},"Manage MCP servers"),Q.createElement(ne,{color:ar.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,{color:ar.DIM},"No MCP servers configured."),Q.createElement(ne,{color:ar.DIM},'Use "cmd mcp add" to add a server.'),Q.createElement(Kr,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:ar.CYAN,dimColor:!0})):Q.createElement(te,{marginTop:1,flexDirection:"column"},g.map((e,t)=>{const n=e.scope!==v;v=e.scope;const r=t===s;return Q.createElement(Q.Fragment,{key:e.name},n&&Q.createElement(te,{marginTop:0===t?0:1},Q.createElement(ne,{bold:!0},w(e.scope)),Q.createElement(ne,{color:ar.DIM}," (",S(e.scope),")")),Q.createElement(te,{paddingLeft:1},Q.createElement(ne,{color:r?ar.WHITE:ar.GRAY},r?"› ":" "),Q.createElement(ne,{color:r?ar.WHITE:void 0,bold:r},e.name),Q.createElement(ne,{color:ar.DIM}," · "),f(e.status),Q.createElement(ne,{color:"connected"===e.status?ar.GREEN:"authenticated"===e.status?ar.CYAN:"requires_auth"===e.status?ar.YELLOW:ar.GRAY}," ",y(e))))})),u&&Q.createElement(te,{marginTop:1},u.loading&&Q.createElement(ne,{color:u.color},Q.createElement(je,{type:"dots"})," "),Q.createElement(ne,{color:u.color},u.text)),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},0===t.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ot(),wn(),Hn(),Rr();var xA=__name(({onClose:e})=>{const[t,n]=Y([]),[r,o]=Y(0),[s,i]=Y(!0),[a,l]=Y(null);X(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(se((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(te,{paddingLeft:1,paddingTop:1},Q.createElement(ne,{color:ar.DIM},"Loading memory files..."));if(a)return Q.createElement(te,{paddingLeft:1,paddingTop:1},Q.createElement(ne,{color:ar.RED},Pe.cross," ",a));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(te,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:ar.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},Q.createElement(te,null,Q.createElement(ne,{color:ar.WHITE,bold:!0},"Select memory to edit:")),Q.createElement(te,{columnGap:4,marginTop:1},Q.createElement(te,{flexDirection:"column"},m.map((e,t)=>Q.createElement(ne,{key:t,color:r===t?ar.WHITE:ar.DIM},r===t?`${Dn} `:" ",e.label))),Q.createElement(te,{flexDirection:"column"},m.map((e,t)=>Q.createElement(ne,{key:t,color:r===t?ar.WHITE:ar.DIM},e.description)))))},"MemorySelector");function AutoCompactMessage({content:e}){return Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.DIM},Pe.bullet," ",e))}function TasteSkipMessage(){return Q.createElement(te,{marginTop:1,marginBottom:1},Q.createElement(te,{flexShrink:0},Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG,bold:!0},CT)),Q.createElement(ne,{color:ar.DIM}," Skipped. Run "),Q.createElement(ne,{color:Tr.CODE},"/learn-taste"),Q.createElement(ne,{color:ar.DIM}," or "),Q.createElement(ne,{color:Tr.CODE},"cmd learn-taste"),Q.createElement(ne,{color:ar.DIM}," anytime."))}function HookWarningMessage({content:e}){return Q.createElement(te,null,Q.createElement(ne,{color:ar.YELLOW},Pe.warning),Q.createElement(te,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.YELLOW},e)))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?Q.createElement(TasteSkipMessage,null):t?.isAutoCompact?Q.createElement(AutoCompactMessage,{content:e}):t?.isHookWarning?Q.createElement(HookWarningMessage,{content:e}):Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:ar.DIM},Pe.bullet," ",e))}Ot(),Rr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(InfoMessage,"InfoMessage"),Ot(),wn(),Qr(),xE(),Co(),io(),Rr(),Ot(),Rr();var AA=yt()?"⠶":"#";function AssistantMessage({content:e}){return Q.createElement(te,null,Q.createElement(ne,{color:Er},AA),Q.createElement(te,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=ar.GREEN,s=Pe.tick,i="default",a=t||"(No output)";n&&(o=ar.YELLOW,s=Pe.arrowRight,i=ar.YELLOW,a="Executing…"),r&&(o=ar.RED,s=Pe.cross,i=ar.RED);const l=Z(()=>buildTreeConnectors(a),[a]);return Q.createElement(te,null,Q.createElement(ne,{color:o},s),Q.createElement(te,{flexDirection:"column",marginLeft:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.GRAY},"$ "),Q.createElement(ne,{color:o,bold:!0},e)),Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,{color:Ar},l),Q.createElement(ne,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?ar.YELLOW:void 0,o=Z(()=>buildTreeConnectors(e),[e]);return Q.createElement(te,{flexDirection:"column",marginBottom:0,marginTop:-1},Q.createElement(te,{columnGap:1},Q.createElement(ne,{color:Ar},o),Q.createElement(te,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(ne,{color:r},e))),t&&Q.createElement(te,{marginLeft:3},Q.createElement(ne,{color:ar.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return Q.createElement(te,null,Q.createElement(ne,{color:ar.RED},t?Pe.pointer:Pe.warning),Q.createElement(te,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?Q.createElement(ne,{color:ar.RED,wrap:"wrap"},e):Q.createElement(Markdown,{color:ar.RED},e)))}__name(AssistantMessage,"AssistantMessage"),Ot(),Rr(),__name(BashMessage,"BashMessage"),Ot(),Rr(),__name(CommandResultMessage,"CommandResultMessage"),Ot(),Rr(),__name(ErrorMessage,"ErrorMessage"),Ot(),Rr();var PA={connected:{char:Pe.tick,color:ar.GREEN},installed:{char:Pe.tick,color:ar.GREEN},up_to_date:{char:Pe.tick,color:ar.GREEN},needs_reload:{char:Pe.circle,color:ar.YELLOW},failed:{char:Pe.cross,color:ar.RED},not_in_ide:{char:Pe.circle,color:ar.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getStatusHeadline(e,t),i=PA[e];return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,null,Q.createElement(ne,{color:i.color},i.char),Q.createElement(ne,null," ",r),o&&Q.createElement(ne,{color:ar.CYAN},o),s&&Q.createElement(ne,null,s))),n?.map((e,t)=>Q.createElement(ne,{key:t,color:ar.DIM}," ",e)))}__name(IDEStatusMessage,"IDEStatusMessage"),Ot(),Ot(),wn();function HelpMessage(){const e=getInvokedCommandName(),t=Z(()=>Bv.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return Q.createElement(te,{flexDirection:"column",paddingY:1},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Command Code"),Q.createElement(ne,{color:ar.GRAY}," v","0.26.7")),Q.createElement(ne,{color:ar.GRAY},Ov)),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Usage"),Q.createElement(te,{paddingLeft:2},Q.createElement(ne,null,e," <command> [options]"))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Options"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},Uv.map(t=>Q.createElement(te,{key:t.key},Q.createElement(ne,null,t.key.replace(/^cmd/,e).padEnd(Fv)),Q.createElement(ne,{color:ar.GRAY},t.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Commands"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},zv.map(t=>Q.createElement(te,{key:t.key},Q.createElement(ne,null,t.key.replace(/^cmd/,e).padEnd(Fv)),Q.createElement(ne,{color:ar.GRAY},t.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Slash Commands"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},t.map(e=>Q.createElement(te,{key:e.key},Q.createElement(ne,null,e.key.padEnd(Fv)),Q.createElement(ne,{color:ar.GRAY},e.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Keyboard Shortcuts"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},jv.map(e=>Q.createElement(te,{key:e.key},Q.createElement(ne,null,e.key.padEnd(Fv)),Q.createElement(ne,{color:ar.GRAY},e.description))))),Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ne,{bold:!0},"Examples"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},Wv.map(t=>Q.createElement(te,{key:t.key},Q.createElement(ne,null,t.key.replace(/^cmd/,e).padEnd(Fv)),Q.createElement(ne,{color:ar.GRAY},t.description))))),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.CYAN},Pe.pointer),Q.createElement(ne,{color:ar.GRAY}," ",Gv.replace(/cmd/,e))),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{bold:!0},"Links"),Q.createElement(te,{flexDirection:"column",paddingLeft:2},Hv.map(e=>Q.createElement(te,{key:e.key},Q.createElement(ne,null,e.key.padEnd(Fv)),Q.createElement(ne,{color:ar.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?Q.createElement(HelpMessage,null):Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{wrap:"wrap"},Q.createElement(Markdown,null,e)))}Rr(),$S(),io(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ot(),Hn(),ro(),Rr();var IA={"Interrupted by user":"Interrupted by user","Insufficient credits":Ln};function UserMessage({content:e,images:t,imageCount:n=0,ideHint:r}){const o="Interrupted by user"===e,s="Insufficient credits"===e,i=e.startsWith("Error:"),a=o||s||i,l=a&&IA[e]||e,u=null!=t?t.length:n,d=J(null);null===d.current&&t&&t.length>0&&(d.current=t.map((e,t)=>saveTempImage(e,t+1)));const m=d.current??[];return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{backgroundColor:a?void 0:Sr.BG,paddingRight:1},Q.createElement(ne,{color:a?ar.RED:Sr.POINTER,bold:!a},Pe.pointer),Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:a?ar.RED:ar.WHITE,wrap:"wrap"},l))),u>0&&Q.createElement(te,{marginLeft:1},Q.createElement(ne,{color:ar.DIM},"⎿"," ",Array.from({length:u},(e,t)=>{const n=m[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))),r&&!a&&Q.createElement(te,{marginLeft:2},Q.createElement(ne,{color:Ar},ST),Q.createElement(ne,{color:ar.DIM}," ","Selected ",r.lines," ",1===r.lines?"line":"lines"," from ",r.file," in ",r.ide)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0,n=e.metadata?.ideHint;return Q.createElement(UserMessage,{content:e.input,images:t,ideHint:n})}return"assistant"===e.role?Q.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?Q.createElement(ToolMessage,{name:EE(e.name||""),input:e.input,output:e.output||"",isPending:yE(e),hasError:fE(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?Q.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:yE(e),hasError:fE(e)}):"system"===e.role?Q.createElement(SystemMessage,{content:e.input}):"info"===e.role?Q.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?Q.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?Q.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?Q.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=findModelById(e);return t?t.name.toLowerCase().replaceAll(" ","-"):e}function getProviderShortName(e){return e?dn[e]?.shortLabel??e.slice(0,4):""}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [ctrl+e to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:wr},o),Q.createElement(BracketedText,{text:n,color:wr}),Q.createElement(ne,{color:wr},o))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(getProviderShortName,"getProviderShortName"),__name(TranscriptDivider,"TranscriptDivider");var NA=Q.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentProvider:s,hiddenCount:i=0})=>{const a=i>0?{role:"transcript-divider",count:i}:null,l=[...t?["header"]:[],...a?[a]:[],...e],u=useTerminalWidth(),d=Z(()=>tx(u),[u]),m=Z(()=>ix(u),[u]),g=Z(()=>getPackageJson().version||"0.0.0",[]),h=Z(()=>getGitHeaderInfo(),[]),f=Z(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?getModelShortName(o):"sonnet-4.6",w="taste-1",S=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO,E=S?" · co":"",C=S&&s?` · ${getProviderShortName(s)}`:"";return Q.createElement(re,{items:l,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return Q.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:u});if("header"===e)return"compact"===m?Q.createElement(te,{key:"header",marginBottom:1,flexDirection:"row"},Q.createElement(te,{width:ox,flexShrink:0},Q.createElement(ax,null,rx)),Q.createElement(te,{flexDirection:"column",marginLeft:2},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Command Code"),Q.createElement(ne,{color:wr}," ","v",g)),Q.createElement(ne,{color:wr},"models: ",y," · ",w,E),Q.createElement(ne,{color:wr},f,h&&h.isLocal&&h.branch&&` (${h.branch})`))):Q.createElement(te,{key:"header",marginBottom:1,flexDirection:"column"},Q.createElement(ax,null,d.trimEnd()),Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(te,null,Q.createElement(ne,{color:wr},"# "),Q.createElement(ne,{bold:!0},"Command Code"),Q.createElement(ne,{color:wr}," v",g)),Q.createElement(ne,{color:wr},"# models: ",y," · ",w,C,E),Q.createElement(te,null,Q.createElement(ne,{color:wr},"# ",f,h&&h.isLocal&&h.branch&&Q.createElement(ne,{color:wr}," ","(branch:"," ",h.branch,")")))));const t=e,n=renderFeedEntry(t,r);return Q.createElement(te,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ot(),xE(),ao(),Rr();var RA=K(__name(function LiveAgentStatusInner2({entry:e}){const t=EE(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,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=Y(".");return X(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),Q.createElement(te,{flexDirection:"column",marginBottom:1,width:"90%"},Q.createElement(te,null,Q.createElement(ne,{backgroundColor:hr.BG,color:hr.FG,bold:!0},` ${t} `),o&&Q.createElement(ne,null," ","(",o,")")),Q.createElement(te,{columnGap:1,marginLeft:1},Q.createElement(ne,null,"⎿"," "),Q.createElement(ne,{color:ar.GRAY},"Running (",formatTime2(i)," | ",formatTokens(s),")",l)),a.length>0&&Q.createElement(te,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=EE(e.name);return Q.createElement(te,{key:t,columnGap:1},Q.createElement(ne,{color:ar.GRAY},"⎿"),Q.createElement(ne,{color:ar.GRAY}," ",n),e.input&&Q.createElement(ne,{color:ar.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),MA=K(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:Q.createElement(RA,{entry:e})},"LiveAgentStatus"));Ot(),wn(),Qr(),Jr(),ao(),io(),Ot(),wn(),Rr();var LA=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o})=>{const s=dn[t],i=o??s?.showProviderLabelInSelector??!1,a=un[e.provider],l=e.id===cn?`${e.label} (default)`:e.label;return Q.createElement(te,null,Q.createElement(ne,{color:n?ar.CYAN:ar.GRAY},n?`${Pe.pointer} `:" "),Q.createElement(ne,{color:n?ar.CYAN:r?ar.GREEN:ar.WHITE},l.padEnd(32)),i&&Q.createElement(ne,{color:ar.DIM},a),e.description&&Q.createElement(ne,{color:ar.DIM},i?" · ":"",e.description),r&&Q.createElement(ne,{color:ar.GREEN}," ",Pe.tick))},"ModelRow");function checkModelAccess({model:e,planId:t,purchasedCredits:n,freeCredits:r}){if(n>0||r>0)return{allowed:!0};if(!t)return{allowed:!0};const o=Xt[t];if(!o)return{allowed:!0};const s=getModelCategory({provider:e.provider,model:e.id});if(!s)return{allowed:!0};const i=`${e.provider}:${e.id}`;if(!o.allowedCategories.includes(s)){const t=getMinimumPlanForModel({fullModelId:i,category:s}),n=t?getPlanDisplayName(t):"Ultra";return{allowed:!1,errorMessage:`${e.name} available in ${n} and above plans or extra on demand usage\nRun /upgrade to check plans or /extra to buy on-demand credits`}}if(o.blockedModels?.includes(i)){const t=getMinimumPlanForModel({fullModelId:i,category:s}),n=t?getPlanDisplayName(t):"Ultra";return{allowed:!1,errorMessage:`${e.name} available in ${n} and above plans or extra on demand usage\nRun /upgrade to check plans or /extra to buy on-demand credits`}}return{allowed:!0}}Rr(),Ot(),wn(),__name(checkModelAccess,"checkModelAccess");var $A="Loading plan info…",DA=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function effortGlyph(e){return"low"===e?"▁▁":"medium"===e?"▃▃":"high"===e?"▆▆":"xhigh"===e?"██":"max"===e?"▣▣":"░░"}function searchGroups(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,DA);e.length>0&&n.push({...r,models:e})}return n}function flattenGroups(e){const t=[];for(const n of e)for(const e of n.models)t.push({providerId:n.providerId,model:e});return t}function groupByModelProvider(e,t){const n=new Map;for(const t of e){const e=un[t.provider]??t.provider,r=n.get(e)??[];r.push(t),n.set(e,r)}const r=[];for(const e of Object.values(un))n.has(e)&&!r.includes(e)&&r.push(e);return r.map(e=>({providerId:t,label:e,models:n.get(e)}))}__name(effortGlyph,"effortGlyph"),__name(searchGroups,"searchGroups"),__name(flattenGroups,"flattenGroups"),__name(groupByModelProvider,"groupByModelProvider");var OA=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0})=>{const[a,l]=Y(""),[u,d]=Y(null),[m,g]=Y(()=>new Set),h=Z(()=>isInternalTeamFlagEnforced(),[]),f=Z(()=>h?mn:groupByModelProvider(pn.flatMap(e=>e.models),dn["command-code"].id),[h]),y=Z(()=>searchGroups(f,a),[f,a]),w=Z(()=>flattenGroups(y),[y]),S=Z(()=>flattenGroups(f),[f]),E=void 0!==o,C=Z(()=>E?null:getCachedBillingContext(),[E]),[v,k]=Y(C),[T,_]=Y(!E&&!C);X(()=>{if(E)return;if(v)return;let e=!0;return getBillingContext().then(t=>{e&&(k(t),_(!1))}),()=>{e=!1}},[E,v]);const x=!E&&!0===v?.fetchFailed,A=E?o:v?.planId??null,P=E?s:v?.purchasedCredits??0,I=E?i:v?.freeCredits??0,N=h?dn.anthropic.id:dn["command-code"].id,R=r??N,M=n?Math.max(0,w.findIndex(e=>e.model.id===n&&e.providerId===R)):0,{cursor:L,error:$,setError:D}=useListNavigation({items:w,onSelect:__name(t=>e(t.model.id,t.providerId),"onSelect"),onCancel:t,initialIndex:M,searchQuery:a,onSearchChange:l,validate:__name(e=>{if(m.has(e.providerId))return`Run /provider to authenticate with ${getProviderConfig(e.providerId)?.displayName??e.providerId} first`;if(u&&!h){const t=dn[u]?.supportedModelProviders;if(t&&!t.includes(e.model.provider))return`${dn[u]?.label??u} does not support ${e.model.provider} models. Switch provider via /provider.`}if(T)return $A;const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:A,purchasedCredits:P,freeCredits:I});return t.allowed?null:t.errorMessage??"Model not available for your plan"},"validate")}),[O,F]=Y(()=>{const e={};for(const t of S)getSupportedEfforts(t.model.id)&&(e[t.model.id]=getReasoningEffort(t.model.id));return e});X(()=>{F(e=>{const t={...e};for(const e of S)getSupportedEfforts(e.model.id)&&(e.model.id in t||(t[e.model.id]=getReasoningEffort(e.model.id)));return t})},[S]);const q=__name((e,t)=>{const n=getSupportedEfforts(e);if(!n||0===n.length)return;const r=[void 0,...n],o=O[e],s=r.indexOf(o),i=r[((-1===s?0:s)+t+r.length)%r.length];F(t=>({...t,[e]:i})),setReasoningEffort({modelId:e,effort:i})},"cycleEffort");se((e,t)=>{if(!t.leftArrow&&!t.rightArrow)return;const n=w[L];n&&getSupportedEfforts(n.model.id)&&q(n.model.id,t.rightArrow?1:-1)}),X(()=>{if(T)return;if($!==$A)return;const e=w[L];if(!e||x)return void D(null);const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:A,purchasedCredits:P,freeCredits:I});D(t.allowed?null:t.errorMessage??"Model not available for your plan")},[T,x,$,D,w,L,A,P,I]),X(()=>{(async()=>{await isOAuthEnforced()&&d(await getConfiguredProvider())})()},[]),X(()=>{(async()=>{const e=new Set(f.map(e=>e.providerId)),t=new Set;for(const n of e){const e=getProviderConfig(n);e?.requiresAuth&&e.checkAuth&&(await e.checkAuth()||t.add(n))}g(t)})()},[f]);let j=0;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,null,Q.createElement(ne,{color:lr,bold:!0},"Select model")),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{dimColor:!0},h?"Select a model and provider. Applies to this session and future sessions.":"Switch between Command Code models. Applies to this session and future sessions.")),Q.createElement(te,{marginBottom:2,flexDirection:"column",width:"100%"},Q.createElement(px,{query:a,resultCount:a?w.length:void 0,placeholder:"Type to search models..."})),0===w.length?Q.createElement(te,{marginY:1},Q.createElement(ne,{color:ar.GRAY},'No models match "',a,'"')):Q.createElement(te,{flexDirection:"column"},y.map((e,t)=>{const r=j;return j+=e.models.length,Q.createElement(te,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:t>0?1:0},h?Q.createElement(ne,{bold:!0,color:lr},e.label):Q.createElement(ne,{bold:!0,dimColor:!0},e.label),e.models.map((t,o)=>Q.createElement(LA,{key:`${e.providerId}-${e.label}-${t.id}`,model:t,providerId:e.providerId,isHighlighted:r+o===L,isCurrent:t.id===n&&e.providerId===R,showProviderLabel:!!h&&void 0})))})),$&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.GRAY},$)),(()=>{const e=w[L];if(!e)return null;const t=getSupportedEfforts(e.model.id);if(!t||0===t.length)return null;const n=O[e.model.id],r=effortGlyph(n),o=n??"auto";return Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0,color:ar.CYAN},r),Q.createElement(ne,{bold:!0},` ${o} effort`),Q.createElement(ne,{dimColor:!0}," [←/→ adjust]"),void 0===n&&Q.createElement(ne,{dimColor:!0}," [provider default]"))})(),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"type to search . up/down navigate . Enter to select"),a?Q.createElement(ne,{color:ar.DIM}," . Esc to clear"):Q.createElement(ne,{color:ar.DIM}," . Esc to cancel")))},"ModelSelector");Ot(),io(),Rr();var FA=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");se((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,i=n&&-1===s;return Q.createElement(te,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},Q.createElement(te,null,Q.createElement(ne,{bold:!0},"Select AI Provider")),n&&Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:ar.DIM},"Current: "),Q.createElement(ne,{color:ar.GREEN},getProviderDisplayName(n)),i&&Q.createElement(ne,{color:ar.YELLOW}," [OAuth enforced]"))),Q.createElement(te,{marginBottom:0},Q.createElement(ne,{color:ar.DIM},"Available Providers:")),Q.createElement(mt,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>Q.createElement(ne,{color:e?ar.CYAN:ar.GRAY,bold:e},e?Pe.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(ne,{color:e?ar.CYAN:ar.GRAY,bold:e},` ${t}`)}),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=Y(0);if(X(()=>{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(te,{marginBottom:1},Q.createElement(ne,{color:kr,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ot(),Rr(),__name(RetryMessage,"RetryMessage"),Ot(),as(),Hn(),Rr();var qA=[{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"}],jA=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=Z(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=Y(Math.max(0,r.length-1)),[i,a]=Y(Math.max(0,r.length-8)),[l,u]=Y("checkpoint"),[d,m]=Y(null),[g,h]=Y(0),f=Z(()=>{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]),y=Z(()=>f?qA:qA.filter(e=>"conversation"===e.mode),[f]);if(X(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),se((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[o]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:lr,bold:!0},"Rewind"),Q.createElement(ne,{color:ar.DIM},"No checkpoints available. Start a conversation to create checkpoints."),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to close")));if("mode"===l&&d)return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:lr,bold:!0},"Rewind"),Q.createElement(te,{marginBottom:1},Q.createElement(ne,{color:ar.DIM},"Restore to: "),Q.createElement(ne,{color:ar.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),Q.createElement(te,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return Q.createElement(te,{key:e.mode,flexDirection:"column"},Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:n?lr:void 0},n?`${Dn} `:" "),Q.createElement(te,{flexDirection:"column"},Q.createElement(ne,{color:n?lr:ar.WHITE},e.label),Q.createElement(ne,{color:ar.DIM},e.description))),!r&&Q.createElement(ne,null," "))})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Enter"),Q.createElement(ne,{color:ar.DIM}," to confirm, "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to go back")));const w=r.slice(i,i+8);return Q.createElement(te,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(ne,{color:lr,bold:!0},"Rewind"),Q.createElement(ne,{color:ar.DIM},"Select a checkpoint to restore your session"),r.length>8&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),Q.createElement(te,{marginTop:1}),Q.createElement(te,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return Q.createElement(te,{key:e.messageId,flexDirection:"column"},Q.createElement(te,{flexDirection:"row"},Q.createElement(ne,{color:s?lr:void 0},s?`${Dn} `:" "),Q.createElement(te,{flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:s?lr:ar.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),Q.createElement(ne,{color:ar.DIM}," • "),Q.createElement(ne,{color:ar.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),Q.createElement(ne,{color:ar.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&Q.createElement(ne,null," "))})),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"Press "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Enter"),Q.createElement(ne,{color:ar.DIM}," to select, "),Q.createElement(ne,{color:ar.DIM,bold:!0},"Esc"),Q.createElement(ne,{color:ar.DIM}," to cancel")))},"RewindSelector");Ot(),Kn(),Ot(),Ot();var UA=__name(e=>{const[t,n]=Y(e),[r,o]=Y(null);return X(()=>{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 Yk.on("reset",t),Yk.on("new-event",r),()=>{Yk.off("reset",t),Yk.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new jw({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o,s;try{const e=await getOAuthCredentials({provider:n});o=e.token,s=e.oauthProvider,validateOAuthToken({token:o,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[Ut.PROJECT_SLUG]:ok.getCurrentProjectDirName(),[Ut.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(i[Ut.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Ut.OAUTH_PROVIDER]=s)),{request:t,headers:i}}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}Ot(),Ot(),sS(),fS(),Kn(),Ot(),wn(),Kn(),Ot(),Ot(),wn(),sS(),fS(),Kn(),Jr(),ao(),__name(createRequestClient,"createRequestClient"),Ot(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ot(),Ot(),Kn(),Lo(),Ot();var BA="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Produce ${t} varied observations for these prompts:\n\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}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}`),Yk.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()}`),Yk.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${Bt.ALPHA.GENERATE} with model: ${BA}`);const r={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:BA,system:"You scan prompts and produce casual observations like a dev friend glancing at someone's 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 per observation\n- one observation per line\n- sound human, not robotic\n- output only the observations, no preamble",max_tokens:200,temperature:.7,stream:!0},threadId:Ae()},o=await e.post({endpoint:Bt.ALPHA.GENERATE,body:r,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const s=createInsightEmitter();await consumeSSEStream(o,{onText:__name(e=>{s.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${s.getChunkCount()} chunks received`),s.emitRemaining(),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 i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(Yk.observerHasRun)return;Yk.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r={...n,[Ut.SESSION_ID]:`observer-${Ae()}`},o=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${o.length} batches`);const s=Math.min(o.length,6);for(let t=0;t<s;t++){if(Yk.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const n=o[t];try{await processBatch(e,r,n,t+1,o.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),Yk.addEvent({type:"progress",message:"Continuing without live observations..."})}}wn(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var zA=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(w.homedir(),".claude","projects");await v.access(r);const o=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await v.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await v.stat(s)).isDirectory())continue;const r=(await v.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),i=await v.stat(r),a=o.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{Yk.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Yk.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 findCursorSessions(e=0){try{Yk.addEvent({type:"progress",message:"Scanning Cursor sessions..."});const t=await findCursorSessions(process.cwd(),e);return dlog(`[Import] found ${t.length} Cursor sessions`),t}catch(e){return dlog("[Import] no cursor sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await v.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=[],o=[];try{Yk.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),i=s.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,o=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length},{name:"Cursor",count:n.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Yk.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${o.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&s.push({agent:"cursor",sessionIds:n.map(e=>e.id),displayName:"Cursor"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:r,learnedSessions:a+l+u,agentSessions:s,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));o.push(...e)}const y=n.length+r.length+o.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${o.length})`),Yk.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:o,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){Yk.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 S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Yk.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const s=getApiBaseUrl(),i=new jw({baseUrl:s});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&Yk.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),s=new Xk({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await s.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Yk.markLearningComplete(),await E,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`)}if(o.length>0){const e=o.map(e=>e.id);await markSessionsAsLearned("cursor",e),dlog(`[Import] marked ${e.length} cursor sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const l=await this.extractLearningSummary(),u=[];if(n.length>0&&u.push(`Claude Code (${n.length})`),r.length>0&&u.push(`Codex (${r.length})`),o.length>0&&u.push(`Cursor (${o.length})`),!a){const s=Yk.getEvents().some(e=>"error"===e.type&&e.message?.toLowerCase().includes("insufficient credits")),i="Learning failed - sessions not marked as learned";return e.push(i),s||Yk.addEvent({type:"error",message:i}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,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"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}return Yk.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,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"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),Yk.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 v.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")}},HA=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),WA=__name(e=>{const[t,n]=Y({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return X(()=>{Yk.reset(),Yk.markImportStarted(),(async()=>{try{const t=await Promise.race([zA.importAndLearn(),HA(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");Ot();var GA=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{se((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");Ot(),Kn();var VA=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=Y(null),[o,s]=Y(null),i=J(!1);return X(()=>{if(i.current)return;let n=null;return(async()=>{try{i.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),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{Yk.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{Yk.reset(),e()}}Ot(),Kn(),Ot(),Kn(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var QA=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=J(n),o=ee(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ee(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ee(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ee(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ee(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Ot(),Kn();var KA=__name(({conditions:e,autoLearn:t})=>{const[n,r]=Y("checking"),o=J(!1);return X(()=>{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]),X(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ot(),Ot(),Rr();var YA=__name(({error:e})=>Q.createElement(te,{padding:1},Q.createElement(te,{flexDirection:"column",borderColor:ar.RED,padding:1},Q.createElement(te,{marginBottom:1},Q.createElement(ne,null,"Error initializing onboarding: ",e)),Q.createElement(te,null,Q.createElement(ne,null,"Continuing without onboarding...")))),"OnboardingError");Ot(),Ot(),Rr();var JA=__name(()=>Q.createElement(ne,null,"Skip"),"SkipOptionText"),XA=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=Y(1);return se((e,t)=>{t.escape?r():"n"!==e&&"N"!==e?t.upArrow||t.downArrow?s(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===o?n():r()):r():n():dismissOnboardingForeverForProject().then(()=>r())}),Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:cr.TEXT,paddingX:1,paddingY:0},Q.createElement(ne,{color:cr.TEXT,bold:!0},"Build Your Coding Taste"),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(ne,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),Q.createElement(te,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,Q.createElement(ne,{color:1===o?cr.TEXT:ar.GRAY},1===o?Pe.pointer:" "," 1. Yes, learn (recommended)")),Q.createElement(te,null,Q.createElement(ne,{color:2===o?cr.TEXT:ar.GRAY},2===o?Pe.pointer:" "," 2."," ",Q.createElement(JA,null)))),Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"↑↓ · "),Q.createElement(ne,{color:Tr.CODE},"enter"),Q.createElement(ne,{color:ar.DIM}," ok · "),Q.createElement(ne,{color:Tr.CODE},"esc"),Q.createElement(ne,{color:ar.DIM}," skip · "),Q.createElement(ne,{color:Tr.CODE},"n"),Q.createElement(ne,{color:ar.DIM}," never")))},"ImportChoice");Ot(),Ot(),Rr();var ZA=__name(({error:e})=>Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.RED,paddingX:2,paddingY:1,marginBottom:2},Q.createElement(ne,{color:ar.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,e))),"ErrorSection");Ot(),Ot(),Rr(),Ot(),Ot(),Ot(),Rr(),Ot(),Rr();var eP=__name(()=>Q.createElement(ne,{backgroundColor:cr.BADGE_BG,color:cr.BADGE_FG},CT),"TasteBadge");Ot(),Rr(),Ot();var tP=["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"],nP="⎿",rP=__name(()=>{const[e,t]=Y(()=>Math.floor(Math.random()*tP.length));return X(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*tP.length))},2e3);return()=>clearInterval(e)},[]),Q.createElement(ne,{color:ar.YELLOW},tP[e],"...")},"PulsingText");Ot(),Rr();var oP=[Pe.bullet,Pe.squareSmallFilled,Pe.lozenge,Pe.star,Pe.triangleRight,Pe.triangleUp,Pe.circleFilled,Pe.pointer],sP=__name(e=>String(e).padStart(3," "),"padNum"),iP=__name(e=>oP[e%oP.length],"getSymbol"),aP=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${sP(t)} ↓${sP(n)} (↑↓ scroll)`,"buildStatusLine"),lP=__name(({insights:e})=>{const[t,n]=Y(0),[r,o]=Y(!0),s=e.length,i=s>10,a=Math.max(0,s-10);if(X(()=>{r&&i&&n(a)},[s,r,i,a]),se((e,t)=>{if(i)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&o(!0),t}))}),0===s)return null;const l=e.slice(t,t+10),u=t,d=s-t-10;return Q.createElement(te,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&Q.createElement(ne,{color:ar.DIM},aP(s,u,d,r)),l.map((e,n)=>{const r=t+n;return Q.createElement(te,{key:r,marginBottom:0},Q.createElement(ne,{color:ar.DIM},iP(r)," ",e))}))},"ScrollableInsights");Ot(),Rr();var cP=__name(()=>{const[e,t]=Y(!0);return X(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),Q.createElement(ne,{color:ar.YELLOW},e?Pe.circleFilled:Pe.circle)},"PulsingDot"),uP=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return Q.createElement(te,{flexDirection:"column",marginBottom:0},Q.createElement(eP,null),Q.createElement(te,{marginTop:0},Q.createElement(ne,{color:ar.DIM},nP),Q.createElement(te,{marginLeft:2},a?Q.createElement(ne,{color:cr.TEXT},"learned your coding taste"):Q.createElement(rP,null))));const u=__name(()=>r?Q.createElement(ne,{color:pr.BG},Pe.square):n?Q.createElement(cP,null):Q.createElement(ne,{color:ar.DIM},Pe.circle),"getStatusIcon"),d=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||d?Q.createElement(te,{flexDirection:"column",marginBottom:0},(n||r)&&Q.createElement(te,{marginBottom:0},Q.createElement(te,{marginRight:1},u()),Q.createElement(ne,{color:r?ar.WHITE:n?ar.YELLOW:ar.DIM},e)),r&&t&&(!l||0===l.learningCount)&&Q.createElement(te,{marginLeft:3,marginBottom:0},Q.createElement(ne,{color:ar.DIM},t)),o.length>0&&Q.createElement(te,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>Q.createElement(ne,{key:t,color:ar.DIM},`${Pe.bullet} ${e}`))),s.length>0&&Q.createElement(lP,{insights:s}),r&&l&&l.learningCount>0&&Q.createElement(te,{flexDirection:"column",marginLeft:1,marginBottom:0},Q.createElement(te,{marginBottom:1,flexDirection:"row"},Q.createElement(ne,null,nP),Q.createElement(te,{marginLeft:2},Q.createElement(ne,{color:cr.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),Q.createElement(te,{flexDirection:"column",marginLeft:1},Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," Stored in"," ",l.storage),Q.createElement(ne,{color:ar.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),dP=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return Q.createElement(te,{flexDirection:"column",marginBottom:1},e.map((e,n)=>Q.createElement(te,{key:e.id,marginLeft:0===n?0:3},Q.createElement(uP,{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"),mP=__name(({steps:e})=>Q.createElement(dP,{steps:e}),"ProgressSection");Ot(),Rr();var pP=__name(({isImporting:e=!1,waitingForInput:t=!1})=>Q.createElement(Q.Fragment,null,e&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"ESC to cancel")),t&&Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ot();var gP=[{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"}}],hP=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=UA(gP),{isImporting:s,waitingForInput:i,error:a}=WA(t);return GA({onEscape:__name(()=>{i&&((a||o)&&n?n():e())},"onEscape"),onEnter:__name(()=>{i&&((a||o)&&n?n():e())},"onEnter"),enabled:s||i}),Q.createElement(te,{flexDirection:"column",padding:1},o&&Q.createElement(ZA,{error:o}),!o&&Q.createElement(mP,{steps:r}),Q.createElement(pP,{isImporting:s,waitingForInput:i}))},"ImportProgress"),fP=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?Q.createElement(XA,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?Q.createElement(hP,{onComplete:r,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),yP=__name(({onComplete:e,autoLearn:t=!1})=>{X(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=VA({autoLearn:t,onShouldSkip:e}),{step:s,setStep:i}=KA({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=QA({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?Q.createElement(YA,{error:r}):"done"===s?null:Q.createElement(fP,{step:s,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const o=[];for(const e of n)if(o.unshift(e),r-=getEntryCharCount(e),r<=0)break;return o}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var wP=K(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,transcriptMode:s,tasteOnboardingEntryId:i,autoLearnTaste:a,showTasteSkipBanner:l,retryAttempt:u,input:d,setInput:m,fileSearchQuery:g,setFileSearchQuery:h,showFileList:f,setShowFileList:y,showProviderSelector:w,showModelSelector:S,showMemorySelector:E,showMcpManager:C,showAgentsConfig:v,showRewindSelector:k,showLoginOverlay:T,showUsageOverlay:_,showAddDirModal:x,showCompactModeSelector:A,authComponentInfo:P,status:I,currentProvider:N,currentModel:R,showProviderNotification:M,shareInfo:L,showShareNotification:$,unshareNotificationMessage:D,updateStatus:O,updateFailedInfo:F,creditWarning:q,permissionMode:j,hintMessage:U,pendingExitKey:B,tasteLearningEnabled:z,interactionTokens:H,contextUsage:W,historyManagerRef:G,executionState:V,contextEngineRef:K,onSubmit:Y,onCommand:J,onToggleAutoAccept:X,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,onTasteOnboardingComplete:se,permissionPanel:ie,questionPanel:ae,onRewindSelect:le,onRewindCancel:ce,onLoginComplete:ue,onLoginCancel:de,setShowProviderSelector:me,setShowModelSelector:pe,setShowMemorySelector:ge,setShowMcpManager:he,setShowAgentsConfig:fe,setShowAddDirModal:ye,setShowUsageOverlay:we,handleProviderSelect:Se,handleProviderCancel:Ee,handleModelSelect:be,handleModelCancel:Ce,handleCompactModeSelect:ve,handleCompactModeCancel:ke,handleAuthSuccess:Te,handleAuthCancel:_e}){const xe=Z(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Ae=useTerminalWidth(),Pe=Z(()=>"off"===s?xe:getBudgetedFeed(xe,"limited"===s?15e3:5e4),[xe,s]),Ie=Z(()=>"off"===s?0:Math.max(0,xe.length-Pe.length),[xe.length,Pe.length,s]),Ne=Z(()=>0===Ie?Pe:Pe.filter(e=>"user"!==e.role),[Pe,Ie]),Re=ee(()=>fe(!1),[fe]),Me=ee(()=>ge(!1),[ge]),Le=ee(()=>he(!1),[he]),$e=ee(()=>ye(!1),[ye]),De=ee(()=>pe(!0),[pe]),Oe=!("off"!==s||ie||ae||w||S||P||E||C||v||k||T||_||x||A||i);return Q.createElement(te,{flexDirection:"column",width:"100%"},Q.createElement(NA,{staticKey:o,feed:Ne,showHeader:!0,expandedToolOutput:"off"!==s,currentModel:R,currentProvider:N,hiddenCount:Ie}),i&&Q.createElement(yP,{onComplete:se,autoLearn:a}),l&&Q.createElement(TasteSkipMessage,null),t.map(e=>e.metadata?.isAgent?Q.createElement(MA,{key:e.id,entry:e}):Q.createElement(te,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==s))),Q.createElement(RetryMessage,{attempt:u}),ae,ie,"off"!==s&&Q.createElement(te,{flexDirection:"column",marginTop:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},"─".repeat(Ae))),Q.createElement(te,{paddingRight:1},Q.createElement(ne,{backgroundColor:pr.BG,color:pr.FG,bold:!0},`${bT}DETAILED TRANSCRIPT${bT}`),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{bold:!0},"ctrl+o"),Q.createElement(ne,{color:ar.DIM}," to toggle"),Q.createElement(ne,{color:ar.DIM}," · "),Q.createElement(ne,{bold:!0},"ctrl+e"),Q.createElement(ne,{color:ar.DIM}," ","to"," ","limited"===s?"show all":"collapse"))),Oe&&Q.createElement(kA,{queuedMessages:n,isProcessing:r,executionState:V,status:I,input:d,setInput:m,onSubmit:Y,showFileList:f,setShowFileList:y,fileSearchQuery:g,setFileSearchQuery:h,onCommand:J,outputTokens:H,contextUsage:W,tasteLearning:z,shareInfo:L,showShareNotification:$,unshareNotificationMessage:D,updateStatus:O,updateFailedInfo:F,creditWarning:q,currentProvider:N,showProviderInfo:M,permissionMode:j,onToggleAutoAccept:X,hintMessage:U,historyManager:G.current,pendingExitKey:B,onResetPendingExitKey:re,onDoubleEscapeEmpty:oe,retryAttempt:u,onAltP:De}),w&&Q.createElement(te,{marginY:1},Q.createElement(FA,{onSelect:Se,onCancel:Ee,currentProvider:N})),S&&Q.createElement(te,{marginY:1},Q.createElement(OA,{onSelect:be,onCancel:Ce,currentModel:R,currentProvider:N})),A&&Q.createElement(te,{marginY:1},Q.createElement(Kx,{onSelect:ve,onCancel:ke})),v&&Q.createElement(te,{marginY:1},Q.createElement(Vx,{onCancel:Re})),E&&Q.createElement(te,{marginY:1},Q.createElement(xA,{onClose:Me})),C&&Q.createElement(te,{marginY:1},Q.createElement(_A,{onClose:Le})),k&&K.current&&Q.createElement(te,{marginY:1},Q.createElement(jA,{checkpoints:K.current.listCheckpoints(),onSelect:le,onCancel:ce})),P&&Q.createElement(te,{marginY:1},Q.createElement(P.Component,{onSuccess:Te,onCancel:_e})),T&&Q.createElement(te,{marginY:1},Q.createElement(TA,{onComplete:ue,onCancel:de})),x&&Q.createElement(te,{marginY:1},Q.createElement(Nx,{onClose:$e})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:C,creditWarning:v,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:A,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return Q.createElement($_,{staticKey:o.staticKey,onTrust:k,onExit:T});if(o.showSessionSelector)return Q.createElement(O_,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!s.projectTrusted)return null;const I=a.pendingQuestion?Q.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,N=a.pendingPermission?Q.createElement(Q_,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null;return o.showLearningFeed?Q.createElement(LearningView,{setShowLearningFeed:o.setShowLearningFeed,setStaticKey:o.setStaticKey,onExit:()=>i.setShouldExit(!0)}):o.showTasteConfig?Q.createElement(TasteConfigView,{staticKey:o.staticKey,setShowTasteConfig:o.setShowTasteConfig,loadTasteStatus:P}):o.showSkillsConfig?Q.createElement(SkillsConfigView,{staticKey:o.staticKey,setShowSkillsConfig:o.setShowSkillsConfig}):o.showUsageOverlay?Q.createElement(UsageView,{staticKey:o.staticKey,setShowUsageOverlay:o.setShowUsageOverlay}):o.showContextView?Q.createElement(ContextConfigView,{staticKey:o.staticKey,contextEngineRef:u,setShowContextView:o.setShowContextView,setInput:w}):o.showStatusView?Q.createElement(StatusConfigView,{staticKey:o.staticKey,setShowStatusView:o.setShowStatusView,setInput:w}):Q.createElement(wP,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:o.staticKey,transcriptMode:o.transcriptMode,tasteOnboardingEntryId:s.tasteOnboardingEntryId,autoLearnTaste:s.autoLearnTaste,showTasteSkipBanner:o.showTasteSkipBanner,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:o.showFileList,setShowFileList:o.setShowFileList,showProviderSelector:o.showProviderSelector,showModelSelector:o.showModelSelector,showMemorySelector:o.showMemorySelector,showMcpManager:o.showMcpManager,showAgentsConfig:o.showAgentsConfig,showRewindSelector:o.showRewindSelector,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:C,creditWarning:v,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:A,permissionPanel:N,questionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel})}__name(renderView,"renderView");var SP=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u,sessionTitleHolder:d})=>{const{exit:m}=ae(),{stdout:g}=oe();X(()=>{prefetchBillingContext()},[]);const[h,f]=Y(""),[y,w]=Y(""),S=J(!1),E=J(!1),C=J(null),v=J(null),k=useUiOverlays(),T=useFeed(),_=useSession(),x=useStatus(s),A=useAuth(),P=usePendingOps(),I=useOnboarding(),N=useExit(),{executeBash:R,executionState:M}=Ok(),L=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:x.setStatus,contextEngineRef:v}),{createContextEngineCallbacks:$}=useContextEngine({sessionId:_.sessionId,sessionLoaded:_.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:I.projectTrusted,setFeed:T.setFeed,setLiveEntries:T.setLiveEntries,setQueuedMessages:T.setQueuedMessages,queuedMessagesRef:T.queuedMessagesRef,setStatus:x.setStatus,pinnedStatusRef:x.pinnedStatusRef,setRetryAttempt:x.setRetryAttempt,setInteractionTokens:x.setInteractionTokens,setContextUsage:x.setContextUsage,setCurrentProvider:A.setCurrentProvider,shareInfoRef:x.shareInfoRef,permissionsService:L.permissionsService,permissionModeRef:L.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:v}),{onCommand:D}=useCommandCtx({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:N,permissionState:L,contextEngineRef:v,isSubmittingRef:S,executeBash:R,createContextEngineCallbacks:$,setInput:f}),{loadTasteStatus:O,loadCurrentProvider:F,onSubmit:q}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:g,feedState:T,sessionState:_,statusState:x,authState:A,onboarding:I,uiOverlays:k,permissionState:L,contextEngineRef:v,isSubmittingRef:S,initialPromptSubmittedRef:E,historyManagerRef:C,executeBash:R,createContextEngineCallbacks:$,setInput:f,onCommand:D});useLifecycle({exit:m,feedState:T,exitState:N,statusState:x,authState:A,onboarding:I,uiOverlays:k,skipOnboarding:l,contextEngineRef:v,sessionTitleHolder:d});const{handleToggleAutoAccept:j,handleDoubleEscapeEmpty:U,handleTasteOnboardingComplete:B,handleTrust:z,handleNoTrust:H}=useHandlers({resume:e,feedState:T,onboarding:I,uiOverlays:k,exitState:N,pendingOps:P,permissionState:L,statusState:x,authState:A,contextEngineRef:v,loadTasteStatus:O,loadCurrentProvider:F,setInput:__name(e=>f(e),"setInput")}),W=useMainActionCallbacks({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,permissionState:L,contextEngineRef:v,createContextEngineCallbacks:$,setInput:f}),{creditWarning:G}=useCreditWarning({interactionTokens:x.interactionTokens});return renderView({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:N,pendingOps:P,permissionState:L,contextEngineRef:v,historyManagerRef:C,executionState:M,actionCallbacks:W,onSubmit:q,onCommand:D,input:h,setInput:f,fileSearchQuery:y,setFileSearchQuery:w,updateFailedInfo:i,creditWarning:G,handleTrust:z,handleNoTrust:H,handleToggleAutoAccept:j,handleDoubleEscapeEmpty:U,handleTasteOnboardingComplete:B,loadTasteStatus:O})},"InteractiveCLI");zr(),$S(),ir(),Rr();var EP=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),bP=ce.hex(ar.DIM),CP=__name(e=>{const t=getInvokedCommandName(),n=tt([e]);return`${bP("To continue this session, run:")}\n${bP(`${t} --resume ${n}`)}\n`},"formatResumeHint"),vP=__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"),kP=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),TP=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),_P=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{let r;return e.permissionMode?r=e.permissionMode:e.plan&&(r="plan"),{resume:"boolean"==typeof e.resume?e.resume:void 0,resumeSessionId:t,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:r,sessionTitleHolder:n}},"buildInteractiveCLIProps"),xP=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),AP=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),PP=__name(()=>{AP()},"initializeTerminal"),IP=__name(async(e={})=>{const t=vP(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),PP(),"string"==typeof e.resume){const t=e.resume;await ok.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await ok.findSessionByName(t);r||(console.error(`No session named "${t}" found.`),process.exit(1)),n=r.id}if(kP(e)&&!n){const e=await ok.isProjectInitialized(),t=e?await ok.listSessions():[],n=TP({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const r={},o=_P({options:e,resumeSessionId:n,sessionTitleHolder:r}),s=xP(),i=ie(Q.createElement(SP,{...o}),s);registerInkControl({clear:i.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await i.waitUntilExit();const a=await(r.loadTitle?.());if(a){const e=EP(a);e&&process.stdout.write(CP(e))}},"interactiveMode");Ao(),Ot(),wn(),yb(),nb();var NP=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${Pe.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${Pe.cross} Login failed: ${getErrorMessage2(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||NP()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated");var RP=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),MP=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),LP=__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"),$P=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:e.resume,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),DP=__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=DP(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:t.model,benchmarkOutput:t.benchmarkOutput})}const n=RP(e);await MP();const r=LP(t),o=$P({options:t,runtimeOptions:r,initialPrompt:n});await IP(o)}__name(interactiveModeAction,"interactiveModeAction"),Ot(),Kn(),hs(),Jr(),eb(),yb(),globalThis.COMMAND_CODE_CWD=process.cwd();var OP=__name(()=>process.cwd(),"getCwd"),FP=__name(()=>process.argv.slice(2),"getArgs"),qP=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),jP=__name(()=>{const e=OP(),t=FP(),n=qP(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){if(jP(),process.argv.includes("--ide-setup")){const e=await runIDESetup();formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}"update"!==FP()[0]&&await maybeRunPendingUpdate(),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100).unref()}__name(preRun,"preRun"),Ot(),wn(),Kn(),Co(),$S(),io();var UP=getPackageJson(),BP=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=UP.version,t=getInvokedCommandName(),n=Bv.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ce.bold("Command Code")+ce.gray(` v${e}`)),console.log(ce.gray(Ov)),console.log(),console.log(ce.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ce.bold("Options"));for(const e of Uv){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Fv)+ce.gray(e.description))}console.log(),console.log(ce.bold("Commands"));for(const e of zv){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Fv)+ce.gray(e.description))}console.log(),console.log(ce.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Fv)+ce.gray(e.description));console.log(),console.log(ce.bold("Keyboard Shortcuts"));for(const e of jv)console.log(" "+e.key.padEnd(Fv)+ce.gray(e.description));console.log(),console.log(ce.bold("Examples"));for(const e of Wv){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Fv)+ce.gray(e.description))}console.log(),console.log(ce.cyan("❯")+" "+ce.gray(Gv.replace(/cmd/,t))),console.log(),console.log(ce.bold("Links"));for(const e of Hv)console.log(" "+e.key.padEnd(Fv)+ce.cyan(e.description));console.log()}function createProgram(){const e=new Ie;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(UP.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by name, or 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)").addOption(new Ne("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ne("--yolo","Bypass all permission prompts (alias for --dangerously-skip-permissions)").implies({dangerouslySkipPermissions:!0})).option("--plan","Start in plan mode (read-only exploration and planning)").addOption(new Ne("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Ne("--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("--max-turns <number>","Maximum conversation turns in print mode (default: 10)",e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new Error("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--ide-setup",qv).option("--add-dir <directory>","Add directory to workspace context",BP,[]).addOption(new Ne("--model <model>","Override model for this run").hideHelp()).addOption(new Ne("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ne("--experimental","Enable experimental features").hideHelp()).addOption(new Ne(qt).hideHelp()).addOption(new Ne(jt).hideHelp()).addOption(new Ne("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ne("--local","Use local server").hideHelp()).addOption(new Ne("--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 i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ot(),hs(),Oo(),ME(),bb(),GE(),Co(),yb(),Ot(),__name(isTTY,"isTTY");var zP=!1;function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=w.platform(),t=w.arch();let n,r,o,s;try{const e=await getAuthenticatedEntity();e.success&&(n=e.user?.userName,r=e.user?.id,o=e.org?.login,s=e.org?.id)}catch{}if(!r)try{const e=await loadCredentials();r=e?.userId}catch{}systemInfo({userName:n,userId:r,orgLogin:o,orgId:s,platform:e,arch:t})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){zP||(zP=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=w.platform(),r=w.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Re("Opening GitHub issues...").start();try{await pe(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"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),yb(),Ot(),ro(),__name(openGitHubIssue,"openGitHubIssue");var HP=new Ie("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ot();var WP=new Ie("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const t=getSystemInfo(),{waitUntilExit:n}=ie(Q.createElement(VT,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}Ot(),Ot(),__name(runInfo,"runInfo");var GP=new Ie("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=ie(Q.createElement(hP,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}Ot(),wn(),Ot(),__name(runLearnTaste,"runLearnTaste"),Kn(),hs();var VP=new Ie(tn.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:cs.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 Ie("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 Ne("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ce.red(`Error: Invalid server name '${e}'`)),console.error(ce.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(ce.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ce.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ce.red("Error: URL is required for http transport")),console.error(ce.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ce.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(ce.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ce.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ce.cyan("Server requires OAuth authentication.")),isSecureOrLoopback(t)||(console.error(ce.red(`Error: Server '${e}' requires OAuth, but URL '${t}' is not secure.`)),console.error(ce.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ce.gray("Switch the URL to https:// or use a non-OAuth server.")),process.exit(1));let n,o="command-code";if(r.metadata.registrationEndpoint){console.log(ce.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${MS}/callback`]});e&&(o=e.clientId,n=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},console.log(ce.gray("A browser window will open for authentication.\n"));const a=await performOAuthFlow(e,t,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ce.gray(` ${e}`))},"onStatus")});a.success?console.log(ce.green("✓ Successfully authenticated")):(i=!0,console.log(ce.yellow(`Warning: Authentication failed: ${a.error}`)),console.log(ce.gray("You can retry with: cmd mcp auth "+e)),console.log(ce.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(ce.red("Error: Command is required for stdio transport")),console.error(ce.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(ce.red("Error: Command is required for stdio transport")),console.error(ce.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ce.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);s={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:s,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(ce.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ce.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===s.transport)console.log(ce.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ce.gray(` Command: ${e}`))}console.log(""),console.log(ce.cyan("Next steps:")),console.log(ce.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ce.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(ce.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(ce.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(ce.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new Ie("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ce.yellow("\nNo MCP servers configured\n")),console.log(ce.gray("Add a server with:")),console.log(ce.gray(" cmd mcp add --transport http <name> <url>")),console.log(ce.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ce.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ce.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ce.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ce.green("enabled"):ce.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ce.green(Pe.tick):ce.red(Pe.cross):o.config.headers||o.config.env?ce.green(Pe.tick):ce.gray("-"),console.log(` ${ce.white(o.name.padEnd(t))} ${ce.cyan(o.config.transport.padEnd(n))} ${ce.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ce.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ie("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(ce.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ce.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ce.dim("Scope:")} ${r}`),console.log(` ${ce.dim("Transport:")} ${n.transport}`),console.log(` ${ce.dim("Status:")} ${n.enabled?ce.green("enabled"):ce.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ce.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ce.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(` ${ce.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ce.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ce.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(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ie("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ne("-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(ce.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ce.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ce.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ce.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ie("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 Ne("-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(ce.red(`Error: Invalid server name '${e}'`)),console.error(ce.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(ce.red("Error: Invalid JSON")),console.error(ce.gray("Make sure to quote the JSON string properly")),console.error(ce.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}o?.oauth?.callbackPort&&(s=o.oauth.callbackPort,delete o.oauth.callbackPort),n.clientSecret&&o?.oauth&&(o.oauth.clientSecret=n.clientSecret);const i=bS.safeParse(o);if(!i.success){console.error(ce.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ce.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ce.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ce.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ce.cyan("Starting OAuth authentication...")),console.log(ce.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,a.url??"",t,{...s&&{port:s},onStatus:__name(e=>{console.log(ce.gray(` ${e}`))},"onStatus")});n.success?console.log(ce.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ce.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ce.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ce.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(ce.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ce.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ce.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ce.gray(` Command: ${e}`))}console.log(""),console.log(ce.cyan("Next steps:")),console.log(ce.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ie("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(ce.yellow("No servers with stored authentication."));console.log(ce.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ce.yellow("expired"):ce.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ce.red("Error: Server name is required")),console.error(ce.gray(`Usage: ${n} mcp auth <server>`)),console.error(ce.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ce.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ce.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ce.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ce.gray(" A refresh token is available for re-authentication"));else{if(console.log(ce.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ce.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ce.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ce.green(`✓ Cleared authentication for '${e}'`)):console.log(ce.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ce.red(`Error: MCP server '${e}' not found`)),console.error(ce.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),console.log(ce.cyan(`Authenticating with '${e}'...`)),console.log(ce.gray("A browser window will open for authentication.\n"));const o=__name(e=>{console.log(ce.gray(` ${e}`))},"onStatus");let s;if(r.config.oauth){const t={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};s=await performOAuthFlow(e,r.config.url??"",t,{onStatus:o})}else"http"===r.config.transport&&r.config.url||(console.error(ce.red("Error: Discovery-based auth requires an http server with a url")),process.exit(1)),s=await discoverAndAuthenticate({serverName:e,serverUrl:r.config.url,onStatus:o});if(s.success)return console.log(ce.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ce.gray("Restart the session to connect with the authenticated server."));console.error(ce.red(`\nError: Authentication failed: ${s.error}`)),console.log(ce.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ce.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ie("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}async function runCommand(e){return new Promise((t,n)=>{const r=be(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let o="",s="";r.stdout.on("data",e=>{o+=String(e)}),r.stderr.on("data",e=>{s+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${s?`: ${s.trim()}`:""}`)):t({stdout:o,stderr:s})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await v.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await v.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const o=parseGitHubSource({source:n});if(!o){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const s=String(t.maxCommits??200),i=`https://github.com/${o.owner}/${o.repo}.git`,a=await v.mkdtemp(e.join(w.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",s,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await v.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${o.owner}/${o.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${o.owner}/${o.repo}`,repoDir:a,repoName:o.repo,github:o,cleanup:__name(async()=>{await v.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),o=new jw({baseUrl:r}),s=new Xk({request:o,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await s.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(ce.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let o=0;for(let s=0;shouldContinueExtraction({offset:s,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:o});s+=10){const i=t.slice(s,s+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;o++;const s=groupCrossFilePatterns(t);for(const t of s.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const o=[`Commit: ${e.subject}`];o.push(`File: ${t.file}`),t.context&&o.push(`In: ${t.context}`);const s=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(s&&o.push(s),r.push({text:`${truncate2(t.removed,60)} → ${truncate2(t.added,60)}`,evidence:o,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${o} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],o=e.branch?[e.branch]:[],s=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...o,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(s)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",o=""]=e.split("");return{hash:t.trim(),subject:o.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let o="",s="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:o,context:s||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),o=e.match(/b\/(.+)$/)?.[1]??"",s="",l=[],isNoiseFile(o)&&(o="");continue}if(e.startsWith("@@")){g(),m(),s=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!o)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Ot(),Ot(),$S(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ot(),__name(listMcpCommand,"listMcpCommand"),Ot(),__name(getMcpCommand,"getMcpCommand"),Ot(),__name(removeMcpCommand,"removeMcpCommand"),Ot(),$S(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ot(),$S(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ot(),wn(),Ot(),Eb(),Ot(),wn(),Ot(),__name(runCommand,"runCommand"),Ot(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Ot(),sS(),fS(),Jr(),ao(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Ot(),Ot(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var QP=5,KP=3;function buildSnippet(e,t,n){const r=e??[],o=n??[],s=t.split("\n").map(e=>e.trimEnd());if(0===s.length&&0===r.length&&0===o.length)return;let i,a=0;s.length>KP?(i=s.slice(0,KP-1),a=s.length-i.length):i=s;const l=i.length+(a>0?1:0),u=Math.max(0,QP-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(o.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of o.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var YP=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return YP.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var JP=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),XP=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!JP.has(n)||!(!n.includes("[bot]")||!XP.some(e=>e.test(t)))}function truncate2(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let o=0;const s=__name(async()=>{for(;o<t.length;){const e=o++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>s())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:o}=e,s=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${s}Commits analyzed: ${o}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){Yk.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await Yk.waitForAuth()}catch{return Yk.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),Yk.markLearningComplete(),{summary:n()}}}t.isLocalSource||Yk.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const o="github"===r.type,s=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=o?e.resolve(process.cwd(),s):i;o&&Yk.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await v.mkdir(a,{recursive:!0}),Yk.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{Yk.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");Yk.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),Yk.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:s,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};Yk.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return Yk.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),Yk.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate2,"truncate"),__name(runBounded,"runBounded"),Ot(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Ot(),Ot(),Ot();var ZP=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return ZP.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Ot(),as(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Ot(),Ot();var eI=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],tI=[{id:"cloning",label:"Cloning repository"},...eI],nI=[Pe.bullet,Pe.squareSmallFilled,Pe.lozenge,Pe.star,Pe.triangleRight,Pe.triangleUp];function createInitialRepoLearnSteps(e){return(e??eI).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Ot();var rI={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var oI=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),sI=__name(e=>e??rI,"withBase");function useRepoLearnState(e){const t=e??eI,[n,r]=Y(()=>createInitialRepoLearnSteps(t)),[o,s]=Y(""),[i,a]=Y([]),[l,u]=Y(null),[d,m]=Y(!1),[g,h]=Y(!1),[f,y]=Y(null),[w,S]=Y(0),E=J(null),[C,v]=Y(null),k=ee(()=>{E.current=Date.now()},[]);return X(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),s(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,v(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(oI),void s("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),s(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=sI(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=sI(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):s(e.message):u(t=>{const n=sI(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),o=__name(()=>{h(e=>e||(r(oI),!0)),s(""),E.current&&v(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return Yk.on("reset",e),Yk.on("new-event",n),Yk.on("learning-complete",o),()=>{Yk.off("reset",e),Yk.off("new-event",n),Yk.off("learning-complete",o)}},[t]),{steps:n,currentMessage:o,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:C,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Ot(),Ot(),Rr();var iI=__name(({isComplete:e,hasError:t})=>Q.createElement(te,{flexDirection:"column",marginTop:1,marginBottom:0},Q.createElement(eP,null),Q.createElement(te,{marginTop:0},Q.createElement(ne,{color:ar.DIM},nP),Q.createElement(te,{marginLeft:2},t?Q.createElement(ne,{color:ar.DIM},"learning interrupted"):e?Q.createElement(ne,{color:cr.TEXT},"learned your coding taste"):Q.createElement(rP,null)))),"RepoLearnTastePill");Ot(),Rr();var aI=__name(({status:e})=>"active"===e?Q.createElement(te,null,Q.createElement(ne,{color:ar.YELLOW},Q.createElement(je,{type:"dots"})),Q.createElement(ne,null," ")):"complete"===e?Q.createElement(ne,{color:pr.BG},Pe.square," "):Q.createElement(ne,{color:ar.DIM},Pe.circle," "),"StepStatusIndicator"),lI=__name(({steps:e,currentMessage:t})=>Q.createElement(te,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return Q.createElement(te,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},Q.createElement(te,null,Q.createElement(te,{marginRight:1},Q.createElement(aI,{status:e.status})),Q.createElement(ne,{bold:n,color:"complete"===e.status?ar.WHITE:n?ar.YELLOW:ar.DIM},e.label)),n&&t?Q.createElement(te,{marginLeft:3},Q.createElement(ne,{color:ar.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ot(),Rr();var cI=__name(({insights:e,insightCount:t})=>0===e.length?null:Q.createElement(te,{flexDirection:"column",marginTop:1,marginLeft:4},Q.createElement(ne,{color:ar.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>Q.createElement(ne,{key:`${t}-${e}`,color:ar.DIM},nI[t%nI.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ot(),Rr();var uI=__name(({message:e})=>Q.createElement(te,{flexDirection:"column",borderStyle:"single",borderColor:ar.RED,paddingX:2,paddingY:1,marginTop:1},Q.createElement(ne,{color:ar.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(te,{marginTop:1},Q.createElement(ne,null,e))),"RepoLearnErrorPanel");Ot(),Rr(),Xr();var dI=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return Q.createElement(te,{flexDirection:"column",marginLeft:3},Q.createElement(te,{marginBottom:1,flexDirection:"row"},Q.createElement(ne,{color:ar.DIM},nP),Q.createElement(te,{marginLeft:2},Q.createElement(ne,{color:cr.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),Q.createElement(te,{flexDirection:"column",marginLeft:1},Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," Taste stored in"," "),Q.createElement(Kr,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:ar.CYAN})),Q.createElement(te,null,Q.createElement(ne,{color:ar.DIM},Pe.pointerSmall," Share your coding taste: ",Q.createElement(ne,{color:ar.CYAN},"npx taste push --all")))),Q.createElement(te,{marginTop:1,marginLeft:1},Q.createElement(ne,{color:ar.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ot(),Rr();var mI=__name(({done:e,error:t})=>t?Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0},"Press ESC to exit")):e?Q.createElement(te,{marginTop:1},Q.createElement(ne,{bold:!0},"Press ENTER to continue")):Q.createElement(te,{marginTop:1},Q.createElement(ne,{color:ar.DIM},"ESC to cancel")),"RepoLearnFooter");Ot(),Rr();var pI=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=Z(()=>tx(n),[n]);return Q.createElement(te,{flexDirection:"column"},Q.createElement(te,{flexDirection:"column",marginBottom:1},Q.createElement(ax,null,r.trimEnd())),e?Q.createElement(ne,{color:ar.WHITE},e):Q.createElement(Q.Fragment,null,Q.createElement(ne,{color:ar.WHITE},"Learning your coding taste from ",Q.createElement(ne,{bold:!0,color:ar.CYAN},t??"repository")),Q.createElement(ne,{color:ar.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?Q.createElement(uI,{message:e}):t?Q.createElement(dI,{summary:n,elapsedSeconds:r}):Q.createElement(cI,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=J(!1);return X(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),se((e,n)=>{if(s.showLogin)return;const r=n.escape||""===e,o=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(s.done||s.error)&&o&&t({published:!1,cancelled:!!s.error})}),s.showLogin?Q.createElement(te,{flexDirection:"column"},Q.createElement(pI,{text:r,repoName:o}),Q.createElement(TA,{onComplete:(e,t)=>{s.setShowLogin(!1),e?Yk.resolveAuth():Yk.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),Yk.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):Q.createElement(te,{flexDirection:"column"},Q.createElement(pI,{text:r,repoName:o}),Q.createElement(iI,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),Q.createElement(lI,{steps:s.steps,currentMessage:s.currentMessage}),Q.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),Q.createElement(mI,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{Yk.reset();const r=new AbortController;let o,s,i=!1,a=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,Yk.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),Yk.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),Yk.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=ie(Q.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{Yk.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),yb();var gI=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new Ie("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",gI("--max-commits"),200).addOption(new Ne("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(gI("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await v.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),o=await resolveDisplayName(t.source),s=!await getAuthKey();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:o}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:s,signal:e});return i=o?.cleanup,r},"runTask");if(r){const t=n?void 0:[...tI];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:o,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),wb(),await IP({skipOnboarding:!0})}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(w.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")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ot(),Ot(),Ot(),wn(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ot(),Ot();var hI=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||hI.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:hI.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(hI.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:i}}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(!hI.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)),i=s.length>0?s[s.length-1]:null;if(!i)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?o.substring(0,i.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:`${Pe.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&i.push(`${o.length} warning${o.length>1?"s":""}`);const a=r.length>0?Pe.cross:Pe.warning;return{valid:s,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ce.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ce.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`${ce.green(e)} ${ce.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?ce.red(t.summary):ce.yellow(t.summary),"",...formatIssueGroup(r,ce.red,ce.bold(ce.red("Errors:"))),...formatIssueGroup(o,ce.yellow,ce.bold(ce.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"),Ot(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var fI=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:o}=e;fI.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 yI=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,wI=/^\[cmd\]: https:\/\/commandcode\.ai\/$/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}):yI.test(s)||wI.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),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:i,rawLines:o});return checkFinalCategory({state:i,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var SI=__name(e=>"local-global"===e?"global":"project","locationLabel"),EI=__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 D(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${SI(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});D(o)&&r.push({path:o,displayName:"taste.md"});const s=(await v.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>D(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 v.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await v.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,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:i}}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 EI({file:"all",error:`No taste files found in ${SI(n)}`});const s=await Promise.all(r.map(lintFile)),i=s.reduce((e,t)=>e+t.errors,0),a=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return EI({file:"all",error:`No taste files found in ${SI(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),i=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return D(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):EI({file:"all",error:`No taste directory found in ${SI(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"),Ot(),hs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var bI=ce.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(`${ce.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?`${ce.dim(t[1])}${ce.green(t[2])}${ce.white(t[3]??"")}${t[4]?ce.dim(t[4]):""}`:ce.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ce.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 CI=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return St(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:CI})}function getProfileLink(e){return St(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:CI})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return wt(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(ce.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(`${ce.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(ce.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ie("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 ${ce.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(`${ce.green(Pe.tick)} All ${ce.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ce.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ce.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(ce.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,n=await v.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await v.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){if(!e)return Ob+"\n\n";const t=e.trim();return t.startsWith($b)||t.startsWith(Fb)||t.startsWith(qb)?e:Ob+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Ot(),Ns(),Ot(),Ot(),Ot(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ot(),__name(formatPackage,"formatPackage"),Ot(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var vI="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:vI,category:e.name});return D(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await v.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:vI});if(!D(e))return[];const t=await v.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:vI,category:t});return D(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:vI});await v.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:vI,category:n.category}),s=e.dirname(o);await v.mkdir(s,{recursive:!0});const i=formatPackage({pkg:n});await v.writeFile(o,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Ot(),Ot();var kI="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!D(n))return null;const r=migrateHeader({content:await v.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),i=o.end<r.length-1?r.slice(o.end+1):[],a={before:s.join("\n").trim(),after:i.join("\n").trim()},l=[...s,...i].join("\n").trim();return""===l&&await v.rm(n,{force:!0}),""!==l&&await v.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:kI}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:kI,category:n}),i=e.dirname(s);return D(i)&&await v.rm(i,{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=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=o.trim()+t,void await v.writeFile(n,e.trim()+"\n","utf-8")}let s="";D(n)&&(s=await v.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await v.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:kI,category:n.category}),i=e.dirname(s);await v.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await v.writeFile(s,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=ensureHeader(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=l.trim()+t,void await v.writeFile(r,e.trim()+"\n","utf-8")}let u="";D(r)&&(u=await v.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await v.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var TI="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:TI,category:e.name});return D(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:TI});if(!D(e))return[];const t=[],n=getRootTasteFile({target:TI});if(D(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await v.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:TI});await v.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:TI}),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 exists2(){const e=getTastePath({target:TI});return D(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!D(n))return;const r=await v.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:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),o&&l.append("description",o),l.append("type",s),l.append("isPublic",String(i)),l.append("overwrite",String(a));const u=formatPackage({pkg:r}),d=new Blob([u],{type:"text/markdown"}),m=new File([d],"taste.md",{type:"text/markdown"});if(l.append("files[taste.md]",m),"category"===s)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!D(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!D(f))return l;const y=await v.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1,overwrite:s=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(o)),i.append("overwrite",String(s));const a=getRootTasteFile({target:"local-project"});if(D(a)){const e=await v.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}const l=t.map(e=>appendCategoryFile(i,e));return await Promise.all(l),i}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,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:cs.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),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}${Bt.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}${Bt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:cs.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()}${Bt.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:cs.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,overwrite:o=!1}=e,s=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:o}),a=`${getApiBaseUrl()}${Bt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:l.status}),await l.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o=!1,overwrite:s=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o,overwrite:s}),l=`${getApiBaseUrl()}${Bt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:a});u.ok||throwTrackedError({message:await parseApiError({response:u,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:u.status,extra:{"package.count":t.length}}),await u.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${Bt.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 v.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 Ie("list").alias("ls").option("-g, --global","List global packages").addOption(new Ne("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ne("--staging","Use staging environment").hideHelp()).description(`List available packages ${ce.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Ot(),fS(),Ot(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),wn(),Ot(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),bb(),hs(),Ot(),yb(),hs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ot(),fS(),yb(),wn(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),Kn(),__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 _I={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?_I.remote:e.global?_I.global:_I.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Pe.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Pe.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` ${ce.white(e.category)}${e.isPublic?ce.green(" [public]"):""}${e.isPublic&&e.starCount?ce.yellow(` ${Pe.star}${e.starCount}`):""}${e.downloadCount?ce.gray(` ${Pe.arrowDown}${e.downloadCount}`):""}${n}${ce.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?Re(`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${bI} Packages`),console.log(`${ce.gray("⎿")} ${ce.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(ce.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(ce.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 v.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 ft([{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"),Ot(),Ot(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var xI=new Set(["local-project","local-global","remote-project","remote-user"]);async function open11(e){const{package:t,target:n}=e;if(!xI.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=Et.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 Ie("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 ${ce.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 pe(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ce.green(Pe.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open11({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ce.green(Pe.tick)} Opened ${ce.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open11,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Ot(),Ot(),Ot(),Ot();var AI=null,PI=!1;function setActiveSpinner(e){AI=e}function stopActiveSpinner(e){AI&&(AI.stop(e),AI=null)}function setPrompted(e){PI=e}function wasPrompted(){return PI}function beginPrompt(e,t){stopActiveSpinner(),Ue.intro(ce.dim(e)),t&&Ue.log.message(ce.dim(t)),setPrompted(!0)}function handleCancel(e){Ue.isCancel(e)&&(Ue.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ue.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ue.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),Ue.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ce.green(`'${t}'`)} from ${n}`,s),Ue.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ce.dim(`(from ${n})`)}`);const i=await Ue.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(i);const a=i;return startStrategySpinner(a),a}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),Ue.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ce.green(`'${t}'`)} to global`,o),Ue.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Ue.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 i=s;return startStrategySpinner(i),i}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),Ue.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ce.green(`'${t}'`)} from global`,o),Ue.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Ue.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 i=s;return startStrategySpinner(i),i}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),Ue.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=St(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ce.green(`'${t}'`)} to ${n}`,s),Ue.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Ue.log.info(`Current package: ${ce.cyan(i)} ${ce.dim("(review)")}`);const a=await Ue.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ue.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=St(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ce.green(`'${t}'`)} to ${n}`,s),Ue.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Ue.log.info(`Current package: ${ce.cyan(i)} ${ce.dim("(review)")}`);const a=await Ue.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(a);const l=a;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 i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{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,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void s.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});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:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:o,flagStrategy:s,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:o,flagStrategy:s,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:o,flagStrategy:s,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Ot(),Ot(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ot(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var II=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),NI=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),RI=__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,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void s.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});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 II({pkg:"all",error:`Invalid source: ${n}`});const s=RI(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return II({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return II({pkg:"all",error:`No taste packages found in ${s}`});const a=validatePackages({packages:i,label:s});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=NI();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,i=await downloadPackage({owner:t,packageName:n});if(!i)return II({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:o,result:s};return"project"===a?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=NI();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return II({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Ue.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,i=wasPrompted()?"":`${Pe.tick} `,a=r?ce.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ce.green(i)}Replaced ${ce.green(`'${t}'`)} taste package in project`+a;if(s){const e=formatMergeParts(s);return`${ce.green(i)}Pulled ${ce.green(`'${t}'`)} taste package from ${n} ${ce.gray(`(${e.join(", ")})`)}`+a}return`${ce.green(i)}Pulled ${ce.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const o=t.packagesPulled[0],s=t.filePaths?.[o],i=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+o.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return s.length>0&&l.push(wrapLine(`${ce.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ce.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${ce.dim("Skipped")} (${o.length}) ${ce.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Ue.log.message(l.join("\n")),Ue.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ce.green(Pe.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ce.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ie("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 Ne("--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 Ne("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ce.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(Re("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(Re("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 jw({baseUrl:e}),n=await t.get({endpoint:Bt.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 Ue.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()?"":`${Pe.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ce.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${Pe.tick} `;if(!a)return logResult2(`${ce.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?` ${ce.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ce.green(l)}Replaced ${s} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ce.green(l)}Pushed ${s} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${ce.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${ce.green(l)}Pushed ${s} to ${a}${h}`),(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,i=s?o:"global",a=wasPrompted()?"":`${Pe.tick} `,l=!s&&o?ce.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ce.green(a)}Replaced ${ce.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ce.green(a)}Pushed ${ce.green(`'${r}'`)} taste package to ${i} ${ce.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ce.green(a)}Pushed ${ce.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",o=wasPrompted()?"":`${Pe.tick} `;return logResult2(wrapLine(`${ce.green(o)}Pushed ${ce.green(t.packagesPushed.length)} taste packages ${ce.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 i=getPackageLink({owner:o,packageName:s});r.has(i)||(r.add(i),console.log(ce.gray(` ${i}`)))}}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,i=[];o.length>0&&i.push(wrapLine(`${ce.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ce.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ce.dim("Skipped")} (${r.length}) ${ce.dim(r.join(", "))}`,4)),i.length>0&&Ue.log.message(i.join("\n"));const a=`${s} ${1===s?"package":"packages"}`;Ue.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),o=[];r.length>0&&o.push(wrapLine(`${ce.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ce.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ce.dim("Skipped")} (${n.length}) ${ce.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"),Ot(),__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"),Ot(),Kn(),Ot(),fS(),sS(),wn(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ot(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ot(),bb(),Ot();var MI=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),LI=__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:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=o.reduce((e,t)=>e+t.learnings.length,0),u=LI(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l}),m=await resolvePushAllStrategy({flagStrategy:a,overwrite:o,existingProject:d,packagesToPush:n,projectName:l,owner:r});if("skip"===m)return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?s:d?.isPublic??!1,overwrite:"overwrite"===m});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 MI({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var $I=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),DI=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o,overwrite:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o,overwrite:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var OI=__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:i,result:a}=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 a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:s,isPublic:i,overwrite:!0}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:s,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=OI({target:n,category:t.category,owner:s});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e;if(!exists2())return $I({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return $I({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:i}):$I({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return $I({pkg:"all",error:`Invalid target: ${r}`});const m=DI();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,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:i}=e,a=await getPackage2({category:r});if(!a)return $I({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return $I({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:o,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?s:u?.isPublic??!1,g=DI();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,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(!exists2())return $I({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return $I({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 Ue.select({message:"Owner",options:r,initialValue:t});return Ue.isCancel(o)&&(Ue.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new Ie("push").description(`Push taste packages to remote ${ce.dim("(commandcode.ai)")} or global ${ce.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 Ne("--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 Ne("--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"),Ot(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var FI=__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};Ue.intro(ce.dim(`pushing ${t}`)),setPrompted(!0);const o=Ue.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Ue.outro(ce.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"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ce.dim(` Pushing ${s} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Re("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:FI(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 i=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:FI(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ue.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Re("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),i=o.length>0?o.length:s.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(ce.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Re("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 Ie(tn.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()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?ue.bold(ue.green(t)):ue.white(t);return`${ue.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ue.bold(ue.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ue.dim(`Run ${ue.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ue.dim("Try updating manually:")),console.log(ue.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ue.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Re("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(`${ue.green(Pe.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ue.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Re("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${Pe.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),trackError({error:sanitizeErrorForTelemetry({error:new Error("Update failed"),label:"cli_update_failed"}),context:{component:cs.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 ${ue.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"),Jr(),__name(createTasteCommand,"createTasteCommand"),Ot(),wn(),hs(),__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 qI=new Ie("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ot(),yb(),bb();var jI=__name((e,t)=>`${Pe.info} ${e}: ${ue.cyan(t)}`,"formatInfoLine"),UI=__name(e=>ue.bold(`${e}:`),"formatSectionHeader"),BI=__name(e=>ue.red(e),"formatError"),zI=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),HI=__name(e=>["",UI("User Information"),jI("Name",e.name),jI("Email",e.email),jI("Username",e.userName)],"buildUserOutput"),WI=__name(e=>["",UI("Organization"),jI("Name",e.name),jI("Login",e.login)],"buildOrgOutput"),GI=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),VI=__name((e,t)=>{GI(HI(e)),t&&GI(WI(t)),console.log("")},"displayUserInfo"),QI=__name(e=>null!==e&&e.length>0,"validateApiKey"),KI=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Re("Fetching user information...").start();try{const t=await getAuthKey();QI(t)||(e.fail(BI('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();KI(n)||(e.fail(BI("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),VI(n.user,n.org)}catch(t){e.fail(BI(`Error: ${zI(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var YI=new Ie("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function normalizeGitUrl(e){let t=e.trim();const n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);return n?`https://${n[1]}/${n[2]}`:(t=t.replace(/\.git$/,""),t)}function validateGitRepo(){try{if("true"!==Se("git rev-parse --is-inside-work-tree",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error("Not inside a git repository.")}catch{throw new Error("Sandbox requires a git repository with a GitHub remote.")}let e;try{e=Se("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("No GitHub remote found. Add one with: git remote add origin https://github.com/you/repo")}const t=normalizeGitUrl(e);let n;try{n=Se("git branch --show-current",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("Failed to determine current branch.")}if(!n)throw new Error("Detached HEAD state. Please checkout a branch first.");if(!/^[\w./-]+$/.test(n))throw new Error("Branch name contains invalid characters. Please use a simpler branch name.");try{if(!Se(`git ls-remote --heads origin ${n}`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}catch(e){if(e instanceof Error&&e.message.includes("not found on remote"))throw e;throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}return{repoUrl:t,branch:n,isClean:""===Se("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}Ot(),Ot(),wn(),sS(),Rs(),fS(),Rn(),io(),Ot(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ot(),fS(),yb(),Ot();var JI=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return JI.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var XI={setting_up:"Setting up sandbox...",cloning:"Cloning repository..."};function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusEvent({event:e,state:t}){const n=e.data.status,r=XI[n],o="setup"===t.phase;if(t.isResume&&o&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&o&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=Re({stream:process.stderr,text:r}).start()),"running"===n)return t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="running",void(t.workingSpinner||(t.workingSpinner=Re({stream:process.stderr}).start()));if("completed"===n){t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="done";const n=e.data.prUrl;return void(n&&console.error(`PR: ${ue.cyan(n)}`))}if("failed"===n){const n=e.data.message||"Unknown error";return t.workingSpinner&&(t.workingSpinner.fail(n),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(n),t.currentSpinner=null),void(t.phase="done")}if("timed_out"===n)return t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null),void(t.phase="done");"cancelled"===n&&(stopAllSpinners({state:t}),t.phase="done",console.error(`\n${ue.yellow("Cancelled.")}`))}}function renderEvent({event:e,state:t}){if("status"!==e.type){if("pty"===e.type){const n=e.data.content;return void(n&&(t.workingSpinner&&t.workingSpinner.stop(),process.stdout.write(n),t.workingSpinner&&t.workingSpinner.start()))}if("error"===e.type){t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null);const n=e.data.message;console.error(`${Pe.cross} ${ue.red(n)}`)}}else renderStatusEvent({event:e,state:t})}function setupInputHandling({callbacks:e}){const t=__name(t=>{3===t[0]?e.onCancel():4===t[0]&&e.onDetach()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({ws:e}){const t=__name(()=>{e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({action:"resize",cols:process.stdout.columns,rows:process.stdout.rows}))},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}function sendTerminalSize({ws:e}){e.send(JSON.stringify({action:"resize",cols:process.stdout.columns||120,rows:process.stdout.rows||30}))}async function streamSession({sessionId:e,prompt:t,lastEventId:n=0,isResume:r=!1}){const o=getApiBaseUrl().replace(/^http/,"ws"),s=await getAuthKey();if(!s)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:s,...n>0?{lastEventId:String(n)}:{}}),a=`${o}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,o)=>{const s=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=Re({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.close(),console.error(`\n${ue.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${ue.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.readyState===WebSocket.OPEN&&s.send(JSON.stringify({action:"cancel"})),s.close(),console.error(`\n${ue.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:s}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");s.addEventListener("open",()=>{sendTerminalSize({ws:s}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${ue.yellow("[Ctrl+C]")} ${ue.dim("stop")} ${ue.yellow("[Ctrl+D]")} ${ue.dim("detach")}`),console.error(`${ue.dim("Session:")} ${ue.gray(e)}`),console.error(""),r&&(i.workingSpinner=Re({stream:process.stderr}).start())}),s.addEventListener("message",e=>{try{const n="string"==typeof e.data?e.data:e.data.toString(),r=JSON.parse(n);renderEvent({event:r,state:i}),void 0!==r.id&&(i.lastEventId=r.id),"status"===r.type&&isTerminalStatus(r.data.status)&&(s.close(),g(),t())}catch{}}),s.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),o(new Error("WebSocket connection failed"))}),s.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${ue.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${ue.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=L.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=L.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=at.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function startSandboxSession({repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}){return new jw({baseUrl:getApiBaseUrl()}).post({endpoint:Bt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateGitRepo();n.isClean||console.error(ue.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),s=e||await askQuestion(`${ue.bold("What do you want to do?")}\n${ue.cyan(">")} `);if(!s.trim())return void console.error(ue.yellow("No prompt provided. Aborting."));const i=s.trim().slice(0,nn.MAX_PROMPT_CHARS),a=Re({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:i,isInternalTeam:r,configFiles:o});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:i}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=e instanceof Ss,r=t?e.code:void 0;if(401===(t?e.status:void 0)||"UNAUTHORIZED"===r)console.error(ue.red("\nAuthentication failed. Try logging in again: cmd login"));else if("GITHUB_APP_NOT_INSTALLED"===r){const e=ue.cyan(ue.underline(n.repoUrl)),t=ue.cyan(ue.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${ue.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(ue.dim(" Then run this command again."))}else{const n=t&&"string"==typeof e.message?e.message:"Something went wrong. Please try again.";console.error(ue.red(`\n${n}`))}process.exit(1)}}function createSandboxCommand(){return new Ie("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(ue.red(t)),process.exit(1)}})}function validateSafeString(e,t){if(e.includes("..")||e.includes("\\"))throw new Error(`Invalid ${t}: path traversal sequences are not allowed.\nExpected format: owner/repo or owner/repo/path`);if(!/^[a-zA-Z0-9._/-]+$/.test(e))throw new Error(`Invalid ${t}: contains unsupported characters.\nOnly letters, numbers, hyphens, underscores, dots, and slashes are allowed.`)}function parseGitHubRepo(e){let t,n=e.replace(/^https?:\/\/github\.com\//,"");const r=n.lastIndexOf("@");r>0&&r<n.length-1&&(t=n.slice(r+1),n=n.slice(0,r),validateSafeString(t,"branch name"));const o=n.split("/");if(o.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[s,i,...a]=o;validateSafeString(s,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:s,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:o}=e;let s=`gh:${t}/${n}`;return r&&(s+=`/${r}`),o&&(s+=`#${o}`),s}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:o,path:s}=n;let i;if(s){const e=s.split("/").filter(Boolean);i=e[e.length-1]}else i=o;const a=t.join(S.tmpdir(),`commandcode-skill-${M()}`);await k.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:s}=await import("giget");try{await s(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,o),await s(e,{dir:a,force:!0,silent:!0})}const l=t.join(a,"SKILL.md"),u=t.join(a,"skill.md");let d=!1;try{await k.access(l),d=!0}catch{}if(!d)try{await k.access(u),d=!0}catch{}if(!d)throw new Error(`SKILL.md not found in ${e}. Make sure the repository contains a SKILL.md file.`);return{tempDir:a,skillName:i}}catch(e){if(await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,o)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:o,path:s,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(Pb(),Ab)),u=await l({owner:r,repo:o,path:s,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${o}${s?` at path "${s}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await k.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await k.access(r),r}catch{}throw new Error(`SKILL.md not found in ${e}`)}function validateSkillName(e){const t=e.trim();if(!t||0===t.length)throw new Error("Invalid skill name: name cannot be empty");if(t.includes("/")||t.includes("\\"))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain path separators (/ or \\).`);if(t.includes(".."))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain parent directory references (..).`);if(t.startsWith("."))throw new Error(`Invalid skill name: "${e}". Skill names cannot start with a dot.`);if(!/^[a-z0-9-]+$/.test(t))throw new Error(`Invalid skill name: "${e}". Skill names must contain only lowercase letters, numbers, and hyphens.`);return t}async function validateSkillContent(e){const t=await resolveSkillMdPath(e),n=await k.readFile(t,"utf-8"),{data:r}=Ke(n),o=hf.parse(r);return{name:validateSkillName(o.name),description:o.description}}async function skillExists(e){const{skillName:n,location:r}=e,o="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),s=t.join(o,n);try{return await k.access(s),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:o=!1,force:s=!1,skillName:i,discoveredSkill:a,cachedTempDir:l}=r;let u,d,m=n;if(i){let e;if(a)e=a;else{const t=await discoverSkillsInRepo(n);if(0===t.skills.length)throw new Error(`No skills found in repository: ${n}`);const r=t.skills.find(e=>e.name.toLowerCase()===i.toLowerCase());if(!r){const e=t.skills.map(e=>e.name).join(", ");throw new Error(`Skill "${i}" not found in repository. Available skills: ${e}`)}e=r}const t=parseGitHubRepo(n),r=[t.path,e.path&&"."!==e.path?e.path:void 0].filter(Boolean).join("/"),o=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${o}@${t.branch}`:o}if(l&&a){u=a.path&&"."!==a.path?t.join(l,a.path):l,d=!1;try{await resolveSkillMdPath(u)}catch{const e=a.path&&"."!==a.path?`at ${a.path}`:"at root";throw new Error(`SKILL.md not found in cached directory ${e}. Make sure the repository contains a SKILL.md file.`)}}else u=(await fetchSkillFromGitHub(m)).tempDir,d=!0;try{const{name:e,description:n}=await validateSkillContent(u),r=e,i=o?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!s)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await k.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await k.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&s&&await k.rm(d,{recursive:!0,force:!0}),await k.rename(g,d)}catch(e){if(await k.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await k.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),o=n?"global":"project",s="global"===o?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(s,r);if(!await skillExists({skillName:r,location:o}))throw new Error(`Skill "${r}" not found in ${"global"===o?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===o?"":" Use -g/--global to check global skills."}`);await k.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t}=await loadAllSkillSummaries();return{global:e.map(e=>({name:e.name,description:e.description,location:"global",path:e.filePath})),project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath}))}}__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusEvent,"renderStatusEvent"),__name(renderEvent,"renderEvent"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(sendTerminalSize,"sendTerminalSize"),__name(streamSession,"streamSession"),__name(readLocalConfigFiles,"readLocalConfigFiles"),__name(askQuestion,"askQuestion"),__name(startSandboxSession,"startSandboxSession"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),Jr(),Ot(),Ot(),Ot(),Ot(),xb(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),Rf(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),wn();var ZI=[`${ue.dim("Usage:")}`,` ${ue.cyan("cmd skills add")} ${ue.white("<owner/repo>")}`,"",`${ue.dim("Examples:")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/my-skills")} ${ue.dim("# single-skill repo")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/skills/path/to/skill")} ${ue.dim("# specific path in repo")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/multi-skills -s my-skill")} ${ue.dim("# pick one from multi-skill repo")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/repo@branch")} ${ue.dim("# specific branch")}`,` ${ue.cyan("cmd skills add")} ${ue.white("acme/repo --global")} ${ue.dim("# install to ~/.commandcode/skills/")}`],eN=__name((e,t)=>`${ue.green(Pe.tick)} Installed ${ue.cyan(e)} ${ue.dim(`${Pe.arrowRight} ${t}/`)}`,"formatInstalled"),tN=__name(e=>`${ue.red(Pe.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await x(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(tN("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),ZI.forEach(e=>console.log(e)),process.exit(1));const t=e.replace(/^https?:\/\/github\.com\//,""),n=t.lastIndexOf("@");(n>0?t.slice(0,n):t).split("/").filter(Boolean).length<2&&(console.error(tN(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${ue.cyan("owner/repo")} or ${ue.cyan("owner/repo/path")}`),console.log(""),ZI.forEach(e=>console.log(e)),process.exit(1))}async function addAction(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let o;validateRepoFormat(e);const s=Re({text:`Fetching ${ue.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(o=u,s.stop(),0===l.length&&(console.error(tN(`No skills found in ${ue.cyan(e)}`)),console.log(ue.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(tN(`Skill "${t.skill}" not found in ${ue.cyan(e)}`)),console.log(""),console.log(ue.dim("Available skills:")),l.forEach(e=>console.log(` ${ue.cyan(e.name)}`)),await cleanupAndExit(o,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await Be({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(ue.dim("Cancelled")),await cleanupAndExit(o,0));const n=t;i=l.filter(e=>n.includes(e.name))}else i=l;let d=0;for(const n of i)try{const s=Re({text:`Installing ${ue.cyan(n.name)}...`,color:"cyan"});s.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:o}});s.stop(),console.log(eN(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(tN(`Failed to install "${n.name}"`)),console.log(ue.dim(` ${t}`))}await cleanupAndExit(o,d>0?1:0)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(tN(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var nN=new Ie("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${ZI.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(tN("No repository specified.")),console.log(""),ZI.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ot(),wn();var rN=__name((e,t)=>`${ue.green(Pe.tick)} Removed ${ue.cyan(e)} from ${t} skills`,"formatRemoved"),oN=__name(e=>`${ue.red(Pe.cross)} ${e}`,"formatError");function validateSkillNameEarly(e){return e.includes("/")||e.includes("\\")?`"${e}" is not a valid skill name — it cannot contain path separators.`:e.includes("..")?`"${e}" is not a valid skill name — it cannot contain "..".`:e.startsWith(".")?`"${e}" is not a valid skill name — it cannot start with a dot.`:/^[a-z0-9-]+$/.test(e.trim())?null:`"${e}" is not a valid skill name — use only lowercase letters, numbers, and hyphens.`}async function removeAction(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",o=validateSkillNameEarly(e);if(o&&(console.error(oN(o)),console.log(ue.dim(`Run ${ue.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await ze({message:`Remove ${ue.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(ue.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(rN(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(oN(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(ue.dim(`Try ${ue.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(ue.dim(`Run ${ue.cyan("cmd skills list")} to see installed skills.`))):console.error(oN(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var sN=new Ie("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction);Ot(),UE(),wn();var iN=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${ue.cyan(e)} ${ue.dim(`· ${n}`)}`},"formatSkillLine"),aN=__name((e,t)=>`${ue.bold(ue.white(e))} ${ue.dim(`(${t})`)}`,"formatSectionHeader"),lN=__name(()=>{const e=process.cwd(),n=t.join(e,".commandcode","skills"),r=t.join(e,".agents","skills"),o=getProjectSkillsDir(),s=getProjectAgentsCompatSkillsDir(),i=["",ue.dim("No skills installed."),"",ue.dim("Looking in:"),ue.dim(` ${getGlobalSkillsDir()} ${ue.white("(global)")}`),ue.dim(` ${getGlobalAgentsCompatSkillsDir()} ${ue.white("(global, .agents)")}`)];return n!==o&&i.push(ue.dim(` ${n} ${ue.white("(cwd)")}`)),r!==s&&i.push(ue.dim(` ${r} ${ue.white("(cwd, .agents)")}`)),i.push(ue.dim(` ${o} ${ue.white("(project)")}`),ue.dim(` ${s} ${ue.white("(project, .agents)")}`),"",`Install a skill: ${ue.cyan("cmd skills add")} ${ue.dim("<owner/repo>")}`,""),i},"formatEmptyHint"),cN=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){try{const{global:e,project:t}=await listSkills(),n=e.length+t.length;0===n&&(cN(lN()),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:ue.dim(`${n} installed`)})),t.length>0&&(console.log(""),console.log(aN("Project",t.length)),t.forEach(e=>{console.log(iN(e.name,e.description))})),e.length>0&&(console.log(""),console.log(aN("Global",e.length)),e.forEach(e=>{console.log(iN(e.name,e.description))})),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${ue.red(Pe.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var uN=new Ie("list").description("List all installed skills").action(listAction),dN=new Ie("skills").description("Manage skills from GitHub repositories").addCommand(nN).addCommand(sN).addCommand(uN);handleUnhandledErrors(),setupTelemetry(),await preRun();var mN=createProgram();mN.action(interactiveModeAction),mN.addCommand(WP),mN.addCommand(GP),mN.addCommand(YI),mN.addCommand(qI),mN.addCommand(HP),mN.addCommand(createTasteCommand()),mN.addCommand(createMcpCommand()),mN.addCommand(VP),mN.addCommand(ys),mN.addCommand(ZE),mN.addCommand(lb),mN.addCommand(dN),isExperimentalEnabled()&&mN.addCommand(createSandboxCommand()),setupCommanderHooks(mN),mN.parse();
|