command-code 0.9.5 → 0.9.6

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.
Files changed (2) hide show
  1. package/dist/index.mjs +2 -2
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import"dotenv/config";import{Command as e,Option as t}from"commander";import{execSync as n,spawn as r}from"child_process";import o,{mainSymbols as a}from"figures";import*as s from"@clack/prompts";import{confirm as i,isCancel as c,cancel as l,note as d,password as u,select as m,outro as g}from"@clack/prompts";import p from"picocolors";import h from"open";import*as f from"path";import y,{dirname as w,join as E,relative as b,isAbsolute as v,resolve as k}from"path";import*as C from"os";import T from"os";import*as S from"fs/promises";import P,{mkdir as A,writeFile as x}from"fs/promises";import $ from"crypto";import I,{z as D}from"zod";import*as F from"fs";import R,{existsSync as M,readFileSync as N,promises as j,constants as O,readdirSync as L,statSync as _}from"fs";import U,{useState as B,useEffect as W,useRef as z,useMemo as G,useCallback as H}from"react";import{Static as V,Box as q,Text as K,useInput as J,useStdout as Y,render as Z,useApp as X}from"ink";import Q from"ink-text-input";import ee from"sharp";import te from"chalk";import ne from"open-editor";import*as re from"process";import oe from"semver";import{fileURLToPath as ae}from"url";import se from"gray-matter";import{minimatch as ie}from"minimatch";import{glob as ce}from"glob";import{quote as le}from"shell-quote";import{MessageStream as de}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import ue from"@sindresorhus/slugify";import{EventEmitter as me}from"events";import ge from"@crosscopy/clipboard";import pe from"ink-gradient";import{setOptions as he,parse as fe}from"marked";import ye from"marked-terminal";import*as we from"diff";import Ee from"ignore";import be from"ink-select-input";import ve from"dedent";import ke from"log-symbols";import Ce from"readline/promises";var Te=Object.defineProperty,__name=(e,t)=>Te(e,"name",{value:t,configurable:!0}),Se=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${o.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${o.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${o.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${o.warning} ${e}`)}debug(e){process.env.DEBUG&&console.log(`[${this.prefix}] ${o.bullet} ${e}`)}};function heading({text:e,sub:t,dim:n,green:r}){return r?`${p.bgGreen(p.black(` ${e} `))} ${t&&t}`:n?`${p.bgBlack(p.white(` ${e} `))} ${t&&t}`:`${p.bold(p.bgCyan(p.black(` ${e} `)))} ${t&&t}`}__name(heading,"heading");var Pe="--co",Ae="--xco",xe=`x-${Pe.replace("--","")}-flag`,$e="x-oauth-token",Ie="x-project-slug",De="x-taste-learning",Fe={ALPHA:{GENERATE:"/alpha/generate",WHOAMI:"/alpha/whoami",NAMESPACES:"/alpha/namespaces",AGENT:{GENERATE:"/alpha/agent/generate"},SHARE:{CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},DEVREL_THREAD:{CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",DATA:"/alpha/devrel-thread/data",UPDATE:"/alpha/devrel-thread/update"},TASTE:{GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"}},BETA:{TASTE:{PACKAGES:{UPLOAD:"/beta/taste/packages/:namespace",LIST:"/beta/taste/packages",GET:"/beta/taste/packages/:namespace/:packageName",FILES:"/beta/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/beta/taste/packages/:namespace/:packageName/download",DELETE:"/beta/taste/packages/:namespace/:packageName"}}},INTERNAL:{ADMIN:{USERS:"/internal/admin/users",GRANT_CREDITS:"/internal/admin/grant-credits",ORGS:"/internal/admin/orgs",GRANT_ORG_CREDITS:"/internal/admin/grant-org-credits",ENTITY_TYPE:"/internal/admin/entity-type"},PROFILE:{GET:"/internal/profile/:login",PACKAGES:"/internal/profile/:login/packages",PACKAGE_GET:"/internal/profile/:login/packages/:packageName",PACKAGE_DOWNLOAD:"/internal/profile/:login/packages/:packageName/download",FOLLOWERS:"/internal/profile/:login/followers",FOLLOWING:"/internal/profile/:login/following"},API_KEYS:{CREATE:"/internal/api-keys/create",LIST:"/internal/api-keys/list",DELETE:"/internal/api-keys/delete"},BILLING:{CREDITS:{GET:"/internal/billing/credits"},CUSTOMERS:{GET:"/internal/billing/customers",UPSERT:"/internal/billing/customers",SETUP_INTENT:"/internal/billing/customers/setup-intent",PAYMENT_METHOD:"/internal/billing/customers/payment-method",SET_DEFAULT_PAYMENT_METHOD:"/internal/billing/customers/payment-method/set-default",INVOICES:"/internal/billing/customers/invoices"},SUBSCRIPTIONS:{GET:"/internal/billing/subscriptions"},WEBHOOK:"/internal/billing/webhook"},ORGS:{LIST:"/internal/orgs",GET:"/internal/orgs/:login",CREATE:"/internal/orgs",UPDATE:"/internal/orgs/:id",DELETE:"/internal/orgs/:id",AVATAR:"/internal/orgs/:id/avatar",MEMBERS:{LIST:"/internal/orgs/:id/members",ADD:"/internal/orgs/:id/members",UPDATE:"/internal/orgs/:id/members/:userId",REMOVE:"/internal/orgs/:id/members/:userId"},INVITATIONS:{LIST:"/internal/orgs/:id/invitations",SEND:"/internal/orgs/:id/invitations",ACCEPT:"/internal/invitations/:token/accept",CANCEL:"/internal/invitations/:id"},FOLLOW:"/internal/orgs/:orgId/follow",FOLLOWERS:"/internal/orgs/:orgId/followers"},USER:{SETTINGS:"/internal/user/settings",AVATAR:"/internal/user/avatar",FOLLOW:"/internal/users/:userId/follow",FOLLOWERS:"/internal/users/:userId/followers",FOLLOWING:"/internal/users/:userId/following"},USAGE:{LIST:"/internal/usage",SUMMARY:"/internal/usage/summary"},TASTE:{PACKAGES:{LIST:"/internal/taste/packages",BATCH:"/internal/taste/packages",GET:"/internal/taste/packages/:namespace/:packageName",FILES:"/internal/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/internal/taste/packages/:namespace/:packageName/download",DELETE:"/internal/taste/packages/:namespace/:packageName",UPDATE:"/internal/taste/packages/:namespace/:packageName/update",STAR:"/internal/taste/packages/:namespace/:packageName/star",PIN:"/internal/taste/packages/:namespace/:packageName/pin"}}}},Re={ALPHA:{TASTE:{GET:new RegExp("/alpha/taste/[a-z0-9-]+"),UPDATE:new RegExp("/alpha/taste/[a-z0-9-]+/update"),DELETE:new RegExp("/alpha/taste/[a-z0-9-]+/rules/[a-z0-9-]+"),LIST:new RegExp("/alpha/taste/[a-z0-9-]+/rules")}},BETA:{TASTE_PACKAGES:{UPLOAD:new RegExp("^/beta/taste/packages/[a-zA-Z0-9_-]+$"),FILES:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}},INTERNAL:{ORGS:{GET:new RegExp("/internal/orgs/[a-zA-Z0-9_-]+"),FOLLOW:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/followers")},USER:{FOLLOW:new RegExp("/internal/users/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/users/[a-zA-Z0-9-]+/followers"),FOLLOWING:new RegExp("/internal/users/[a-zA-Z0-9-]+/following")},TASTE:{PACKAGES:{GET:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),FILES:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),DOWNLOAD:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download"),UPDATE:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/update"),STAR:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/star"),PIN:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pin")}}}};Object.values(Re.ALPHA.TASTE),Object.values(Re.BETA.TASTE_PACKAGES),Fe.ALPHA.GENERATE,Fe.ALPHA.AGENT.GENERATE,Fe.ALPHA.WHOAMI,Fe.ALPHA.NAMESPACES,Fe.ALPHA.SHARE.CREATE,Fe.ALPHA.SHARE.DELETE,Fe.ALPHA.SHARE.APPEND,Fe.ALPHA.DEVREL_THREAD.CREATE,Fe.ALPHA.DEVREL_THREAD.DELETE,Fe.ALPHA.DEVREL_THREAD.UPDATE,Fe.ALPHA.TASTE.LEARN,Fe.ALPHA.TASTE.DELETE,Fe.ALPHA.TASTE.GET,Fe.ALPHA.TASTE.UPDATE,Object.values(Fe.BETA.TASTE.PACKAGES),Object.values(Re.INTERNAL.ORGS),Object.values(Re.INTERNAL.USER),Object.values(Re.INTERNAL.TASTE.PACKAGES);var Me={INTERNAL:{PROFILE:{GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+"),PACKAGES:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages"),FOLLOWING:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/following"),FOLLOWERS:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/followers"),PACKAGE_GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+"),PACKAGE_DOWNLOAD:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+/download")}}};function getStudioAuthUrl(e){return"dev"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}Object.values(Me.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl");var Ne="anthropic";I.enum(["owner","admin","member"]);var je={SONNET_4_5:{id:"claude-sonnet-4-5-20250929",label:"Default",name:"Sonnet 4.5",description:"recommended"},OPUS_4_5:{id:"claude-opus-4-5-20251101",label:"Opus",name:"Opus 4.5",description:""}},Oe=je.SONNET_4_5.id;new Set([].map(e=>e.toLowerCase()));var Le,_e=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];(e=>{e.OAuth=D.object({type:D.literal("oauth"),refresh:D.string(),access:D.string(),expires:D.number()}),e.ApiKey=D.object({type:D.literal("api"),key:D.string()}),e.Info=D.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),n=__name(()=>y.join(T.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=t(),r="dev"===e?"models.dev.json":"staging"===e?"models.staging.json":"models.json";return y.join(n(),r)},"getAuthFile");async function get(e){try{const t=await P.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),a=r();await P.mkdir(o,{recursive:!0});let s={};try{const e=await P.readFile(a,"utf-8");s=JSON.parse(e)}catch{}s[e]=t,await P.writeFile(a,JSON.stringify(s,null,2)),await P.chmod(a,384)}async function remove(e){const t=r();try{const n=await P.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await P.unlink(t):(await P.writeFile(t,JSON.stringify(r,null,2)),await P.chmod(t,384))}catch{}}async function list2(){try{const e=await P.readFile(r(),"utf-8");return JSON.parse(e)}catch{return{}}}e.get=get,__name(get,"get"),e.set=set,__name(set,"set"),e.remove=remove,__name(remove,"remove"),e.list=list2,__name(list2,"list")})(Le||(Le={}));var Ue,Be="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing";async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=ee(n),a=await o.metadata();if(!a.width||!a.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const s=1200;let i,c,{width:l,height:d}=a;(l>s||d>s)&&(l>d?(d=Math.round(d*s/l),l=s):(l=Math.round(l*s/d),d=s)),t.includes("png")&&a.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:u,compressionRatio:r/u}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}function processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};let r=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");return r=r.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),{isPasteStart:t,isPasteEnd:n,cleanedContent:r}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}(e=>{const t="9d1c250a-e61b-44d9-88ed-5944d1962f5e",n="https://console.anthropic.com/v1/oauth/token",r="https://console.anthropic.com/oauth/code/callback";function generateCodeVerifier(){return $.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return $.createHash("sha256").update(e).digest("base64url")}function generateState(){return $.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens(e,o,a){const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:a})});if(!s.ok){const e=await s.text();throw new Error(`Token exchange failed: ${e}`)}const i=await s.json();await Le.set("anthropic",{type:"oauth",refresh:i.refresh_token,access:i.access_token,expires:Date.now()+1e3*i.expires_in})}async function refreshAccessToken(){const e=await Le.get("anthropic");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return e.access;try{const r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t,refresh_token:e.refresh})});if(!r.ok)return void await Le.remove("anthropic");const o=await r.json();return await Le.set("anthropic",{type:"oauth",refresh:o.refresh_token,access:o.access_token,expires:Date.now()+1e3*o.expires_in}),o.access_token}catch(e){return void await Le.remove("anthropic")}}}async function getValidAccessToken(){const e=await Le.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens,__name(exchangeCodeForTokens,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken,__name(refreshAccessToken,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken,__name(getValidAccessToken,"getValidAccessToken")})(Ue||(Ue={})),__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var We={"command-code":{id:"command-code",displayName:"Command Code",description:"recommended",requiresAuth:!1},anthropic:{id:"anthropic",displayName:"Anthropic",description:"Claude Pro/Max",requiresAuth:!0,hidden:!0,authComponent:__name(({onSuccess:e,onCancel:t})=>{const[n,r]=B(""),[o,a]=B(null),[s,i]=B(!1),[c,l]=B(null),[d,u]=B(!0),[m,g]=B(!1),[p,f]=B(!1);W(()=>{const{url:e,verifier:t,state:n}=Ue.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=H(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}r(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}},[p]);J((e,n)=>{n.escape&&t(),d&&!m&&("y"===e||"Y"===e?o&&(h(o.url).catch(console.error),g(!0),u(!1)):"n"!==e&&"N"!==e||t())});const w=__name(async()=>{if(n.trim()&&o&&!s){i(!0),l(null);try{const t=n.split("#")[0].trim();await Ue.exchangeCodeForTokens(t,o.verifier,o.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){l(e instanceof Error?e.message:"Authentication failed"),i(!1)}}},"handleSubmit");return d&&!m?U.createElement(q,{flexDirection:"column"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),U.createElement(q,{marginBottom:1},U.createElement(K,null,"Open the Anthropic auth page?",U.createElement(K,{dimColor:!0}," (Y/n)")))):U.createElement(q,{flexDirection:"column"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"After authorizing, copy the code and paste it below:")),c&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"red"},"Error: ",c)),U.createElement(q,null,U.createElement(K,null,"Authorization code: "),U.createElement(Q,{mask:"*",focus:!0,value:n,onChange:y,onSubmit:w,placeholder:"Paste code here..."})),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth"),checkAuth:__name(async()=>!!await Ue.getValidAccessToken(),"checkAuth")}};function getProviderDisplayName(e){if(!e)return"None";const t=We[e];return t?.displayName||e}function getProviderConfig(e){return We[e]}function isInternalFlagPresent(){return process.argv.includes(Pe)}function getProviderOptions(){const e=isInternalFlagPresent();return Object.values(We).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}async function loadUserConfig(){try{const e=Ke();return parseJSON(await S.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=Ke();F.writeFileSync(t,JSON.stringify(e,null,2)),F.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=getConfiguredModel(),r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){return isInternalFlagPresent()?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),!0):(await loadUserConfig()).forceOAuth??!1}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error('OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.')}function getConfiguredModel(){try{const e=Ke();return(parseJSON(F.readFileSync(e,"utf-8"))||{}).model??Oe}catch{return Oe}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalFlagPresent,"isInternalFlagPresent"),__name(getProviderOptions,"getProviderOptions"),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel");var ze=__name(()=>y.join(T.homedir(),".commandcode"),"getAuthDir"),Ge=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),He=__name(()=>{const e=Ge();return"dev"===e?"--dev":"staging"===e?"--staging":""},"getEnvFlag"),Ve=__name(e=>{const t=e??Ge(),n="dev"===t?"auth.dev.json":"staging"===t?"auth.staging.json":"auth.json";return y.join(ze(),n)},"getAuthFile"),qe=__name(()=>y.join(T.homedir(),".commandcode"),"getConfigDir"),Ke=__name(e=>{const t=e??Ge(),n="dev"===t?"config.dev.json":"staging"===t?"config.staging.json":"config.json";return y.join(qe(),n)},"getConfigFile"),Je=__name(e=>{const t=e??Ge(),n="dev"===t?"models.dev.json":"staging"===t?"models.staging.json":"models.json";return y.join(qe(),n)},"getModelsFile");async function loginAction(){try{const e=Ge(),t=getStudioAuthUrl(e);console.log("\n"),s.intro(heading({text:"Command Code Authentication",sub:""}));const n=await i({message:`Open the authentication page? ${p.dim("— copy your API key from there and paste it here.")}`});c(n)&&(l(`${o.cross} Login cancelled.`),process.exit(0)),n&&(await h(t),d(p.yellow("Please copy your API key from the opened page and paste it here.")));const r=await u({message:"Paste your API key:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(0)),r.trim()||(console.log(`${o.cross} No API key provided.`),process.exit(1));const a=ze(),f=Ve(e);await P.mkdir(a,{recursive:!0}),await P.writeFile(f,JSON.stringify({apiKey:r},null,2)),await P.chmod(f,384);const y=getProviderOptions();let w;if(1===y.length)w=y[0].value;else{const e=await m({message:"Select provider",options:y});if(c(e)&&(l(`${o.cross} No provider selected.`),process.exit(0)),w=e,"anthropic"===w){const e=await m({message:"Login method",options:[{value:"anthropic-oauth",label:"Claude Pro/Max"}]});c(e)?l(`${o.cross} No login method selected.`):"anthropic-oauth"===e&&await anthropicAuth()}}await updateUserConfig({provider:w});let E=`You are logged in. API key is stored in ~/.commandcode/${"dev"===e?"auth.dev.json":"staging"===e?"auth.staging.json":"auth.json"}. Run \`cmd\` to get started.`;g(p.green(E)),process.exit(0)}catch(e){console.error(`${o.cross} Login failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function anthropicAuth(){try{const{url:e,verifier:t,state:n}=Ue.createAuthorizationUrl();await i({message:"Open the Anthropic auth page?"})&&(await h(e),d(p.yellow("Please copy your authorization code from the opened page and paste it here.")));const r=await u({message:"Paste your authorization code:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(1)),r.trim()||(console.log(`${o.cross} No authorization code provided`),process.exit(1));const a=r.split("#")[0].trim();return await Ue.exchangeCodeForTokens(a,t,n),!0}catch(e){l(`${o.cross} Anthropic OAuth failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function logoutAction(){try{const e=Ge(),t=Ve(e),n=Je(e);try{await P.unlink(t)}catch(e){}try{const e=await loadUserConfig(),{provider:t,...n}=e;await saveUserConfig(n)}catch(e){}try{await P.unlink(n)}catch(e){}g(p.green("Successfully logged out from Command Code")),process.exit(0)}catch(e){l(`${o.cross} Logout failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function getAuthKey(e){try{const t=Ve(e),n=await P.readFile(t,"utf-8");return JSON.parse(n).apiKey||null}catch{return null}}async function statusAction(){try{const e=Ge();await getAuthKey(e)||(l(`${o.cross} Not authenticated. Please login using "cmd auth login".`),process.exit(1)),g(p.green(`${o.tick} Authenticated with Command Code`)),process.exit(0)}catch(e){l(`${o.cross} Status check failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}__name(loginAction,"loginAction"),__name(anthropicAuth,"anthropicAuth"),__name(logoutAction,"logoutAction"),__name(getAuthKey,"getAuthKey"),__name(statusAction,"statusAction");var Ye=new e("auth").description("Manage authentication with Command Code");Ye.command("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Ye.command("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Ye.command("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);var Ze=new e("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Xe=new e("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Qe=new e("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${T.platform()}-${T.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return R.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function isGitRepository(){try{return n("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return n("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=n("git branch -r",{encoding:"utf8",cwd:getCurrentWorkingDirectory()});return e.includes("origin/main")?"main":e.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=n("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),r=t.filter(e=>e.startsWith(" M")).length,o=t.filter(e=>e.startsWith("A ")).length,a=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,i=[];return r>0&&i.push(`M ${r}`),o>0&&i.push(`A ${o}`),a>0&&i.push(`D ${a}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=n("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getRootDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[]}}function detectTerminal(){const e=process.env;if(e.TERM_PROGRAM){const t=e.TERM_PROGRAM;if("vscode"===t)return{name:"Visual Studio Code",type:"vscode",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("iTerm.app"===t)return{name:"iTerm2",type:"iterm2",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION,iterm2Profile:e.ITERM_PROFILE}};if("Apple_Terminal"===t)return{name:"macOS Terminal",type:"terminal",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("WarpTerminal"===t)return{name:"Warp",type:"warp",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("Hyper"===t)return{name:"Hyper",type:"hyper",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}function isDisableOAuthFlagPresent(){return process.argv.includes(Ae)}function formatDate(e=new Date){return e.toISOString().split("T")[0]}function parseJSON(e){try{return JSON.parse(e)}catch{return null}}async function getConfiguredProvider(){try{const e=Ke(),t=await P.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,a=isInternalFlagPresent();return isDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):a||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!e.ctrl||"o"!==t)}__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext"),__name(detectTerminal,"detectTerminal"),__name(getIsTerminalIterm2,"getIsTerminalIterm2"),__name(isDisableOAuthFlagPresent,"isDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut");var et=new Se("Config"),tt=f.join(C.homedir(),".commandcode-config.json");async function loadConfig(){try{return parseJSON(await S.readFile(tt,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await S.writeFile(tt,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var nt=new e("config").description("Manage CLI configuration").addCommand(new e("get").description("Get a configuration value").argument("<key>","Configuration key").action(async e=>{const t=(await loadConfig())[e];void 0!==t?et.info(`${e}: ${JSON.stringify(t)}`):et.warn(`Key "${e}" not found in configuration`)})).addCommand(new e("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action(async(e,t)=>{"provider"!==e||"anthropic"!==t||isInternalFlagPresent()||(et.error('Invalid provider "anthropic". Available provider: command-code'),process.exit(1));const n=await loadConfig();let r=t;"true"===t?r=!0:"false"===t?r=!1:isNaN(Number(t))||(r=Number(t)),n[e]=r,await saveConfig(n),et.success(`Set ${e} = ${JSON.stringify(r)}`)})).addCommand(new e("list").description("List all configuration values").action(async()=>{const e=await loadConfig();0===Object.keys(e).length?et.info("No configuration values set"):(et.info("Current configuration:"),Object.entries(e).forEach(([e,t])=>{console.log(` ${e}: ${JSON.stringify(t)}`)}))})).addCommand(new e("reset").description("Reset all configuration").action(async()=>{await saveConfig({}),et.success("Configuration reset successfully")})),rt=new Se("Info"),ot=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(rt.info("System Information:"),console.log("-------------------"),console.log(`${o.info} Date: ${formatDate()}`),console.log(`${o.info} Platform: ${C.platform()}`),console.log(`${o.info} Architecture: ${C.arch()}`),console.log(`${o.info} CPUs: ${C.cpus().length}`),console.log(`${o.info} Memory: ${Math.round(C.totalmem()/1024/1024/1024)} GB`),console.log(`${o.info} Home Directory: ${C.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),C.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=C.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}rt.success("Information displayed successfully!")});function getApiBaseUrl(){const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(getApiBaseUrl,"getApiBaseUrl");var at=class _APIError extends Error{static{__name(this,"APIError")}status;headers;error;code;param;type;request_id;constructor(e,t,n,r){super(_APIError.makeMessage(e,t,n)),this.status=e,this.headers=r,this.request_id=r?.["lb-request-id"];const o=t;this.error=o,this.code=o?.code,this.status=o?.status}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e)return new st({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new it(e,o,n,r);case 401:return new ct(e,o,n,r);case 403:return new lt(e,o,n,r);case 404:return new dt(e,o,n,r);case 409:return new ut(e,o,n,r);case 422:return new mt(e,o,n,r);case 429:return new gt(e,o,n,r);default:return e>=500?new pt(e,o,n,r):new _APIError(e,o,n,r)}}},st=class extends at{static{__name(this,"APIConnectionError")}status=void 0;constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},it=class extends at{static{__name(this,"BadRequestError")}status=400},ct=class extends at{static{__name(this,"AuthenticationError")}status=401},lt=class extends at{static{__name(this,"PermissionDeniedError")}status=403},dt=class extends at{static{__name(this,"NotFoundError")}status=404},ut=class extends at{static{__name(this,"ConflictError")}status=409},mt=class extends at{static{__name(this,"UnprocessableEntityError")}status=422},gt=class extends at{static{__name(this,"RateLimitError")}status=429},pt=class extends at{static{__name(this,"InternalServerError")}},ht=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=await this.buildHeaders({headers:e.headers});let o;try{o=await this.makeRequest({url:n,options:e,headers:r})}catch(e){throw new st({cause:e instanceof Error?e:void 0})}return o.ok||await this.handleErrorResponse({response:o}),e.stream?o.body:o.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const a=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),a}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={};throw e.headers.forEach((e,t)=>{n[t]=e}),at.generate(e.status,t,e.statusText,n)}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"})}};async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new ht({baseUrl:e});return await t.get({endpoint:Fe.ALPHA.WHOAMI})}async function whoamiAction(){try{await getAuthKey()||(console.log(`${o.cross} ${p.red('Not authenticated. Please login using "cmd auth login"')}`),process.exit(1));const e=await getAuthenticatedEntity();e.success&&e.user||(console.log(`${o.cross} ${p.red("Failed to fetch user info")}`),process.exit(1)),console.log(`\n${p.bold("User Information:")}`),console.log(`${o.info} Name: ${p.cyan(e.user.name)}`),console.log(`${o.info} Email: ${p.cyan(e.user.email)}`),console.log(`${o.info} Username: ${p.cyan(e.user.userName)}`),e.org&&(console.log(`\n${p.bold("Organization:")}`),console.log(`${o.info} Name: ${p.cyan(e.org.name)}`),console.log(`${o.info} Login: ${p.cyan(e.org.login)}`)),console.log("")}catch(e){console.log(`${o.cross} ${p.red(`Error: ${e instanceof Error?e.message:"Unknown error"}`)}`),process.exit(1)}}__name(getAuthenticatedEntity,"getAuthenticatedEntity"),__name(whoamiAction,"whoamiAction");var ft=new e("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function getTastePath(e){const{target:t}=e;switch(t){case"local-project":return f.join(process.cwd(),".commandcode","taste");case"local-global":return f.join(C.homedir(),".commandcode","taste");case"remote-project":case"remote-user":throw new Error(`Remote storage not yet implemented: ${t}`);default:throw new Error(`Unknown storage target: ${t}`)}}function getRootTasteFile(e){const{target:t}=e;return f.join(getTastePath({target:t}),"taste.md")}function getCategoryPath(e){const{target:t,category:n}=e;return f.join(getTastePath({target:t}),n)}function getCategoryTasteFile(e){const{target:t,category:n}=e;return f.join(getCategoryPath({target:t,category:n}),"taste.md")}function parseTasteBuckets(e){const{content:t,sourcePath:n}=e,r=[],o=t.split(/^# /gm).filter(e=>e.trim());for(const e of o){const t=e.split("\n"),o=t[0].trim();if(e.includes("See ["))continue;const a=[];for(const e of t){const t=parseLearning({line:e});t&&a.push(t)}a.length>0&&r.push({category:normalizeCategory({category:o}),learnings:a,sourcePath:n})}return r}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatBucket(e){const{bucket:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),__name(parseTasteBuckets,"parseTasteBuckets"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),__name(formatBucket,"formatBucket");var yt="# Taste (Continuously Learned by CommandCode.ai)",wt=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return wt.test(t)?t.replace(wt,`$1${yt}`):t}__name(migrateHeader,"migrateHeader");var Et=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!M(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(M(n)){let e=await S.readFile(n,"utf-8");const r=migrateHeader({content:e});r!==e&&(await S.writeFile(n,r,"utf-8"),e=r);const o=parseTasteBuckets({content:e,sourcePath:n});t.push(...o)}const r=await S.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(M(n)){let r=await S.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await S.writeFile(n,o,"utf-8"),r=o);const a=parseTasteBuckets({content:r,sourcePath:n});for(const t of a)t.category=e.name;t.push(...a)}}return t}async getBucket(e){const{category:t}=e;return(await this.getAllBuckets()).find(e=>e.category===t)||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await S.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,a=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:a}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:a})}async removeBucket(e){const{category:t}=e,n=getRootTasteFile({target:this.target});let r=null;if(M(n)){let e=await S.readFile(n,"utf-8");e=migrateHeader({content:e});const o=e.split("\n");let a=-1,s=-1;const i=new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let e=0;e<o.length;e++)if(i.test(o[e])){a=e;for(let t=e+1;t<o.length;t++)if(o[t].startsWith("# ")){let n=t-1;for(;n>e&&""===o[n].trim();)n--;s=n;break}-1===s&&(s=o.length-1);break}if(-1!==a){const e=o.slice(0,a),t=s<o.length-1?o.slice(s+1):[];r={before:e.join("\n").trim(),after:t.join("\n").trim()};const i=[...e,...t].join("\n").trim();""===i?await S.rm(n,{force:!0}):await S.writeFile(n,i+"\n","utf-8")}}const o=getCategoryTasteFile({target:this.target,category:t}),a=f.dirname(o);return M(a)&&await S.rm(a,{recursive:!0,force:!0}),r}async writeToRoot(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=formatBucket({bucket:t});if(r){let e=r.before;e&&!e.trim().startsWith(yt)&&(e=yt+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o.trim(),r.after&&(e+="\n\n"+r.after),await S.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";M(n)&&(e=await S.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(yt)||(e=yt+"\n\n"+e):e=yt+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await S.writeFile(n,e.trim()+"\n","utf-8")}}async writeToSubdirectory(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=getCategoryTasteFile({target:this.target,category:t.category}),a=f.dirname(o);await S.mkdir(a,{recursive:!0});const s=formatBucket({bucket:t});await S.writeFile(o,s,"utf-8");const i=`# ${t.category}\nSee [${t.category}/taste.md](${t.category}/taste.md)\n`;if(r){let e=r.before;e=migrateHeader({content:e}),e&&!e.trim().startsWith(yt)&&(e=yt+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i.trim(),r.after&&(e+="\n\n"+r.after),await S.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";M(n)&&(e=await S.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(yt)||(e=yt+"\n\n"+e):e=yt+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i,await S.writeFile(n,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return M(e)}},bt=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!M(e))return[];const t=[],n=await S.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(M(n)){let r=await S.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await S.writeFile(n,o,"utf-8"),r=o);const a=parseTasteBuckets({content:r,sourcePath:n});for(const t of a)t.category=e.name;t.push(...a)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});if(!M(n))return null;let r=await S.readFile(n,"utf-8");const o=migrateHeader({content:r});return o!==r&&(await S.writeFile(n,o,"utf-8"),r=o),parseTasteBuckets({content:r,sourcePath:n})[0]||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await S.mkdir(n,{recursive:!0});const r=getCategoryTasteFile({target:this.target,category:t.category}),o=f.dirname(r);await S.mkdir(o,{recursive:!0});const a=formatBucket({bucket:t});await S.writeFile(r,a,"utf-8")}async deleteBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t}),r=f.dirname(n);M(r)&&await S.rm(r,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await S.stat(n.sourcePath)).mtime}catch{e=new Date}t.push({category:n.category,learningCount:n.learnings.length,lastUpdated:e,filePath:n.sourcePath})}return t}exists(){const e=getTastePath({target:this.target});return M(e)}};async function prepareUploadFormData(e){const{packageName:t,bucket:n,description:r,type:o="category",isPublic:a=!1}=e,s=new FormData;if(s.append("name",t),r&&s.append("description",r),s.append("type",o),s.append("isPublic",String(a)),"category"===o){const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",r)}else{const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",r);const o=getTastePath({target:"local-project"}),a=f.join(o,n.category);if(M(a)){const e=getCategoryTasteFile({target:"local-project",category:n.category});if(M(e)){const t=await S.readFile(e,"utf-8"),r=new Blob([t],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});s.append(`files[${n.category}/taste.md]`,o)}}}return s}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r,isPublic:o=!1}=e,a=new FormData;a.append("name",n),r&&a.append("description",r),a.append("type","project"),a.append("isPublic",String(o));const s=getRootTasteFile({target:"local-project"});if(M(s)){const e=await S.readFile(s,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});a.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(M(t)){const n=await S.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});a.append(`files[${e.category}/taste.md]`,o)}}return a}function parseTasteContent(e){const t=[],n=e.split("\n");for(const e of n){const n=e.trim();if(!n||n.startsWith("#")||!n.startsWith("-"))continue;const r=n.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(r){const e=r[1].trim(),n=parseFloat(r[2]);e&&!isNaN(n)&&t.push({text:e,confidence:n})}}return t}__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),__name(parseTasteContent,"parseTasteContent");var vt=class{static{__name(this,"RemoteStorage")}async getAllBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${Fe.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const a=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&a.push(t)}catch(t){console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return a}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=getApiBaseUrl(),o=`${r}${Fe.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",t).replace(":packageName",n)}`;try{const e=await fetch(o,{method:"GET"});if(e.ok){const{data:t}=await e.json();return{type:t.type||"category",files:t.files||[],isPublic:!0}}if(404!==e.status){let t="Failed to download taste package";try{const n=await e.json();t=n.error?.message||n.message||`${t} (${e.status})`}catch{t=`${t} (${e.status})`}throw new Error(t)}if(!await getAuthKey())throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`")}catch(e){if(e instanceof Error)throw e}const a=await getAuthKey();if(!a)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");const s=`${r}${Fe.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${a}`}});if(!i.ok){if(404===i.status)return null;let e="Failed to download taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:c}=await i.json();return{type:c.type||"category",files:c.files||[],isPublic:c.isPublic??!1}}async getBucket(e){const{category:t}=e;if(!await getAuthKey())throw new Error("No API key found. Please authenticate with: cmd login");const n=await getAuthenticatedEntity();if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");const r=n.user.userName;return this.downloadPackageToBucket({namespace:r,packageName:t})}async downloadPackageToBucket(e){const{namespace:t,packageName:n}=e,r=await this.downloadPackage({namespace:t,packageName:n});if(!r)return null;const o=r.files||[];if(0===o.length)return null;const a=o.find(e=>"taste.md"===e.file);if(!a)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async writeBucket(e){const{bucket:t,namespace:n,isPublic:r=!1}=e,o=await getAuthKey();if(!o)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category",isPublic:r}),s=`${getApiBaseUrl()}${Fe.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:a});if(!i.ok){let e="Failed to upload taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}await i.json()}async writeBuckets(e){const{buckets:t,projectName:n,namespace:r,isPublic:o=!1}=e,a=await getAuthKey();if(!a)throw new Error("No API key found. Please authenticate with: cmd login");const s=await prepareMultiplePackagesUpload({buckets:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${Fe.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:s});if(!c.ok){let e="Failed to upload taste packages";try{const t=await c.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}await c.json()}async deleteBucket(e){throw new Error("Remote storage not yet implemented")}async listBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${Fe.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}async importBucket(e){throw new Error("Remote storage not yet implemented")}};function mergeLearnings(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},o=new Map;for(const e of n)o.set(e.text,e);const a=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(a.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(a.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(a.values()),details:r}}__name(mergeLearnings,"mergeLearnings");var kt=/confidence:/i;function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const o=t.split("\n"),a=[];let s=0;for(;s<o.length;){const e=o[s],t=s+1,n=e.trim();if(n.startsWith("-"))if(kt.test(n))a.push({text:e,originalLineNum:t}),s++;else{let n=e,r=s+1;for(;r<o.length;){const e=o[r].trim();if(e.startsWith("#")||e.startsWith("-"))break;if(e.length>0&&(n=n+" "+e),kt.test(e)){r++;break}r++}a.push({text:n,originalLineNum:t}),s=r}else a.push({text:e,originalLineNum:t}),s++}let i=null,c=null,l=0;for(const{text:e,originalLineNum:t}of a){if(!e.trim())continue;if(e.trim().startsWith("# ")){if("# Taste (Continuously Learned by CommandCode.ai)"===e.trim()||"# Taste (Continuously Learned by CommandCode)"===e.trim())continue;i&&0===l&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),i=e.trim().substring(2).trim(),c=t,l=0;continue}if(e.trim().startsWith("-")){if(!i){r.push({line:t,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'});continue}l++;const n=validateLearningLine({line:e.trim(),lineNum:t});r.push(...n);continue}const n=e.trim();/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i.test(n)||r.push({line:t,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"})}return i&&0===l&&c&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),buildResult({issues:r,filePath:n})}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=n+3;for(let e=n+1;e<t.length&&e<r;e++){const n=t[e];if(n.trim().startsWith("# "))break;if(n.includes("See [")&&n.includes("taste.md"))return!0}return!1}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!kt.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 a=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),s=a.length>0?a[a.length-1]:null;if(!s)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=s[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;c<0||c>1?r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}):0===c&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});let l="";return l=s&&void 0!==s.index?o.substring(0,s.index).trim():o.trim(),l&&0!==l.length?l.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}):r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),o=t.filter(e=>"warning"===e.severity),a=0===r.length;let s;if(0===t.length)s=`✓ ${n} is valid`;else{const e=[];r.length>0&&e.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&e.push(`${o.length} warning${o.length>1?"s":""}`),s=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:a,issues:t,summary:s}}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${te.green(e)} ${te.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity),a=[r.length>0?te.red(t.summary):te.yellow(t.summary),""];if(r.length>0){a.push(te.bold(te.red("Errors:")));for(const e of r){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.red(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}if(o.length>0){a.push(te.bold(te.yellow("Warnings:")));for(const e of o){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.yellow(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}return a.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:t,namespace:n,localBucket:r,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${r.learnings.length} learnings`),console.log(`Remote: ${a} learnings (from ${n})\n`);const i=await s.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} → ${a} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptPushStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteBucket:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${a.learnings.length} learnings (in ${n})\n`);const i=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${a.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalBucket:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in global storage\n`)),console.log(`Local: ${n} learnings`),console.log(`Global: ${r.learnings.length} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function promptGlobalPullStrategy(e){const{packageName:t,localBucket:n,globalLearningsCount:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${n.learnings.length} learnings`),console.log(`Global: ${r} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function promptTypeMismatchStrategy(e){const{packageName:t,namespace:n,localType:r,remoteType:a,localLearningsCount:i,remoteLearningsCount:c}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, skipping push`)),"skip";const l=`https://commandcode.ai/${n}/${t}`;console.log(te.yellow(`\n${o.warning} Pushing local project taste to individual package '${t}'\n`)),console.log(`Local: ${t} (${i} learnings)`),console.log(`Remote: ${t} (${c} learnings) in ${n}\n`),console.log(`Review package: ${te.cyan(l)}\n`);const d=await s.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});return s.isCancel(d)&&(s.cancel("Operation cancelled"),process.exit(0)),d}async function promptSameTypeStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, skipping push`)),"skip";const i=`https://commandcode.ai/${n}/taste/${t}`;console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${a} learnings\n`),console.log(`Review taste package: ${te.cyan(i)}\n`);const c=await s.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 (${a} → ${r} learnings)`}],initialValue:"skip"});return s.isCancel(c)&&(s.cancel("Operation cancelled"),process.exit(0)),c}async function push(e){const t=void 0!==e.isPublic,{buckets:n,target:r,overwrite:o=!1,isPublic:a=!1}=e,s=new Et,i={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!s.exists())return i.success=!1,i.errors.push({bucket:"all",error:"No taste directory found in project"}),i;const c=await s.getAllBuckets();if(0===c.length)return i.success=!1,i.errors.push({bucket:"all",error:"No taste packages found in project"}),i;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){i.success=!1;const n=formatValidationIssues({result:t,verbose:!0});i.errors.push({bucket:e.category,error:`Validation failed for taste package in project:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in project has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(i.errors.length>0)return i;const l=n.length>0?c.filter(e=>n.includes(e.category)):c;if(n.length>0&&0===l.length){i.success=!1;for(const e of n)i.errors.push({bucket:e,error:"Taste package not found in project"});return i}let d,u;if("remote-project"===r||"remote-user"===r)try{const e=await getAuthenticatedEntity();e.success&&e.user?.userName&&(d=e.user.userName)}catch{}if("remote-project"===r&&0===n.length){const e=f.basename(process.cwd()),n=new vt;if(!d)return i.success=!1,i.errors.push({bucket:"all",error:"Failed to get user namespace for remote push"}),i;try{const r=await n.downloadPackage({namespace:d,packageName:e});let s="overwrite";const c="project",u=r?.type??"category",m=l.reduce((e,t)=>e+t.learnings.length,0),g=r?.files?r.files.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0):0;if(s=o?"overwrite":r?u!==c?await promptTypeMismatchStrategy({packageName:e,namespace:d,localType:c,remoteType:u,localLearningsCount:m,remoteLearningsCount:g}):await promptSameTypeStrategy({packageName:e,namespace:d,type:c,localLearningsCount:m,remoteLearningsCount:g}):"overwrite","skip"===s)return i;await n.writeBuckets({buckets:l,projectName:e,namespace:d,type:"project",isPublic:t?a:r?.isPublic??!1});for(const e of l)i.bucketsPushed.push(e.category),i.filePaths[e.category]=`${d}/${e.category}`,i.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if(r)for(const e of l)i.overwritten.push(e.category);return i}catch(e){return i.success=!1,i.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),i}}switch(r){case"local-global":u=new bt;break;case"remote-project":case"remote-user":u=new vt;break;default:return i.success=!1,i.errors.push({bucket:"all",error:`Invalid target: ${r}`}),i}for(const e of l)try{const t=await u.getBucket({category:e.category});let n;if(n=o?"overwrite":t&&"local-global"===r?await promptGlobalPushStrategy({packageName:e.category,localLearningsCount:e.learnings.length,globalBucket:t}):"merge","skip"===n)continue;if("overwrite"===n){if("local-global"===r)await u.writeBucket({bucket:e});else{if(!d)throw new Error("Failed to get user namespace for remote push");await u.writeBucket({bucket:e,namespace:d,isPublic:a})}i.bucketsPushed.push(e.category),i.overwritten.push(e.category)}else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},i.mergeDetails[e.category]=r.details}else n=e,i.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if("local-global"===r)await u.writeBucket({bucket:n});else{if(!d)throw new Error("Failed to get user namespace for remote push");await u.writeBucket({bucket:n,namespace:d,isPublic:a})}i.bucketsPushed.push(e.category)}if("local-global"===r){const t=getCategoryTasteFile({target:"local-global",category:e.category});i.filePaths[e.category]=t}else"remote-project"!==r&&"remote-user"!==r||!d||(i.filePaths[e.category]=`${d}/${e.category}`)}catch(t){i.success=!1,i.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return i}async function pull(e){const{buckets:t,source:n,overwrite:r=!1}=e,o=new Et,a={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},s=__name(()=>{switch(n){case"local-global":return"global";case"remote-project":return"remote project";case"remote-user":return"remote";default:return"source"}},"getSourceName")();let i,c;switch(n){case"local-global":i=new bt;break;case"remote-project":case"remote-user":i=new vt;break;default:return a.success=!1,a.errors.push({bucket:"all",error:`Invalid source: ${n}`}),a}try{c=await i.getAllBuckets()}catch(e){return a.success=!1,a.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),a}if(0===c.length)return a.success=!1,a.errors.push({bucket:"all",error:`No taste packages found in ${s}`}),a;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){a.success=!1;const n=formatValidationIssues({result:t,verbose:!0});a.errors.push({bucket:e.category,error:`Validation failed for taste package in ${s}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${s} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(a.errors.length>0)return a;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){a.success=!1;for(const e of t)a.errors.push({bucket:e,error:`Taste package not found in ${s}`});return a}for(const e of l)try{const t=await o.getBucket({category:e.category});let s;if(s=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===s)continue;if("overwrite"===s)await o.writeBucket({bucket:e}),a.bucketsPulled.push(e.category),a.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},a.mergeDetails[e.category]=r.details}else n=e,a.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});a.filePaths[e.category]=i}catch(t){a.success=!1,a.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return a}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new Et,a=new vt,s={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await a.downloadPackage({namespace:t,packageName:n});if(!e)return s.success=!1,s.errors.push({bucket:n,error:"Taste package not found in remote"}),s;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){s.success=!1;const r=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:n,error:`Validation failed for ${e.file}:\n${r}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s})}catch(e){s.success=!1,s.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return s}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(i){const e=parseTasteBuckets({content:i.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processBucket({bucket:t,namespace:r,overwrite:o,targetStorage:a,result:s})}for(const e of t){if("taste.md"===e.file)continue;const t=e.file.replace("/taste.md",""),i={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processBucket({bucket:i,namespace:r,overwrite:o,targetStorage:a,result:s})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:a}=e;try{const e=await o.getBucket({category:t.category});let s;if(s=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===s)return void a.skipped.push(t.category);if("overwrite"===s)await o.writeBucket({bucket:t}),a.bucketsPulled.push(t.category),a.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},a.mergeDetails[t.category]=r.details}else n=t,a.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});a.filePaths[t.category]=i}catch(e){a.success=!1,a.errors.push({bucket:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullCategoryPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return s.success=!1,void s.errors.push({bucket:n,error:"No taste.md file found in category package"});const c={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processBucket({bucket:c,namespace:r,overwrite:o,targetStorage:a,result:s})}async function pushRemote(e){const{namespace:t,packageName:n,overwrite:r=!1,isPublic:o=!1}=e,a=new Et,s=new vt,i={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return i.success=!1,i.errors.push({bucket:n,error:"No taste directory found in project"}),i;try{const e=await a.getBucket({category:n});if(!e)return i.success=!1,i.errors.push({bucket:n,error:`Taste package '${n}' not found in local project`}),i;const c=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!c.valid){i.success=!1;const e=formatValidationIssues({result:c,verbose:!0});return i.errors.push({bucket:n,error:`Validation failed:\n${e}`}),i}if(c.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${n}' has validation warnings:\n`);const e=formatValidationIssues({result:c,verbose:!0});console.warn(e+"\n")}const l=await s.downloadPackageToBucket({namespace:t,packageName:n});let d;if(d=r?"overwrite":l?await promptPushStrategy({packageName:n,namespace:t,localLearningsCount:e.learnings.length,remoteBucket:l}):"merge","skip"===d)return i;if("overwrite"===d)await s.writeBucket({bucket:e,namespace:t,isPublic:o}),i.bucketsPushed.push(n),i.overwritten.push(n);else{let r;if(l){const t=mergeLearnings({source:e.learnings,target:l.learnings});r={...e,learnings:t.merged},i.mergeDetails[n]=t.details}else r=e,i.mergeDetails[n]={added:e.learnings.length,updated:0,unchanged:0};await s.writeBucket({bucket:r,namespace:t,isPublic:o}),i.bucketsPushed.push(n)}i.filePaths[n]=`${t}/${n}`}catch(e){i.success=!1,i.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return i}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new Et;break;case"local-global":n=new bt;break;case"remote-project":case"remote-user":n=new vt;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof bt||n instanceof vt?await n.listBuckets():(await n.getAllBuckets()).map(e=>({category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}))}async function deleteBuckets(e){const{buckets:t,location:n}=e,r={success:!0,bucketsDeleted:[],errors:[]};let o;switch(n){case"local-global":o=new bt;break;case"remote-project":case"remote-user":o=new vt;break;case"local-project":return r.success=!1,r.errors.push({bucket:"all",error:"Cannot delete from local project via sync. Use taste clear instead."}),r;default:return r.success=!1,r.errors.push({bucket:"all",error:`Invalid location: ${n}`}),r}if(0===t.length)return r.success=!1,r.errors.push({bucket:"all",error:"No taste packages specified for deletion"}),r;for(const e of t)try{await o.deleteBucket({category:e}),r.bucketsDeleted.push(e)}catch(t){r.success=!1,r.errors.push({bucket:e,error:t instanceof Error?t.message:String(t)})}return r}async function lint(e){const{packages:t,target:n}=e,r={success:!0,filesLinted:[],errors:[],totalErrors:0,totalWarnings:0},o=getTastePath({target:n});if(!M(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const a=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});M(t)?a.push({path:t,displayName:`${e}/taste.md`}):(r.success=!1,r.errors.push({file:e,error:`Taste package '${e}' not found in ${"local-global"===n?"global":"project"}`}))}else{const e=getRootTasteFile({target:n});M(e)&&a.push({path:e,displayName:"taste.md"});const t=await S.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});M(t)&&a.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===a.length&&r.errors.length>0)return r;if(0===a.length)return r.success=!1,r.errors.push({file:"all",error:"No taste files found in "+("local-global"===n?"global":"project")}),r;for(const e of a){let t=await S.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await S.writeFile(e.path,n,"utf-8"),t=n);const o=validateTasteFile({content:t,filePath:e.displayName}),a=o.issues.filter(e=>"error"===e.severity),s=o.issues.filter(e=>"warning"===e.severity);r.totalErrors+=a.length,r.totalWarnings+=s.length,o.valid||(r.success=!1);const i=formatValidationIssues({result:o});r.filesLinted.push({file:e.displayName,valid:o.valid,errors:a.length,warnings:s.length,formatted:i})}return r}async function open3(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new Et;break;case"local-global":e=new bt;break;case"remote-project":case"remote-user":e=new vt;break;default:throw new Error(`Invalid target: ${n}`)}const r=(await e.getAllBuckets()).find(e=>e.category===t);if(!r)return{success:!1,error:`Taste package '${t}' not found in ${"local-global"===n?"global":"project"}`};const o=r.sourcePath,a=await findCategoryLineNumber({filePath:o,category:t});return await ne([{file:o,line:a}]),{success:!0,filePath:o,lineNumber:a}}catch(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}}async function findCategoryLineNumber(e){const{filePath:t,category:n}=e;try{const e=await S.readFile(t,"utf-8");if("taste.md"===f.basename(t)&&f.basename(f.dirname(t))===n)return 1;const r=e.split("\n");for(let e=0;e<r.length;e++)if(r[e].trim().toLowerCase()===`# ${n.toLowerCase()}`)return e+1;return 1}catch{return 1}}function getEditorSetupInstructions(){const e=re.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}async function runMigrations(){await removeMetadataFile()}async function removeMetadataFile(){const e=f.join(C.homedir(),".commandcode","taste",".metadata.json");if(M(e))try{await S.unlink(e)}catch{}}__name(validateTasteFile,"validateTasteFile"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(validateLearningLine,"validateLearningLine"),__name(buildResult,"buildResult"),__name(formatValidationIssues,"formatValidationIssues"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptPushStrategy,"promptPushStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),__name(push,"push"),__name(pull,"pull"),__name(pullRemote,"pullRemote"),__name(pullProjectPackage,"pullProjectPackage"),__name(processBucket,"processBucket"),__name(pullCategoryPackage,"pullCategoryPackage"),__name(pushRemote,"pushRemote"),__name(list,"list"),__name(deleteBuckets,"deleteBuckets"),__name(lint,"lint"),__name(open3,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var Ct=class{static{__name(this,"TasteSyncManager")}constructor(){runMigrations().catch(()=>{})}async push(e){return await push(e)}async pull(e){return await pull(e)}async pullRemote(e){return await pullRemote(e)}async pushRemote(e){return await pushRemote(e)}async list(e){return await list(e)}async delete(e){return await deleteBuckets(e)}async lint(e){return await lint(e)}async open(e){return await open3(e)}};async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new ht({baseUrl:e}),n=await t.get({endpoint:Fe.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}}async function promptNamespaceSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],o=await s.select({message:"Select namespace to push to\n",options:r,initialValue:t});return s.isCancel(o)&&(s.cancel("Operation cancelled"),process.exit(0)),o}function createTasteCommand(){const n=new e("taste");n.description("Manage taste learning packages");const r=new Ct;return n.command("push").argument("[package]","Package name (optional if using --all)").option("-g, --global","Push to global storage").option("--remote","Push to remote (default)").option("--all","Push all packages").option("--overwrite","Overwrite target without prompting (default: interactive merge)").option("--public","Make this package publicly discoverable").addOption(new t("--dev","Push to dev environment").hideHelp()).addOption(new t("--staging","Push to staging environment").hideHelp()).description("Push packages from project to remote or global storage (prompts on conflicts)").action(async(e,t)=>{try{let n;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(te.gray(" cmd taste push --all (pushes whole project)")),console.error(te.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote)if(t.all)n=await r.push({buckets:[],target:"remote-project",overwrite:t.overwrite,isPublic:t.public});else{let o,a;if(e&&e.includes("/")){const[t,n]=e.split("/");t&&n||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste push --remote username/packageName")),console.error(te.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),o=t,a=n}else{e||(console.error(te.red("Error: Please specify a package name")),console.error(te.gray("Usage: cmd taste push <namespace>/<package>")),console.error(te.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),a=e;let t;(await r.list({location:"local-project"})).some(e=>e.category===a)||(console.error(te.red(`Error: Taste package '${a}' not found in local project`)),process.exit(1));try{t=await fetchUserNamespaces()}catch(e){throw e}o=t.orgs.length>0?await promptNamespaceSelection(t):t.userName}n=await r.pushRemote({namespace:o,packageName:a,overwrite:t.overwrite,isPublic:t.public})}else{const o="local-global",a=t.all?[]:[e];n=await r.push({buckets:a,target:o,overwrite:t.overwrite})}if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}let o=!1;if(1===n.bucketsPushed.length){const e=n.bucketsPushed[0],r=n.filePaths?.[e];if(t.overwrite)t.remote&&r?console.log(te.green(`✓ Replaced '${e}' taste package in ${r}`)):(console.log(te.green(`✓ Replaced '${e}' taste package in global`)),r&&console.log(te.gray(` Path: ${r}`)));else if(n.mergeDetails?.[e]){const a=n.mergeDetails[e],s=[];a.added>0&&s.push(`${a.added} ${1===a.added?"learning":"learnings"} added`),a.updated>0&&s.push(`${a.updated} ${1===a.updated?"learning":"learnings"} updated`),a.unchanged>0&&s.push(`${a.unchanged} ${1===a.unchanged?"learning":"learnings"} unchanged`),t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r} (${s.join(", ")})`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global (${s.join(", ")})`)),r&&console.log(te.gray(` Path: ${r}`))),(a.added>0||a.updated>0)&&a.unchanged>0&&(o=!0)}else t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r}`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global`)),r&&console.log(te.gray(` Path: ${r}`)))}else if(n.bucketsPushed.length>0){const e=t.remote?"remote":"global";if(console.log(te.green(`✓ Pushed ${n.bucketsPushed.length} taste packages (${n.bucketsPushed.join(", ")}) to ${e}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){o=!0;break}}o&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,t)=>{try{let n,o;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),t.remote&&t.all&&(console.error(te.red("Error: The --all flag is not supported for remote pull")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),t.remote&&!e&&(console.error(te.red("Error: Please provide both namespace and package name")),process.exit(1)),t.remote&&e&&!e.includes("/")&&(console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(te.gray(" cmd taste pull <package> -g (from global)")),console.error(te.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote){e.includes("/")||(console.error(te.red("Error: Package name must include namespace")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[a,s]=e.split("/");a&&s||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),o=a,n=await r.pullRemote({namespace:o,packageName:s,overwrite:t.overwrite})}else{const o="local-global",a=t.all?[]:[e];n=await r.pull({buckets:a,source:o,overwrite:t.overwrite})}const a=t.remote?o?`${o}`:"remote":"global";if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}if(n.skipped&&n.skipped.length>0)for(const e of n.skipped)console.log(te.yellow(`⊘ Skipped '${e}' - kept local version`));let s=!1;if(1===n.bucketsPulled.length){const e=n.bucketsPulled[0],r=n.filePaths?.[e];if(t.overwrite)console.log(te.green(`✓ Replaced '${e}' taste package in project`)),r&&console.log(te.gray(` Saved to: ${r}`));else if(n.mergeDetails?.[e]){const t=n.mergeDetails[e],o=[];t.added>0&&o.push(`${t.added} ${1===t.added?"learning":"learnings"} added`),t.updated>0&&o.push(`${t.updated} ${1===t.updated?"learning":"learnings"} updated`),t.unchanged>0&&o.push(`${t.unchanged} ${1===t.unchanged?"learning":"learnings"} unchanged`),console.log(te.green(`✓ Pulled '${e}' taste package from ${a} (${o.join(", ")})`)),r&&console.log(te.gray(` Saved to: ${r}`)),(t.added>0||t.updated>0)&&t.unchanged>0&&(s=!0)}else console.log(te.green(`✓ Pulled '${e}' taste package from ${a}`)),r&&console.log(te.gray(` Saved to: ${r}`))}else if(n.bucketsPulled.length>0){const e=` (${n.bucketsPulled.join(", ")})`;if(console.log(te.green(`✓ Pulled ${n.bucketsPulled.length} taste packages${e} from ${a}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){s=!0;break}}s&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("list").option("-g, --global","List global packages").option("--remote","List remote packages").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let t,n;e.global&&e.remote&&(console.error(te.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(t="remote-project",n="remote"):e.global?(t="local-global",n="global"):(t="local-project",n="project");const o=await r.list({location:t});if(0===o.length)return void console.log(te.yellow(`No taste packages found in ${n}`));let a;console.log(te.hex("#E4CCFF").bold("\nTaste Packages")),a="remote-project"===t?"Stored in your commandcode.ai account":"local-global"===t?"Stored globally in ~/.commandcode/taste":"Stored locally in .commandcode/taste",console.log(te.dim(a+"\n"));let s=0;const i=__name(e=>{let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ★${e.starCount}`.length),e.downloadCount&&(t+=` ↓${e.downloadCount}`.length),t},"getDisplayLength"),c=Math.max(...o.map(i));for(const e of o){s+=e.learningCount;const t=getTimeAgo(e.lastUpdated),n=" ".repeat(c-i(e)+2),r=te.white(e.category),o=e.isPublic?te.green(" [public]"):"",a=e.isPublic&&e.starCount?te.yellow(` ★${e.starCount}`):"",l=e.downloadCount?te.gray(` ↓${e.downloadCount}`):"";console.log(` ${r}${o}${a}${l}${n}${te.dim.gray(`(${e.learningCount} learnings, updated ${t})`)}`)}console.log(te.dim(`\nTotal: ${o.length} packages, ${s} learnings\n`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("delete").argument("<package>","Package name to delete").option("-g, --global","Delete from global").description("Delete a package").action(async(e,t)=>{try{t.global||(console.error(te.red("Error: Currently only global is supported. Use -g flag.")),process.exit(1));const n=await r.delete({buckets:[e],location:"local-global"});if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}console.log(te.green(`✓ Deleted '${e}' taste package from global`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("lint").argument("[package]","Package name (required unless using --all)").option("-g, --global","Lint global taste files").option("--all","Lint all packages").description("Validate taste file format and structure").action(async(e,t)=>{try{e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste lint <package>")),console.error(te.gray(" cmd taste lint --all")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1));const n=await r.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(te.red(`Error: ${e.error}`));process.exit(1)}for(const e of n.filesLinted)console.log(e.formatted);if(n.filesLinted.length>1)if(console.log(""),0===n.totalErrors&&0===n.totalWarnings)console.log(te.green(`✓ All ${n.filesLinted.length} taste files are valid`));else{const e=[];n.totalErrors>0&&e.push(te.red(`${n.totalErrors} error${n.totalErrors>1?"s":""}`)),n.totalWarnings>0&&e.push(te.yellow(`${n.totalWarnings} warning${n.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${n.filesLinted.length} files`)}n.success||process.exit(1)}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,t)=>{try{const n=t.global?"local-global":"local-project",o=await r.open({package:e,target:n});o.success||(console.error(te.red(o.error)),process.exit(1)),console.log(te.green(`✓ Opened '${e}' taste package from ${t.global?"global":"project"}`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n}function getTimeAgo(e){const t=(new Date).getTime()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}function getPackageJson(){const e=import.meta.url,t=ae(e),n=w(t);return JSON.parse(N(E(n,"./../package.json"),"utf8"))}__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(promptNamespaceSelection,"promptNamespaceSelection"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),__name(getPackageJson,"getPackageJson");var Tt=getPackageJson(),St=y.join(T.homedir(),".commandcode"),Pt=y.join(St,"update-status.json"),At=y.join(St,"update-failed.json");function ensureCommandCodeDir(){R.existsSync(St)||R.mkdirSync(St,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=n("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3}),t=JSON.parse(e),r=Tt.version,o=r.includes("alpha"),a=t.filter(e=>!e.includes("alpha")),s=t.filter(e=>e.includes("alpha"));let i=r,c=!1;if(a.length>0){const e=a.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}if(!c&&o&&s.length>0){const e=s.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}return{currentVersion:r,latestVersion:i,updateAvailable:c}}catch(e){return null}}async function performAutoUpdate(e){const{silent:t=!1,updateInfo:r,onProgress:o}=e||{},a=r||await checkForUpdateAvailable();if(!a||!a.updateAvailable)return{success:!1};o?.(`Updating to v${a.latestVersion}...`);try{n(`npm i -g command-code@${a.latestVersion}`,{stdio:"ignore",env:{...process.env,NODE_NO_WARNINGS:"1"}}),ensureCommandCodeDir();const e={updatedFrom:a.currentVersion,updatedTo:a.latestVersion,updatedAt:Date.now()};return R.writeFileSync(Pt,JSON.stringify(e,null,2)),{success:!0}}catch(e){console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code"),ensureCommandCodeDir();const t={currentVersion:a.currentVersion,latestVersion:a.latestVersion,failedAt:Date.now()};return R.writeFileSync(At,JSON.stringify(t,null,2)),{success:!1,updateInfo:a}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),R.existsSync(Pt)){const e=JSON.parse(R.readFileSync(Pt,"utf-8"));return R.unlinkSync(Pt),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),R.existsSync(At)){const e=JSON.parse(R.readFileSync(At,"utf-8"));return R.unlinkSync(At),{currentVersion:e.currentVersion,latestVersion:e.latestVersion}}}catch(e){}return null}__name(ensureCommandCodeDir,"ensureCommandCodeDir"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(performAutoUpdate,"performAutoUpdate"),__name(getUpdateStatus,"getUpdateStatus"),__name(getFailedUpdateInfo,"getFailedUpdateInfo");var xt=new e("update").description("Update Command Code to the latest version").option("--check","Check for updates without installing").action(async e=>{if(e.check){console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));e.updateAvailable?(console.log(te.bold("Update available!")),console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd update")+te.dim(" to install."))):console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`))}else{console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));if(!e.updateAvailable)return void console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`));console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim(`\nUpdating command-code from ${e.currentVersion} → `)+te.white(e.latestVersion)+te.dim("...")),(await performAutoUpdate({silent:!0,updateInfo:e})).success?(console.log(te.green("\n✓ Successfully updated to ")+te.bold(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd")+te.dim(" to start using the new version."))):(console.log(te.red("✗ Update failed")),console.log(te.dim("Please try updating manually:")),console.log(te.cyan("npm i -g command-code")),process.exit(1))}}),$t=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:o=process.cwd(),env:a=process.env}=t;return new Promise(t=>{const s=r("/bin/bash",["-c",e],{cwd:o,env:{...a},stdio:["pipe","pipe","pipe"]});let i="",c="",l=null;n>0&&(l=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:i,stderr:c+(c?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{i+=e.toString()}),s.stderr?.on("data",e=>{c+=e.toString()}),s.on("close",n=>{l&&clearTimeout(l),t({stdout:i.trim(),stderr:c.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{l&&clearTimeout(l),t({stdout:i,stderr:c+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),It=__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"),Dt="read_file",Ft="edit_file",Rt="write_file",Mt="read_directory",Nt="read_multiple_files",jt="grep",Ot="shell_command",Lt="think",_t="todo_write",Ut="web_search",Bt="web_fetch",Wt=__name(e=>e===Ut,"isWebSearchTool");function toRelativePath(e){const t=global.COMMAND_CODE_CWD||process.cwd(),n=process.env.HOME||process.env.USERPROFILE||"",r=f.relative(t,e);return r.startsWith("..")?n&&e.startsWith(n)?e.replace(n,"~"):e:""===r?f.basename(e):r}function replacePathsInText(e){if(!e||"string"!=typeof e)return e;let t=e;return t=t.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,e=>f.isAbsolute(e)?toRelativePath(e):e),t=t.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),t}__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var zt=D.object({id:D.string(),timestamp:D.number(),type:D.literal("image"),source:D.object({type:D.enum(["base64","url"]),media_type:D.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:D.string()})}),Gt=D.object({id:D.string(),timestamp:D.number(),input:D.string(),output:D.string().optional(),metadata:D.record(D.string(),D.any()).optional(),images:D.array(zt).optional().default([])}),Ht=Gt.extend({role:D.literal("user")}),Vt=Gt.extend({role:D.literal("assistant")}),qt=Gt.extend({role:D.literal("tool"),name:D.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Kt=Gt.extend({role:D.literal("bash"),command:D.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),Jt=Gt.extend({role:D.literal("system")}),Yt=Gt.extend({role:D.literal("error")}),Zt=Gt.extend({role:D.literal("info")}),Xt=D.discriminatedUnion("role",[Ht,Vt,qt,Kt,Jt,Yt,Zt]),Qt=__name((e,t)=>Xt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),en=__name(e=>Xt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),tn=__name(e=>Xt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),nn=__name((e,t,n)=>Xt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),rn=__name(e=>Xt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),on=__name(e=>Xt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),an=__name(e=>Xt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),sn=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return Xt.parse(n)},"updateEntryWithOutput"),cn=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),ln=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),dn=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),un=["Thinking…","Yapping…","Yawning…","Brewing…","Contemplating…","Conjuring…","Pondering…","Mixing…","Stirring…","Channeling…","Sculpting…","Crystallizing…","Spinning…","Tuning…","Sparking…","Revving…","Cruising…","Exploring…","Blazing…","Climbing…","Diving…","Surfing…","Riding…","Dancing…","Juggling…","Performing…","Casting…","Cooking…","Baking…","Seasoning…","Garnishing…","Vibing…","Chilling…","Grooving…","Jamming…","Swaying…","Bouncing…","Flowing…","Gliding…","Floating…","Drifting…","Wandering…","Meandering…","Strolling…","Skipping…","Hopping…","Leaping…","Soaring…","Glowing…","Shimmering…","Twinkling…","Flickering…","Pulsing…","Humming…","Buzzing…","Whirring…","Purring…","Chirping…","Whistling…","Giggling…","Snickering…","Chuckling…","Grinning…","Smirking…","Winking…","Nodding…","Stretching…","Flexing…","Wiggling…","Swirling…","Twirling…","Spiraling…","Weaving…","Bobbing…","Rocking…","Swinging…","Swooshing…","Zipping…","Zooming…","Whizzing…","Zapping…","Popping…","Snapping…","Crackling…","Sizzling…","Bubbling…","Fizzing…"],mn=__name(()=>un[Math.floor(Math.random()*un.length)],"getRandomLLMStatus"),gn=__name(e=>{switch(e){case Dt:return"Read";case Ft:return"Edit";case Rt:return"Write";case Mt:return"List";case Nt:return"Read Multiple";case jt:return"Search";case Ot:return"Shell";case _t:return"Todos";case Lt:return"Thinking…";case Ut:return"Web Search";case Bt:return"Web Fetch";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),pn=__name((e,t)=>{try{switch(e){case Dt:case Rt:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case Ft:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Mt:return toRelativePath(t.path||"directory");case jt:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case Ot: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 _t:return`${t.todos?t.todos.length:0} items`;case Lt:return t.content||"planning";case Nt:const r=t.include||[];return Array.isArray(r)?r.join(", "):"multiple files";case Ut:return t.query||"search";case Bt:return t.url||"fetch";default:const o=t?.messages||[];if(Array.isArray(o)&&o.length>0&&o[0]&&"object"==typeof o[0]&&"content"in o[0]){const e=o[0].content;if("string"==typeof e)return e.slice(0,50)+(e.length>50?"...":"")}return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),hn=__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"),fn=__name(()=>{const[e,t]=B({isExecuting:!1,currentCommand:null});return{executeBash:H(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await $t(e,{timeout:3e4,cwd:process.cwd()}),o=It(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]=sn(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]=sn(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),yn=D.object({name:D.string().min(1,"Skill name is required").max(64,"Skill name must be 64 characters or less").regex(/^[a-z0-9-]+$/,"Skill name must contain only lowercase letters, numbers, and hyphens").refine(e=>!e.startsWith("-")&&!e.endsWith("-"),"Skill name cannot start or end with a hyphen").refine(e=>!e.includes("--"),"Skill name cannot contain consecutive hyphens"),description:D.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:D.string().optional(),compatibility:D.array(D.string()).optional(),metadata:D.record(D.string(),D.any()).optional(),"allowed-tools":D.array(D.string()).optional()});function getPersonalSkillsDir(){return y.join(T.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return y.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:t}=e;try{await P.access(t);const e=(await P.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory());return(await Promise.all(e.map(async e=>{try{const n=y.join(t,e.name,"SKILL.md");await P.access(n);const r=await P.readFile(n,"utf-8"),{data:o}=se(r),a=yn.parse(o);return{name:a.name,description:a.description,filePath:n}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getPersonalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{personal:e,project:t}}function escapeXML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function generateSkillsXML(e){const{personal:t,project:n}=e,r=[...t,...n];return 0===r.length?"":`<available_skills>\n${r.map(e=>{const t=y.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(t)}\n</location>\n</skill>`}).join("\n")}\n</available_skills>`}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}D.object({name:D.string(),description:D.string(),license:D.string().optional(),compatibility:D.array(D.string()).optional(),metadata:D.record(D.string(),D.any()).optional(),"allowed-tools":D.array(D.string()).optional(),content:D.string(),filePath:D.string()}),D.object({name:D.string(),description:D.string(),filePath:D.string()}),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var wn=D.object({absolutePath:D.string().describe("The absolute path to the file to read"),offset:D.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:D.number().optional().describe("Optional number of lines to read")});D.object({content:D.union([D.string(),D.instanceof(Buffer)]),contentType:D.enum(["text","binary"]),fileType:D.string(),size:D.number(),linesRead:D.number().optional()});var En=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(e){const{absolutePath:t,offset:n,limit:r}=e;if(!f.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new En("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=f.normalize(t);try{await S.access(o,F.constants.F_OK|F.constants.R_OK)}catch{throw new En(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await S.stat(o)).isFile())throw new En("Path does not point to a file","NOT_A_FILE");const a=getFileType(o),s=isBinaryFile(a);if(void 0!==n&&void 0===r||void 0===n&&void 0!==r)throw new En("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new En("Offset must be >= 0","INVALID_OFFSET");if(void 0!==r&&r<=0)throw new En("Limit must be > 0","INVALID_LIMIT");try{if(s){const e=await S.readFile(o);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==r){const e=await readTextFileLines(o,n,r);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await S.readFile(o,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof En)throw e;throw new En(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var bn={".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(e){const t=f.extname(e).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",...bn}[t]||"unknown"}function isBinaryFile(e){return Object.values(bn).includes(e)}async function readTextFileLines(e,t,n){const r=(await S.readFile(e,"utf8")).split(/\r?\n/),o=t,a=Math.min(o+n,r.length),s=r.slice(o,a);return{content:s.join("\n"),linesRead:s.length}}async function processFileReferences(e){const t=[];let n=e;const r=[...e.matchAll(/@([^\s@]+)/g)];for(const e of r){const r=e[0],o=e[1];try{const e=f.isAbsolute(o)?o:f.resolve(process.cwd(),o),a=await readFileContent({absolutePath:e});if("binary"===a.contentType)continue;const s=String(a.content),i=f.relative(process.cwd(),e),c=1e5;if(s.length>c){t.push({token:r,resolvedPath:e,content:"",tooLarge:!0});const o=`${i}`;n=n.replace(r,o);continue}t.push({token:r,resolvedPath:e,content:s});const l=`{${i}: ${s}}`;n=n.replace(r,l)}catch(e){continue}}return{displayContent:e,processedContent:n,fileReferences:t}}function reconstructContent(e,t){let n=e;for(const e of t){const t=`{${f.relative(process.cwd(),e.resolvedPath)}: ${e.content}}`;n=n.replace(e.token,t)}return n}function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),__name(formatOutput,"formatOutput");var vn={name:"read_file",description:"Reads the contents of a file from the local filesystem, handling both text and binary files appropriately. \nThis tool automatically detects the file type based on extension and processes it accordingly - text files are returned as readable strings while binary files return metadata about the file type and size. \nFor large text files, you can optionally read specific line ranges using the offset and limit parameters to avoid loading the entire file into memory. \nThe tool validates that the provided path is absolute and that the file exists and is readable before attempting to read it. \nIt should be used when you need to examine file contents, verify file existence, or extract specific portions of text files for analysis or processing.",input_schema:{type:"object",properties:{absolutePath:{type:"string",description:'The absolute path to the file to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). Relative paths like "./file.txt" or "../file.txt" are not accepted. The file must exist and be readable by the current process.'},offset:{type:"number",description:"The line number to start reading from (0-based index, where 0 is the first line). This parameter must be used together with the limit parameter for reading specific line ranges. Cannot be negative. Use this when you need to read a specific section of a large file without loading the entire content."},limit:{type:"number",description:"The maximum number of lines to read starting from the offset. Must be a positive integer and used together with the offset parameter. This helps manage memory usage when dealing with large files by reading only the necessary portion."}},required:["absolutePath"]},execute:__name(async e=>{try{const t=wn.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading file`}},"execute")},kn=D.object({filePath:D.string().describe("The absolute path to the file to edit"),oldValue:D.string().describe("The text to replace"),newValue:D.string().describe("The new text to insert"),replacementCount:D.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:D.boolean().optional().describe("Whether to replace all occurrences (default: false)")});D.object({path:D.string(),replacementsCount:D.number(),oldContent:D.string(),newContent:D.string()}),D.object({name:D.string(),message:D.string(),code:D.string().optional()});var Cn=D.object({backupFileName:D.string().nullable(),version:D.number().int().positive(),backupTime:D.string().datetime()}),Tn=D.object({messageId:D.string().uuid(),trackedFileBackups:D.record(D.string(),Cn),timestamp:D.string().datetime()});D.object({type:D.literal("file-history-snapshot"),messageId:D.string().uuid(),snapshot:Tn,isSnapshotUpdate:D.boolean()}),D.object({maxFileSize:D.number().int().positive().default(10485760),retentionDays:D.number().int().positive().default(30)});var Sn=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`${$.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 y.join(T.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:t}=e;return y.join(getCommandCodeBasePath(),"file-history",t)}function getBackupFilePath(e){const{sessionId:t,backupFileName:n}=e;return y.join(getFileHistoryPath({sessionId:t}),n)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await P.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 P.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await P.writeFile(r,n);const e=await P.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 P.rename(r,t)}catch(e){try{await P.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await P.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await P.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function truncateString(e){const{text:t,maxLength:n}=e;return t.length<=n?t:n<=3?t.slice(0,n):t.slice(0,n-3)+"..."}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),a=Math.floor(o/60),s=Math.floor(a/24);return s>0?`${s}d ago`:a>0?`${a}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:t}=e;return y.basename(t)}function isWithinRetentionPeriod(e){const{timestamp:t,retentionDays:n}=e,r=new Date(t).getTime();return Date.now()-r<=24*n*60*60*1e3}__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(truncateString,"truncateString"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod");var Pn={maxFileSize:10485760,retentionDays:30},An=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Pn,...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 P.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const a=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:a,content:e});const s={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,s),this.trackedState.versions.set(t,n),{success:!0,backup:s,skipped:!1}}catch(e){return{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 P.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r}))throw new Sn(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");const o=await P.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 P.access(t,P.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 P.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await P.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await P.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}},xn=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new An({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,maxLength:100}))}const o=Object.keys(n.trackedFileBackups);let a=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(a={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:a})}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,a=0,s=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{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?a++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(s=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:a,messagesRemoved:s}}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}},$n=null;function initializeCheckpointService(e){const{sessionId:t}=e;return $n=new xn({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return $n?$n.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(e){const{filePath:t,oldValue:n,newValue:r,replaceAll:o=!1,replacementCount:a=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!f.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!n)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==r)throw createFileEditError("newValue is required","INVALID_INPUT");if(!o&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await j.access(t,O.F_OK|O.R_OK|O.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let s;try{const e=await readFileContent({absolutePath:t});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");s=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 i=(s.match(new RegExp(escapeRegExp(n),"g"))||[]).length;if(0===i)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let c,l;if(o)c=i;else if(c=a,c>i)throw createFileEditError(`Expected ${c} replacements, but only found ${i} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||c===i)l=s.split(n).join(r),d=i;else{l=s;for(let e=0;e<c;e++){const e=l.indexOf(n);-1!==e&&(l=l.substring(0,e)+r+l.substring(e+n.length),d++)}}if(0===d)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:t}),await j.writeFile(t,l,"utf-8"),{path:t,replacementsCount:d,oldContent:s,newContent:l}}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"),__name(formatOutput2,"formatOutput");var In={name:"edit_file",description:"Performs precise text replacements in files by finding and replacing exact string matches, similar to a str_replace operation.\nThis tool is designed for making targeted edits to text files, allowing you to replace specific occurrences of text with new content while preserving the rest of the file unchanged.\nIt validates that the file exists, is accessible, and is a text file (not binary) before attempting any modifications, ensuring data integrity.\nThe tool can replace a single occurrence, a specific number of occurrences, or all occurrences of the target text based on your requirements.\nIt should be used when you need to fix typos, update variable names, modify configuration values, or make any other precise text changes in code or text files.\nThe tool will report the exact number of replacements made and will fail safely if the target text is not found or if multiple matches exist when expecting a unique match.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path to the file to edit. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The file must exist and have write permissions. Binary files cannot be edited with this tool."},oldValue:{type:"string",description:"The exact text string to search for in the file. This must match exactly including whitespace, indentation, and line breaks. The match is case-sensitive. If multiple matches exist and replaceAll is false, only the first occurrence from the beginning of the file will be replaced."},newValue:{type:"string",description:"The replacement text that will be inserted in place of each matched occurrence of oldValue. Can be an empty string to effectively delete the matched text. Preserves any surrounding whitespace and formatting."},replaceAll:{type:"boolean",description:"When true, replaces all occurrences of oldValue in the file. When false (default), replaces only the number of occurrences specified by replacementCount. Use true when you need to update all instances, such as renaming a variable throughout a file."},replacementCount:{type:"number",description:"The number of occurrences to replace when replaceAll is false. Default is 1. Must be a positive integer. If set higher than the actual number of occurrences, the tool will report an error. Use this for controlled, partial replacements."}},required:["filePath","oldValue","newValue"]},execute:__name(async e=>{try{const t=kn.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while editing file`}},"execute")},Dn=D.object({path:D.string().describe("The absolute path to the directory to read"),exclude:D.array(D.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:D.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});D.object({files:D.array(D.string()),directories:D.array(D.string())});var Fn=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(e){const{path:t,exclude:n=[],respectGitIgnore:r=!1}=e;if(!f.isAbsolute(t))throw new Fn("Path must be absolute, not relative","INVALID_PATH");try{if(!(await S.stat(t)).isDirectory())throw new Fn("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Fn)throw e;throw new Fn(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await S.readdir(t);let o=[];r&&(o=await loadGitIgnorePatterns(t));const a=[...n,...o],s=[],i=[];for(const n of e){if(shouldIgnoreEntry(n,a))continue;const e=f.join(t,n);try{const t=await S.stat(e);t.isDirectory()?i.push(n):t.isFile()&&s.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:s.sort(),directories:i.sort()}}catch(e){if(e instanceof Fn)throw e;throw new Fn(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(e){const t=[];try{if(!await isInGitRepository(e))return t;let n=f.resolve(e);const r=await findGitRoot(e);for(;n&&isWithinGitRoot(n,r);){const e=f.join(n,".gitignore");try{const n=(await S.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const r=f.dirname(n);if(r===n)break;n=r}}catch(e){}return t}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(e){let t=f.resolve(e);for(;;){try{const e=f.join(t,".git");if((await S.stat(e)).isDirectory())return t}catch{}const e=f.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=f.resolve(e),r=f.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(ie(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")}__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),__name(formatOutput3,"formatOutput");var Rn={name:"read_directory",description:"Lists the contents of a directory, providing separate arrays of files and subdirectories found at the specified path.\nThis tool is essential for exploring project structure, discovering available files, and understanding directory organization before performing operations on specific files.\nIt automatically respects .gitignore patterns by default when operating within git repositories, ensuring you don't see files that are intentionally excluded from version control.\nThe tool supports custom exclusion patterns using glob syntax, allowing you to filter out specific files or directories based on your needs, such as build artifacts or temporary files.\nResults are always sorted alphabetically for consistent output, making it easier to locate specific items in large directories.\nIt should be used when you need to explore a directory's contents, verify file existence, or understand project structure before performing file operations.",input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the directory to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The directory must exist and be accessible. Returns an error if the path points to a file instead of a directory."},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude from results. Uses minimatch syntax for pattern matching. Examples: ["*.log", "temp*", "**/*.tmp"] would exclude all log files, anything starting with "temp", and all .tmp files in any subdirectory. Patterns are applied in addition to any .gitignore rules.'}},required:["path"]},execute:__name(async e=>{try{const t=Dn.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading directory`}},"execute")},Mn=D.object({filePath:D.string().describe("The absolute path where the file should be written"),content:D.string().describe("The content to write to the file")});async function writeFile5({filePath:e,content:t}){if(!v(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=w(e);return M(n)||await A(n,{recursive:!0}),await backupFileBeforeEdit({filePath:e}),await x(e,t,"utf-8"),{path:e,bytesWritten:Buffer.byteLength(t,"utf-8")}}catch(t){const n=t instanceof Error?t.message:"Unknown error occurred";throw new Error(`Failed to write file '${e}': ${n}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}D.object({success:D.boolean(),message:D.string(),path:D.string().optional()}),__name(writeFile5,"writeFile"),__name(formatOutput4,"formatOutput");var Nn={name:"write_file",description:"Creates or overwrites a file with the specified content at the given absolute path, automatically creating any necessary parent directories.\nThis tool handles the complete file writing process, including directory creation, making it ideal for generating new files, saving processed output, or creating configuration files.\nIf the file already exists, it will be completely overwritten with the new content - the previous contents will be lost, so use with caution on existing files.\nThe tool automatically creates any missing parent directories in the path, eliminating the need to manually ensure directory structure exists before writing.\nIt should be used when you need to create new files, save generated content, write configuration files, or output processed data to the filesystem.\nAll content is written as UTF-8 encoded text, making it suitable for source code, configuration files, documentation, and other text-based formats.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path where the file should be written. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). If parent directories do not exist, they will be created automatically. Existing files at this path will be overwritten without warning."},content:{type:"string",description:"The text content to write to the file. Can be any UTF-8 string including multi-line text, JSON, XML, source code, or any other text format. Empty strings are valid and will create an empty file. Line endings are preserved as provided."}},required:["filePath","content"]},execute:__name(async e=>{try{const t=Mn.parse(e),n=await writeFile5(t);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")},jn=D.object({include:D.array(D.string()).describe("Array of glob patterns to include files"),exclude:D.array(D.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:D.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:D.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:D.string().optional().describe("Base directory for relative paths. Default: current working directory")}),On=D.object({filePath:D.string(),content:D.string(),fileType:D.string(),size:D.number()});D.object({content:D.string(),filesRead:D.array(D.string()),errors:D.array(D.object({file:D.string(),error:D.string()})),fileDetails:D.array(On)});var Ln=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},_n=["**/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 a of e)try{(await ce(a,{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 "${a}": ${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:t,exclude:n=[],gitIgnore:r=!0,defaultExclude:o=!0,targetDirectory:a=process.cwd()}=e;if(!t||0===t.length)throw new Ln("At least one include pattern must be provided","NO_PATTERNS");const s=y.resolve(a),i={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(..._n);const a=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:s});for(const e of a)try{const t=y.resolve(s,e),n=await readFileContent({absolutePath:t}),r=processFileResult({content:n,filePath:e});i.fileDetails.push(r),i.content+=`\n// File: ${e} (${n.fileType})\n`,i.content+=r.content,i.content+="\n",i.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);i.errors.push({file:e,error:n}),i.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return i}catch(e){if(e instanceof Ln)throw e;throw new Ln(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){return{totalFiles:e.fileDetails.length,successfulReads:e.filesRead.length,failedReads:e.errors.length,totalSize:e.fileDetails.reduce((e,t)=>e+t.size,0),fileTypesCounts:e.fileDetails.reduce((e,t)=>(e[t.fileType]=(e[t.fileType]||0)+1,e),{}),contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];return n.push(`Read ${t.successfulReads}/${t.totalFiles} files (${t.totalSize} bytes)`),e.errors.length>0&&(n.push("\nErrors:"),e.errors.forEach(e=>n.push(` - ${e.file}: ${e.error}`))),n.push("\n--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var Un={name:"read_multiple_files",description:"Reads multiple files simultaneously based on glob patterns, returning their contents concatenated with clear file headers for easy identification.\nThis tool is designed for bulk file operations, such as analyzing all source files in a project, reviewing multiple configuration files, or processing sets of related documents.\nIt automatically excludes common non-source directories like node_modules and build folders by default, and respects .gitignore patterns to avoid processing files that shouldn't be analyzed.\nThe tool handles both text and binary files appropriately - text files have their content included while binary files are noted with their type and size information.\nEach file's content is clearly separated with a header showing the file path and type, making it easy to distinguish between different files in the concatenated output.\nIt should be used when you need to analyze multiple files at once, search across multiple files for patterns, or gather content from various sources for processing or review.\nThe tool provides detailed feedback including which files were successfully read, any errors encountered, and statistics about the operation.",input_schema:{type:"object",properties:{include:{type:"array",items:{type:"string"},description:'Array of glob patterns to match files for reading. Uses standard glob syntax with support for wildcards (* for single level, ** for recursive). Examples: ["**/*.ts"] matches all TypeScript files, ["src/**/*.js", "lib/**/*.js"] matches JavaScript files in src and lib directories. At least one pattern must be provided.'},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude files from reading. Applied after include patterns. Examples: ["**/*.test.ts", "**/*.spec.js"] excludes test files, ["**/generated/**"] excludes generated directories. These patterns are additive with default exclusions and .gitignore rules.'},defaultExclude:{type:"boolean",description:"Whether to apply default exclusions for common non-source directories and files. Default is true. When enabled, automatically excludes: node_modules, dist, build, .git, coverage, tmp, temp, .DS_Store, *.log, *.tmp, *.cache, and other common build artifacts. Set to false to read all matching files regardless of common conventions."},gitIgnore:{type:"boolean",description:"Whether to respect .gitignore files when matching patterns. Default is true. When enabled, any files or directories listed in .gitignore files will be excluded from results. Useful for avoiding generated files, secrets, or other intentionally untracked files. Set to false to include all files matching your patterns."},targetDirectory:{type:"string",description:"The base directory from which to resolve glob patterns. Default is the current working directory. Must be an absolute path. All include and exclude patterns will be resolved relative to this directory. Use this to scope your file search to a specific part of the filesystem."}},required:["include"]},execute:__name(async e=>{try{const t=jn.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading multiple files`}},"execute")},Bn=D.object({pattern:D.string().min(1,"Pattern is required"),include:D.array(D.string()).optional(),directory:D.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,o)=>{const a=r(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";a.stdout?.on("data",e=>{s+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("close",e=>{0===e?n(s):1!==e||i?o(new Error(i||`Command failed with exit code ${e}`)):n("")}),a.on("error",e=>{o(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(a){if(!(a instanceof Error&&a.message.includes("ENOENT")))throw a;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 a=e.trim().split("\n"),s=[];for(const e of a){const t=parseGrepLine(e);t&&s.push(t)}return s}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),__name(formatGrepResults,"formatGrepResults");var Wn={name:"grep",description:"Searches for text patterns across files in a directory using regular expressions, providing powerful pattern matching capabilities for code analysis, debugging, and content discovery.\nThis tool performs recursive searches through directory structures, examining file contents to find all occurrences of the specified pattern, making it ideal for locating specific code implementations, finding TODO comments, searching for function usage, or identifying configuration values.\nThe search uses Perl-compatible regular expressions (PCRE), supporting advanced patterns including lookaheads, lookbehinds, character classes, and quantifiers, with results showing file paths and line numbers for each match.\nFile filtering can be applied using glob patterns to search only specific file types, improving performance and relevance by focusing on the files that matter for your search.\nIt should be used when you need to find where something is defined or used in a codebase, locate specific text patterns across multiple files, verify the presence of certain code patterns, or analyze code structure and dependencies.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'The regular expression pattern to search for in file contents. Supports full PCRE syntax including special characters (\\d, \\w, \\s), quantifiers (*, +, ?, {n,m}), anchors (^, $), and groups. Special regex characters like ., *, [, ], (, ), {, }, |, \\, ^, $ must be escaped with backslash when matching literally. Examples: "TODO.*urgent" finds TODO comments marked urgent, "function\\s+\\w+\\(" finds function definitions, "import.*from.*react" finds React imports.'},include:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to filter which files to search. Only files matching at least one pattern will be searched. Supports standard glob syntax: * matches any characters except /, ** matches any characters including /, ? matches single character, [abc] matches character set. Examples: ["*.ts", "*.tsx"] searches TypeScript files, ["src/**/*.js"] searches JavaScript files in src directory, ["*.{js,jsx,ts,tsx}"] searches all JavaScript/TypeScript files. If omitted, searches all files except those in .gitignore.'},directory:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=Bn.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while searching files`}},"execute")},zn=D.object({pattern:D.string().min(1,"Pattern is required"),path:D.string().optional()}),Gn=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:t,path:n="."}=e;if(!t)throw new Gn("Pattern parameter is required","INVALID_PATTERN");try{const e=y.resolve(process.cwd(),n),r=process.cwd(),o=r.endsWith(y.sep)?r:r+y.sep;if(e!==r&&!e.startsWith(o))throw new Gn("Search path must be within the current working directory","INVALID_PATH");const a=await ce(t,{cwd:e,ignore:_e,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),s=await Promise.all(a.map(async t=>{const n=y.join(e,t);try{return{file:t,mtime:(await P.stat(n)).mtimeMs}}catch{return{file:t,mtime:0}}}));return s.sort((e,t)=>t.mtime-e.mtime),{files:s.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof Gn)throw e;if(e instanceof Error)throw new Gn(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new Gn("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")}__name(globSearch,"globSearch"),__name(formatGlobResults,"formatGlobResults");var Hn={name:"glob",description:"Searches for files in a directory tree using glob-style path patterns, enabling fast and flexible discovery of files across codebases of any size.\nThis tool matches file paths against glob patterns such as **/*.js or src/**/*.ts, making it ideal for locating files by name, extension, or directory structure without inspecting file contents. It performs recursive traversal where applicable and efficiently handles large repositories.\nResults are returned as a list of matching file paths, sorted by modification time, allowing you to quickly identify the most recently changed or relevant files.\nFile pattern matching can be refined using inclusive or exclusive glob expressions to narrow down results, improving performance and focus when working with large or complex projects.\nIt should be used when you need to find files based on naming or path patterns, explore the structure of an unfamiliar codebase, locate configuration or entry-point files, or prepare a targeted set of files for further inspection with tools like grep.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files. Supports wildcards: * matches any characters except /, ** matches any characters including / (for recursive search), ? matches single character, [abc] matches character set, {js,ts} matches alternatives. Examples: "**/*.ts" finds all TypeScript files recursively, "src/**/*.{js,jsx}" finds JavaScript files in src directory, "*.json" finds JSON files in current directory, "**/test/**/*.spec.ts" finds test spec files.'},path:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=zn.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while finding files`}},"execute")},Vn=D.object({command:D.string().min(1,"Command cannot be empty"),args:D.array(D.string()).optional(),directory:D.string().optional(),timeout:D.number().optional()}),qn=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,a,s){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=a,this.duration=s}};async function executeShellCommand(e){const{command:t,args:n=[],directory:o,timeout:a=3e4}=e,s=Date.now();if(!t.trim())throw new qn("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(f.isAbsolute(o))throw new qn("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=f.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await P.stat(i)).isDirectory())throw new qn(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof qn)throw e;throw new qn(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:i,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((o,i)=>{let c="",l="",d=!1;const u=n.length>0?le([t,...n]):t,m=setTimeout(()=>{if(!d){g.kill("SIGTERM");const e=Date.now()-s;i(new qn(`Command timed out after ${a}ms`,"TIMEOUT",null,"SIGTERM",c,l,e))}},a),g=r(u,[],e);g.stdout?.on("data",e=>{c+=e.toString()}),g.stderr?.on("data",e=>{l+=e.toString()}),g.on("close",(e,t)=>{d=!0,clearTimeout(m);const n=Date.now()-s;0===e?o({stdout:c.trim(),stderr:l.trim(),exitCode:e,signal:t,duration:n}):i(new qn(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,c.trim(),l.trim(),n))}),g.on("error",e=>{d=!0,clearTimeout(m);const t=Date.now()-s;i(new qn(`Failed to start command: ${e.message}`,"START_FAILED",null,null,c.trim(),l.trim(),t))})})}catch(e){if(e instanceof qn)throw e;throw new qn(`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")}__name(executeShellCommand,"executeShellCommand"),__name(formatShellCommandResult,"formatShellCommandResult");var Kn={name:"shell_command",description:"Executes shell commands in a controlled environment with comprehensive output capture, timeout protection, and working directory management, enabling system operations, build processes, and tool integrations.\nThis tool spawns commands as child processes with full control over execution environment, capturing both standard output and error streams while monitoring exit codes and signals, making it ideal for running build scripts, executing CLI tools, performing system operations, or integrating with external programs.\nCommands run with shell interpretation enabled for cross-platform compatibility, supporting pipes, redirections, and shell built-ins, with automatic timeout termination to prevent hanging processes from blocking execution.\nThe tool provides detailed execution results including stdout, stderr, exit codes, and execution duration, helping diagnose issues and verify successful completion of operations.\nIt should be used when you need to run build or test commands, execute system utilities, interact with CLI tools, perform file operations that require shell commands, or integrate with external programs and scripts.\nImportant: Commands execute with the permissions of the current process. Be cautious with commands that modify the filesystem or system state. Always validate and sanitize any user-provided input before including it in commands.",input_schema:{type:"object",properties:{command:{type:"string",description:'The shell command to execute. Can be any valid shell command available in the system PATH or built-in shell commands. Common commands include: "npm" for Node.js packages, "git" for version control, "ls"/"dir" for listing files, "echo" for output, "cat"/"type" for file contents. The command string is passed to the system shell (sh on Unix, cmd.exe on Windows). Special characters should be properly escaped. Cannot be empty.'},args:{type:"array",items:{type:"string"},description:'Optional array of arguments to pass to the command. Each argument is passed as a separate string and is automatically escaped for shell safety. Use this instead of including arguments in the command string for better security and cross-platform compatibility. Examples: ["install", "--save-dev", "typescript"] for npm, ["status", "--short"] for git, ["-la", "/usr"] for ls. Arguments containing spaces or special characters are automatically quoted.'},directory:{type:"string",description:'Optional working directory where the command should be executed, specified as a relative path from the current working directory. Must be a relative path (absolute paths are not allowed for security). The directory must exist and be accessible. Examples: "src" runs in src folder, "packages/core" runs in packages/core, "../sibling" runs in sibling directory. If omitted, uses the current working directory. Useful for running commands that depend on specific file locations or configurations.'},timeout:{type:"number",description:"Optional maximum time in milliseconds to wait for the command to complete before forcibly terminating it. Must be between 100 and 300000 (5 minutes). Defaults to 30000ms (30 seconds). The command process is killed with SIGTERM if it exceeds this duration. Useful for preventing long-running or hanging processes. Set higher for operations known to take time (builds, installs), lower for quick operations. Examples: 5000 for quick commands, 60000 for npm install, 120000 for large builds."}},required:["command"]},execute:__name(async e=>{try{const t=Vn.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${o.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${o.cross} Error: ${e.message}`}return`${o.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var Jn={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)}__name(todoWrite,"todoWrite");var Yn={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};function getRootAgentDir(){return y.join(T.homedir(),".commandcode","agents")}function getLocalAgentDir(){return y.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,t){try{const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=se(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,systemPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,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(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents");var Zn=2e5;function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.max(0,Math.ceil(t-n))}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>25e3}function getOversizedOutputError(e,t){return`Error: Output too large (${e.toLocaleString()} tokens, max ${25e3.toLocaleString()}). Try using grep or ripgrep with more specific patterns to filter results.`}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?getOversizedOutputError(estimateTokens(e)):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 getEnterpriseMemoryPath(){switch(C.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return f.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const e=C.homedir();return f.join(e,".commandcode","AGENTS.md")}function getProjectMemoryPaths(e){return[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:M(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(M(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:M(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return M(e)?await S.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(e,t,n=0,r=5){if(n>=r)return e;const o=[],a=e.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),s=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let i=a;for(const e of s){const o=e[1];let a=o;o.startsWith("~/")?a=f.join(C.homedir(),o.slice(2)):f.isAbsolute(o)||(a=f.resolve(f.dirname(t),o));const s=await loadMemoryFile(a);if(s){const t=await processImports(s,a,n+1,r);i=i.replace(e[0],`\n# Imported from ${o}\n${t}\n`)}}return i=i.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>o[parseInt(t)]),i}async function loadAllMemories(e,t){const n=new Map,r=getEnterpriseMemoryPath();if(M(r)){const e=await loadMemoryFile(r);if(e){const t=await processImports(e,r);n.set(r,t)}}const o=getUserMemoryPath();if(M(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);n.set(o,t)}}const a=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of a)if(M(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}if(t&&t.length>0)for(const r of t){const t=f.isAbsolute(r)?f.dirname(r):f.dirname(f.resolve(e,r));if(t.startsWith(e)&&t!==e){const r=[];let o=t;for(;o.startsWith(e)&&o!==e;)r.push(o),o=f.dirname(o);for(const e of r.reverse()){const t=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of t)if(M(e)&&!n.has(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}}}}return n}async function openInEditor(e){const t=process.env.EDITOR||process.env.VISUAL||"code",n=f.dirname(e);return M(n)||await S.mkdir(n,{recursive:!0}),M(e)||await S.writeFile(e,"# AGENTS.md\n\n","utf-8"),new Promise((n,o)=>{const a=r(t,[e],{stdio:"inherit",shell:!0});a.on("exit",e=>{0===e?n():o(new Error(`Editor exited with code ${e}`))}),a.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),o(e)})})}async function initProjectMemory(e){const t=f.join(e,"AGENTS.md");return M(t)||await S.writeFile(t,"# 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"),t}async function getMemoryContent(e){try{const t=process.cwd(),n=await loadAllMemories(t,e);if(0===n.size)return null;const r=[],o=getEnterpriseMemoryPath(),a=getUserMemoryPath(),s=[f.join(t,"AGENTS.md"),f.join(t,".commandcode","AGENTS.md")];n.has(o)&&r.push(`# Memory from: ${o}\n\n${n.get(o)}`),n.has(a)&&r.push(`# Memory from: ${a}\n\n${n.get(a)}`);for(const e of s)if(n.has(e)){r.push(`# Memory from: ${e}\n\n${n.get(e)}`);break}for(const[e,t]of n)e===o||e===a||s.includes(e)||r.push(`# Memory from: ${e}\n\n${t}`);return r.join("\n\n---\n\n")}catch(e){return null}}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__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");var Xn=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return y.join(T.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return ue(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=y.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=y.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=n("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await P.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await P.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),o={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await P.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 t=e||this.sessionId,n=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.readFile(n,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading messages:",e),[]}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n&&t.push({id:o,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)t.push({id:o,timestamp:r,role:"assistant",input:e.content,images:[]});else if(Array.isArray(e.content)){for(const r of e.content)if("text"===r.type)n+=r.text;else if("tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=pn(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}else if("server_tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=pn(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}n.trim()&&t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]})}}}return t}async loadSession(e){const t=e||this.sessionId,n=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.readFile(n,"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(),t=_SessionManager.getCurrentProjectDirName(),n=y.join(e,t);try{return(await P.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=y.join(e,t);try{return await P.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=y.join(_SessionManager.getProjectsBasePath(),e);try{try{await P.access(t)}catch{return[]}const e=(await P.readdir(t)).filter(e=>e.endsWith(".jsonl")),n=[];for(const r of e){const e=r.replace(".jsonl",""),o=y.join(t,r);try{const r=await P.stat(o),a=(await P.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(a.length>0){let o="",s="";const i=JSON.parse(a[0]);i.gitBranch&&(s=i.gitBranch);for(const e of a){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}n.push({id:e,createdAt:r.birthtime.toISOString(),lastModified:r.mtime.toISOString(),firstMessage:o||"No messages",messageCount:a.length,projectPath:t,gitBranch:s||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return n.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 t=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await P.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.unlink(e)}catch(e){}}getCheckpointsFilePath(){return y.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 P.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 a=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await P.writeFile(r,a)}else await P.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 P.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 P.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 a=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await P.writeFile(r,a)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return await this.saveMessages(r),r}},Qn=new Se("AgentExecutor");function agentToTool(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;return{name:e.name,description:e.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(t,s)=>{let i=getAvailableTools(e,{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a});if(s?.onFeedUpdate){const n=pn(e.name,t),r={id:`${e.name}-tool-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Running..."};s.onFeedUpdate(r)}const c=await getConfiguredProvider(),l=await isOAuthEnforced();let d;c===Ne&&(d=await Ue.getValidAccessToken(),validateOAuthToken({token:d,provider:c}));const u=getApiBaseUrl(),m=new ht({baseUrl:u});let g=0;const p=[];if(Array.isArray(t?.messages)&&t?.messages.length>0)for(const e of t.messages)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&p.push({role:"user",content:t})}const h={stream:!0,messages:p,max_tokens:64e3,system:e.systemPrompt,temperature:.3,tools:i,model:`anthropic:${getConfiguredModel()}`},y=await isTasteLearningEnabled(),w={[Ie]:Xn.getCurrentProjectDirName(),[De]:y.toString(),[xe]:l.toString()};d&&(w[$e]=`Bearer ${d}`);const E=getEnvironmentContext(),b=await getMemoryContent([]),v=crypto.randomUUID();let k="",C=!0;for(;C;){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");if(0===g&&p.length>0){const e=p[p.length-1];g=estimateTokens(e)}const e=await callAPIWithRetry({request:m,body:{mode:"custom-agent",config:E,memory:b,threadId:v,params:{...h,messages:p}},headers:w,abortSignal:s?.abortSignal,onTextDelta:__name(e=>{g+=estimateTokens(e)},"onTextDelta")}),t=e.content.filter(e=>"tool_use"===e.type);if(k=e.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(e,s):e.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===t.length){const t=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);t.length>0&&p.push({role:"assistant",content:t}),C=!1;break}const n=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);n.length>0&&p.push({role:"assistant",content:n});const r=[],o=new Set;let a=!1;for(const e of t){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");let t=e.input;try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&s?.onPermissionRequest&&!await s.onPermissionRequest(e.name,t)){Qn.debug(`Permission denied for tool: ${e.name}`),a=!0;break}if("object"==typeof t&&null!==t){const n={...t};let r=!1;const o=["path","file_path","absolutePath","filePath","directory","folder"];for(const e of o)if(e in n&&"string"==typeof n[e]){const t=n[e];if(!f.isAbsolute(t)){const o=f.resolve(process.cwd(),t);n[e]=o,r=!0,Qn.debug(`Converted '${e}': '${t}' -> '${o}'`)}}"paths"in n&&Array.isArray(n.paths)&&(n.paths=n.paths.map(e=>"string"!=typeof e||f.isAbsolute(e)?e:(r=!0,f.resolve(process.cwd(),e)))),r?(t=n,Qn.debug(`Resolved input for ${e.name}: ${JSON.stringify(t,null,2)}`)):Qn.debug(`No path resolution needed for ${e.name}: ${JSON.stringify(t,null,2)}`)}if(s?.onFeedUpdate){const n=pn(e.name,t),r={id:`${e.name}-${e.id}-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Processing…"};s.onFeedUpdate(r)}const n=await executeTool(e.name,t,s),i=estimateTokens(n);if(g+=i,s?.abortSignal?.aborted)throw new Error("Interrupted by user");const c=checkToolOutputTokensLimit(n,e.name);if(r.push({type:"tool_result",tool_use_id:e.id,content:c}),o.add(e.id),s?.onFeedUpdate){const n=pn(e.name,t),r={id:`${e.name}-${e.id}-complete-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:c};s.onFeedUpdate(r)}Qn.debug(`Tool executed successfully: ${e.name}`)}catch(n){const a=n instanceof Error?n.message:"Unknown error";if(r.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${a}`,is_error:!0}),o.add(e.id),s?.onFeedUpdate){const n=pn(e.name,t),r={id:`${e.name}-${e.id}-error-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:`Error: ${a}`};s.onFeedUpdate(r)}Qn.error(`Tool execution failed: ${e.name} - ${a}`)}}if(a){const e=p[p.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:p.pop()}C=!1;break}const i=[...r];p.push({role:"user",content:i})}return k||"DONE"},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;let s=[];if("*"===e.tools)s=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){const t=a[e];if(t){const e=o.get(t);if(e)s.push(e);else{const e=r.find(e=>e.name===t);e&&s.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){const e=a[t];if(e){const t=o.get(e);if(t)s.push(t);else{const t=r.find(t=>t.name===e);t&&s.push(t)}}}return s}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:a}=e;let s=null;for(let e=0;e<5;e++)try{const e=await t.post({body:n,stream:!0,endpoint:Fe.ALPHA.GENERATE,signal:o,headers:r}),s=de.fromReadableStream(e);a&&s.on("text",a);let i=null;s.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await s.finalMessage();if(i)throw i;return c}catch(t){if(s=t,isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Qn.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n))}throw s||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 it&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof lt||403===e?.status}function isRetryableError(e){return!!e?.message&&!!['Unexpected event order, got error before "message_start"',"API Error: Unexpected event order","Body is unusable: Body has already been read"].some(t=>e.message.includes(t))}function formatAPIError(e,t){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||t?.aborted)return new Error("Interrupted by user");if(e instanceof it&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof lt||403===e?.status)return e;if(e?.message?.startsWith("Error:"))return e;let n="Error: ";return e.message?n+="Something went wrong. Please try again or contact support if the issue persists.":e.toString?n+=e.toString():n+="Unknown error occurred",new Error(n)}function processServerToolBlocks(e,t){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let n="";for(const r of e.content)if("text"===r.type)n+=r.text;else if("server_tool_use"===r.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const e=pn(r.name,r.input),n=Wt(r.name)?"Found 10 results":"Content fetched",o={id:`${r.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:r.name,input:e,output:n};t.onFeedUpdate(o)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}__name(agentToTool,"agentToTool"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks");var er=new Map,tr=null;function initializeAgentManager(e){tr=e}async function loadAgentTools(){if(!tr)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");const{personal:e,project:t}=await loadAllAgents();er.clear();const n=[...e,...t];for(const e of n){const t=agentToTool(e,tr);er.set(t.name,t)}}async function getAgentTools(){return 0===er.size&&await loadAgentTools(),Array.from(er.values())}async function getAgentTool(e){return 0===er.size&&await loadAgentTools(),er.get(e)}function isPathInTasteDirectory(e){const{filePath:t,projectRoot:n}=e,r=f.join(n,".commandcode","taste"),o=f.normalize(f.resolve(n,t)),a=f.normalize(r);return o.startsWith(a)}function getTasteFileInfo(e){const t=f.normalize(f.resolve(e)),n=f.normalize(f.join(process.cwd(),".commandcode","taste")),r=f.normalize(f.join(C.homedir(),".commandcode","taste"));let o=null;if(t.startsWith(n)?o=n:t.startsWith(r)&&(o=r),!o)return{isTaste:!1};if(!t.endsWith("taste.md"))return{isTaste:!1};const a=f.relative(o,t).split(f.sep);return 1===a.length?{isTaste:!0}:2===a.length?{isTaste:!0,category:a[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),__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");var nr=[vn,In,Rn,Nn,Un,Wn,Hn,Kn,Jn,Yn],rr=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],or=new Map(nr.map(e=>[e.name,e]));async function executeTool(e,t,n){let r=or.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from(or.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: ",""))}try{return!or.has(e)&&n?await r.execute(t,n):await r.execute(t)}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message)throw e;return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}async function getToolSchemas(){return[...nr.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...(await getAgentTools()).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...rr]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var ar={};nr.forEach(e=>{ar[e.name]=toPascalCase(e.name)}),rr.forEach(e=>{ar[e.name]=toPascalCase(e.name)});var sr={};Object.entries(ar).forEach(([e,t])=>{sr[t]=e}),initializeAgentManager({clientTools:nr,serverTools:rr,toolsMap:or,displayNameToToolName:sr});var ir=class _PathSanitizer{static{__name(this,"PathSanitizer")}projectRoot;homeDir;options;constructor(e={}){this.projectRoot=e.projectRoot||process.cwd(),this.homeDir=this.getHomeDirectory(),this.options={projectRoot:this.projectRoot,useHomeShorthand:e.useHomeShorthand??!0,customReplacements:e.customReplacements||[]}}sanitizeMessage(e){if(!e)return e;const t=JSON.parse(JSON.stringify(e)),n=t.message||t;return"string"==typeof n.content?n.content=this.sanitizeText(n.content):Array.isArray(n.content)?n.content=n.content.map(e=>"text"===e.type&&"string"==typeof e.text?{...e,text:this.sanitizeText(e.text)}:"tool_use"===e.type&&e.input?{...e,input:this.sanitizeToolInput(e.input)}:e):n.content&&"object"==typeof n.content&&(n.content.input&&(n.content.input=this.sanitizeText(n.content.input)),n.content.output&&(n.content.output=this.sanitizeText(n.content.output))),t.message&&(t.message=n),t.metadata&&(t.metadata=this.sanitizeObject(t.metadata)),t}sanitizeToolInput(e){if(!e||"object"!=typeof e)return e;const t={...e},n=["absolutePath","filePath","path","file_path"];for(const e of n)t[e]&&"string"==typeof t[e]&&(t[e]=this.sanitizePath(t[e]));return t.directory&&"string"==typeof t.directory&&(t.directory=this.sanitizePath(t.directory)),t.content&&"string"==typeof t.content&&(t.content=this.sanitizeText(t.content)),t}sanitizeText(e){if(!e||"string"!=typeof e)return e;let t=e;for(const{pattern:e,replacement:n}of this.options.customReplacements)t=t.replace(e,n);return t=this.replaceAbsolutePaths(t),t}sanitizePath(e){if(!e||"string"!=typeof e)return e;if(!y.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=y.relative(this.projectRoot,e);if(!t.startsWith("../../../"))return t.startsWith("../")?t:`./${t}`}catch(e){}if(this.options.useHomeShorthand&&e.startsWith(this.homeDir))return e.replace(this.homeDir,"~");const t=y.basename(e);return y.dirname(e),this.isUserPath(e)?`<user-home>/${y.relative(this.homeDir,e)}`:`<system-path>/${t}`}replaceAbsolutePaths(e){return e.match(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g),(e=e.replace(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g,e=>this.sanitizePath(e))).match(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g),(e=e.replace(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g,e=>this.sanitizePath(e))).match(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g),e.replace(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g,(e,t)=>e.substring(0,e.length-t.length)+this.sanitizePath(t))}sanitizeObject(e){if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.sanitizeObject(e));const t={};for(const[n,r]of Object.entries(e))t[n]="string"==typeof r?this.sanitizeText(r):"object"==typeof r?this.sanitizeObject(r):r;return t}isWindowsAbsolutePath(e){return/^[A-Za-z]:\\/.test(e)}isUserPath(e){return e.includes("/Users/")||e.includes("/home/")||e.includes("\\Users\\")}getHomeDirectory(){return process.env.HOME||process.env.USERPROFILE||""}static forProject(e){return new _PathSanitizer({projectRoot:e,useHomeShorthand:!0})}static sanitizeMessage(e,t){return _PathSanitizer.forProject(t).sanitizeMessage(e)}static sanitizeMessages(e,t){const n=_PathSanitizer.forProject(t);return e.map(e=>n.sanitizeMessage(e))}},cr=new class extends me{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;addEvent(e){const{type:t,message:n,details:r}=e,o={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r};this.events.unshift(o),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",o)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}};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}),a=new Map(r.map(e=>[e.text,e.confidence])),s=[],i=[],c=[];return o.forEach(e=>{const t=a.get(e.text);void 0===t?s.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:s,upgraded:i,downgraded:c}}__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings");var lr=__name((e,t)=>{},"dlog"),dr=new Se("LearningAgent"),ur=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=5;request;projectRoot;tasteDir;sessionId;constructor(e){this.request=e.request,this.sessionId=e.sessionId,this.projectRoot=e.projectRoot,this.tasteDir=f.join(e.projectRoot,".commandcode","taste")}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)this.pendingMessages=t;else if(0!==t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length){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)}}catch(e){cr.addEvent({type:"error",message:"learning pass failed",details:e instanceof Error?e.message:String(e)}),this.lastProcessedMessageIndex=t.length-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)];cr.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),a=t.length-this.lastProcessedMessageIndex-1,s=Math.max(20,a),i=Math.max(0,t.length-s),c=t.slice(i);let l=0,d=!1;lr("New messages count",a),lr("Context window size",s),lr("Sending conversation messages",c.length);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){lr(`Starting learning turn ${l+1}/${this.maxTurns}`);const e=await this.callLearningAPI({conversation:u});lr("Received response from learning API"),lr("Response content blocks",e.content.length);const t=this.extractToolCalls({content:e.content});if(lr("Extracted tool calls",t.length),t.length>0&&lr("Tool calls",t.map(e=>({name:e.name,id:e.id}))),0===t.length){lr("No tool calls found, checking for text response");const t=e.content.filter(e=>"text"===e.type);if(t.length>0){const e=t[0].text||"";lr("Text response from LLM",e.substring(0,300))}break}lr("Executing tools");const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});lr("Tools executed, learnings found?",r),r&&(d=!0),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&dr.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||cr.addEvent({type:"no_learnings",message:"no changes to taste"}),cr.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{lr(`Executing tool: ${e.name}`),this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",a="";if("write_file"===e.name||"edit_file"===e.name){lr("Tool is write/edit, will track changes");const e=t;if(a=String(e.filePath||e.file_path||""),a)try{o=await F.promises.readFile(a,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const s=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&a)try{i=await F.promises.readFile(a,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=a.replace(`${this.projectRoot}/`,"");lr("Target file path",e);const t=compareLearnings({oldText:o,newText:i});lr("Diff results",{added:t.added.length,upgraded:t.upgraded.length,downgraded:t.downgraded.length}),t.added.forEach(t=>{cr.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{cr.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{cr.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:s})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(e){const{toolName:t,input:n}=e,r={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(!r||!n[r])return;const o=String(n[r]);if(f.isAbsolute(o))throw new Error(`Security: ${t} received absolute path. Only taste-relative paths are allowed (e.g., " .commandcode/taste/cli/taste.md" or " .commandcode/taste/taste.md"). Attempted: ${o}`);const a=f.join(this.tasteDir,o);if(!f.normalize(a).startsWith(this.tasteDir))throw new Error(`Security: ${t} can only access files within .commandcode/taste/. Attempted: ${o}`)}adjustPathsForTaste(e){const{toolName:t,input:n}=e,r={...n},o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(o&&r[o]){const e=String(r[o]);let n;const a="write_file"===t||"edit_file"===t;if(f.isAbsolute(e)&&e.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(e))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${e}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);n=e}else n=e;else{if(f.isAbsolute(e))throw new Error(`Invalid path: Absolute path outside taste directory: ${e}`);if(n=e.startsWith(".commandcode/taste")?e.replace(".commandcode/taste",this.tasteDir):f.join(this.tasteDir,e),a&&!this.isValidTasteFilePath(n))throw new Error(`Invalid adjusted path: ${n}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}r[o]=n}return r}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isValidTasteFilePath(e))throw new Error(`Security: Invalid taste file path. Only allowed:\n - {project}/.commandcode/taste/taste.md\n - {project}/.commandcode/taste/{category}/taste.md\nAttempted: ${e}`)}async initializeTasteDirectory(){if(!F.existsSync(this.tasteDir)){F.mkdirSync(this.tasteDir,{recursive:!0});const e=f.join(this.tasteDir,"taste.md");F.writeFileSync(e,"","utf-8")}}async reorganizeIfNeeded(){const e=f.join(this.tasteDir,"taste.md");if(!F.existsSync(e))return!1;const t=F.readFileSync(e,"utf-8"),n=this.parseCategories({content:t}).filter(e=>e.learningCount>5);if(0===n.length)return!1;let r=t;for(const e of n){const t=e.name.toLowerCase().replace(/\s+/g,"-"),n=f.join(this.tasteDir,t),o=f.join(n,"taste.md");F.mkdirSync(n,{recursive:!0}),cr.addEvent({type:"refactored",message:`moved: ${e.name} package`,details:`moved to ${t}/taste.md`});const a=`# ${e.name}\n${e.learnings.join("\n")}\n`;F.writeFileSync(o,a,"utf-8");const s=`# ${e.name}\nSee [${t}/taste.md](${t}/taste.md)\n`;r=r.replace(e.fullSection,s)}return F.writeFileSync(e,r,"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 F.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(e){const{dir:t,prefix:n}=e,r=F.readdirSync(t,{withFileTypes:!0});let o="";for(let e=0;e<r.length;e++){const a=r[e],s=e===r.length-1,i=s?"└── ":"├── ";if(a.isDirectory()){o+=`${n}${i}${a.name}/\n`;const e=n+(s?" ":"│ ");o+=await this.buildTree({dir:f.join(t,a.name),prefix:e})}else if("taste.md"===a.name){const e=(F.readFileSync(f.join(t,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${n}${i}${a.name} (${e} learnings)\n`}else o+=`${n}${i}${a.name}\n`}return o}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===Ne&&(o=await Ue.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const a={[Ie]:Xn.getCurrentProjectDirName(),[xe]:r.toString()};o&&(a[$e]=`Bearer ${o}`);let s=0,i=null;for(;s<=this.maxApiRetries;)try{return await this.request.post({endpoint:Fe.ALPHA.TASTE.LEARN,body:{conversation:t,tools:await this.getTasteTools(),model:`anthropic:${getConfiguredModel()}`,threadId:this.sessionId},headers:a})}catch(e){if(i=e instanceof Error?e:new Error(String(e)),s++,s>this.maxApiRetries)throw i;const t=2e3*Math.pow(2,s);await this.sleep({ms:t})}throw i||new Error("API call failed")}sleep(e){const{ms:t}=e;return new Promise(e=>setTimeout(e,t))}static async isInitialized(e){const{projectRoot:t}=e,n=f.join(t,".commandcode","taste");return F.existsSync(n)}};async function getTasteContent(){try{const e=process.cwd(),t=f.join(e,".commandcode","taste","taste.md");if(!M(t))return null;const n=await S.readFile(t,"utf-8"),r=n.trim();return r&&"# Taste (Continuously Learned by CommandCode.ai)"!==r&&"# Taste (Continuously Learned by CommandCode)"!==r?n:null}catch(e){return null}}__name(getTasteContent,"getTasteContent");var mr=new Se("ContextEngine"),gr=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];learningAgent;checkpointManager;constructor(e,t){const n=getApiBaseUrl();this.request=new ht({baseUrl:n}),this.callbacks=e,this.sessionManager=new Xn(t),this.learningAgent=new ur({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}createSessionStoreAdapter(){return{saveSnapshot:__name(async e=>{await this.sessionManager.saveSnapshot(e)},"saveSnapshot"),loadSnapshots:__name(async()=>this.sessionManager.loadSnapshots(),"loadSnapshots"),deleteSnapshotsAfter:__name(async e=>{await this.sessionManager.deleteSnapshotsAfter(e)},"deleteSnapshotsAfter"),getMessageAtIndex:__name(e=>this.sessionManager.getMessageAtIndex({index:e.index,messages:this.messages}),"getMessageAtIndex"),getMessageIndexById:__name(e=>this.sessionManager.getMessageIndexById({messageId:e.messageId,messages:this.messages}),"getMessageIndexById"),truncateMessagesAtIndex:__name(async e=>{const t=await this.sessionManager.truncateMessagesAtIndex({index:e.index,messages:this.messages});this.messages=t},"truncateMessagesAtIndex"),getMessageCount:__name(()=>this.sessionManager.getMessageCount({messages:this.messages}),"getMessageCount")}}setupCheckpointSessionStore(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),this.checkpointManager.runCleanup().catch(()=>{})}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,mr.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)&&t.message.content.some(e=>"tool_use"===e.type)&&(this.messages.pop(),mr.debug("Removed assistant message with pending tool calls to prevent API errors")),e){this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[{type:"text",text:"Interrupted by user"}]}));const e=Qt("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>mr.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t){let n=e,r=[];try{const t=await processFileReferences(e);if(n=t.processedContent,r=t.fileReferences,r.length>0){const e=r.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}const o=Qt(e);t&&t.length>0&&(o.metadata={...o.metadata,images:t}),r&&r.length>0&&(o.metadata={...o.metadata,fileReferences:r}),this.callbacks.onFeedUpdate(o);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&a.push({type:"text",text:n});const s={role:"user",content:a},i=crypto.randomUUID(),c=this.createMessageWithMeta(s,{messageId:i});return this.addMessageAndSync(c),this.checkpointManager.createSnapshot({messageId:i}).catch(e=>mr.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,o).catch(e=>mr.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent(),await this.processMessages()}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){mr.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}async processMessages(){let e="";this.abortController=new AbortController;let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.updateContextUsage(o);const a=o.content.filter(e=>"tool_use"===e.type),s=o.content.filter(e=>"server_tool_use"===e.type);if(e=s.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===a.length){const t=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===s.length){const t=tn(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>mr.error(`Failed to save messages: ${e}`))}if(0!==s.length&&this.sessionManager.saveMessages(this.messages).catch(e=>mr.error(`Failed to save messages: ${e}`)),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0){const t=[];for(const n of e){t.push({type:"text",text:n});const e=Qt(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>mr.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const i=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(i.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:i})),e.trim()){const t=tn(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:a}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=Qt(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>mr.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&mr.debug("Request interrupted or insufficient credits"),this.formatAPIError(e)}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const t=await this.sessionManager.loadMessages(e);this.messages=t,await this.loadCheckpoints();const n=this.sessionManager.reconstructFeedFromMessages(t);return mr.debug(`Loaded session ${e} with ${t.length} messages`),n}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async 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 a=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],s=n.message.role;if(e&&t>=r&&-1!==r)a.push(n);else{if("user"===s){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}a.push(n)}else a.push(n)}else if("assistant"===s){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?a.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&a.push(n)}"user"!==s&&"assistant"!==s&&(o+=estimateTokens(n.message))}}this.messages=a,await this.sessionManager.saveMessages(this.messages);const s=Math.max(0,n-o);return this.contextTokensUsed=s,this.callbacks.onContextUsageUpdate?.({current:s,limit:Zn}),{messagesRemoved:t-a.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){}}))}async syncMessageToShare(e,t){try{const n=ir.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Fe.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.abortController?.signal.aborted)throw new Error("Interrupted by user")}initializeInteractionTokens(){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message)}async prepareAPICall(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(t),t===Ne&&(r=await Ue.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId()};mr.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${e.length} tools, streaming: true`);const s=await isTasteLearningEnabled(),i={[Ie]:Xn.getCurrentProjectDirName(),[De]:s.toString(),[xe]:n.toString()};return r&&(i[$e]=`Bearer ${r}`),{body:a,headers:i}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++)try{const t=await this.request.post({body:e.body,stream:!0,endpoint:Fe.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers}),n=de.fromReadableStream(t);n.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let r=null;n.on("error",e=>{r="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const o=await n.finalMessage();if(r)throw r;return this.callbacks.onRetryUpdate?.(null),o}catch(e){if(t=e,this.isNonRetryableError(e))throw this.formatAPIError(e);if(9===n)throw this.callbacks.onRetryUpdate?.(null),this.formatAPIError(e);const r=Math.min(n,10),o=100*Math.pow(2,r),a=Math.max(o,1e3),s=Math.min(a,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await new Promise(e=>setTimeout(e,s))}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||this.abortController?.signal.aborted||e instanceof it&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof lt||403===e?.status}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=e.message?.toLowerCase().includes("insufficient credits");if(t)return new Error("Insufficient credits");const n=e.message?.toLowerCase().includes("oauth authentication required");if(n)return e;if(e instanceof lt||403===e?.status)return e;let r="Error: ";return e.message?e.message.includes("Invalid 'Authorization' header")?r+='Authentication failed. Run "cmd login" to sign in again.':r+='Something went wrong. Type "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord.':e.toString?r+=e.toString():r+="Unknown error occurred",new Error(r)}async executeToolBlocks(e){const t=[],n=new Set;let r=!1;for(const o of e.toolBlocks){this.checkIfInterrupted();try{const e=await this.checkToolPermission(o);if(e.needsPermission&&!e.allowed){this.handlePermissionDenied(o),r=!0;break}const a=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:a}),n.add(o.id),this.showToolSuccess(o,a)}catch(e){const r=e instanceof Error?e.message:"Unknown error";t.push({type:"tool_result",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}),n.add(o.id),this.showToolError(o,r)}}return{toolResults:t,executedToolIds:n,permissionDenied:r}}async checkToolPermission(e){return["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=await executeTool(e.name,e.input,{onPermissionRequest:this.callbacks.onPermissionRequest,abortSignal:this.abortController?.signal,onFeedUpdate:this.callbacks.onFeedUpdate});this.checkIfInterrupted();const n=checkToolOutputTokensLimit(t,e.name),r=estimateTokens(n);return this.currentInteractionTokens+=r,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),n}handlePermissionDenied(e){const t=pn(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=nn(e.name,t,n),o=sn(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}showToolSuccess(e,t){let n="edit_file"===e.name?e.input:void 0;if("read_file"===e.name){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(n={...n||{},isTasteFile:!0,tasteCategory:e.category})}}const r={...e.input,...n?.isTasteFile?{isTasteFile:n.isTasteFile}:{},...n?.tasteCategory?{tasteCategory:n.tasteCategory}:{}},o=pn(e.name,r),a=nn(e.name,o,n),s=sn(a,t);this.callbacks.onFeedUpdate(s)}showToolError(e,t){const n=pn(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=nn(e.name,n,r),a=sn(o,cn(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let t="";for(const n of e.content)if("text"===n.type)t+=n.text;else if("server_tool_use"===n.type){if(t.trim()){const e=tn(t.trim());this.callbacks.onFeedUpdate(e),t=""}const e=pn(n.name,n.input),r=nn(n.name,e),o=Wt(n.name)?"Found 10 results":"Content fetched",a=sn(r,o);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=tn(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:Zn}),this.checkAndCompactIfNeeded()}async checkAndCompactIfNeeded(){const e=Math.floor(17e4);if(this.contextTokensUsed>e){mr.debug(`Context tokens (${this.contextTokensUsed}) exceeded threshold (${e}), triggering automatic compaction`);try{const e=await this.compactConversation({preserveCurrentInteraction:!0});mr.debug(`Automatic compaction completed: removed ${e.messagesRemoved} messages, saved ${e.tokensSaved} tokens`)}catch(e){mr.error(`Failed to automatically compact conversation: ${e}`)}}}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 a=await this.checkpointManager.restore({messageId:t,mode:n});return!a.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Zn})),a}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}};function Markdown({children:e,...t}){const n={...t};he({renderer:new ye(n),breaks:!0,gfm:!0});const r=fe(e);return U.createElement(K,null,r.toString().trim())}function AssistantMessage({content:e}){return U.createElement(q,null,U.createElement(K,null,a.nodejs),U.createElement(q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},U.createElement(Markdown,null,e)))}__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var pr={"Interrupted by user":"Interrupted by user","Insufficient credits":Be};function UserMessage({content:e}){const t="Interrupted by user"===e,n="Insufficient credits"===e,r=e.startsWith("Error:"),o=t||n||r;let s=o&&pr[e]||e;return U.createElement(q,{paddingX:1,backgroundColor:o?void 0:"#333333"},U.createElement(K,{color:o?"red":"#AAAAAA",bold:!o},a.pointer),U.createElement(q,{marginLeft:1},U.createElement(K,{color:o?"red":"white",wrap:"wrap"},s)))}__name(UserMessage,"UserMessage");var hr="#6B7280";function truncateToolOutputForDisplay(e){const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),n=t.split("\n");if(n.length<=1)return t;const r=n.slice(0,1).join("\n");return n.length,r}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:a=2,dimDiff:s=!1,maxLines:i}){const c=we.diffLines(e,t);let l=0,d=0,u=0,m=0;c.forEach(e=>{e.added?(l+=e.count||1,m+=e.count||1):e.removed&&(d+=e.count||1,m+=e.count||1)});const g=[];c.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(u++,g.push(U.createElement(q,{key:`${t}-${r}-removed`,width:"100%"},U.createElement(K,{color:"gray",dimColor:s},u.toString().padStart(3)," "),U.createElement(q,{backgroundColor:"#712F37"},U.createElement(K,{dimColor:s},"-"),U.createElement(K,{dimColor:s}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(U.createElement(q,{key:`${t}-${r}-added`,width:"100%"},U.createElement(K,{color:"gray",dimColor:s},u.toString().padStart(3)," "),U.createElement(q,{backgroundColor:"#325B30"},U.createElement(K,{dimColor:s},"+"),U.createElement(K,{dimColor:s}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:U.createElement(q,{flexDirection:"column"},o&&!r&&U.createElement(K,{color:"gray"},"Updated"," ",U.createElement(K,{color:"white",bold:!0},n)," ","with ",U.createElement(K,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",U.createElement(K,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&U.createElement(K,{color:"red"},"Rejected update to",U.createElement(K,{color:"red"},` ${n}`)),U.createElement(q,{flexDirection:"column",marginLeft:a},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=hn(e);return t?U.createElement(q,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?"☒":"☐";let r,o=!1;switch(e.status){case"completed":r="#22C55E",o=!0;break;case"in_progress":r="#E4CCFF";break;default:r="white"}return U.createElement(q,{key:e.id||t,flexDirection:"row"},U.createElement(q,{width:2},U.createElement(K,{color:r},n)),U.createElement(K,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):U.createElement(K,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const c="Thinking…"===e,l="Todos"===e,d="Edit"===e,u=!0===s?.isTasteFile,m=s?.tasteCategory,g=!0===s?.permissionDenied,p=!c&&t&&!u,h=!c&&!l&&!u,{name:f}=detectTerminal(),y="iTerm2"===f?"shift":"ctrl";let w,E;if(r)w="yellow",E="→";else if(o)w="red",E=a.nodejs;else if(c)w=hr,E="✻";else if(l&&n){const e=hn(n),t=e?.every(e=>"completed"===e.status);w=t?"#22C55E":"#D4A017",E=a.nodejs}else w="#22C55E",E=a.nodejs;return U.createElement(q,null,c&&U.createElement(K,{color:w},E),U.createElement(q,{flexDirection:"column",marginLeft:c?1:0},U.createElement(q,null,c?U.createElement(U.Fragment,null,U.createElement(K,{color:hr},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!i&&U.createElement(K,{dimColor:!0},"(",`${y}+o to expand`,")")):u?U.createElement(U.Fragment,null,U.createElement(K,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),U.createElement(K,null," ","Using your taste ",m?"package of ":"packages",m&&U.createElement(K,{bold:!0},m))):U.createElement(K,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),p&&U.createElement(K,null," ",U.createElement(Markdown,null,`(${t})`))),n&&!u&&U.createElement(q,{columnGap:1,marginLeft:h?1:0},h&&U.createElement(K,null,"⎿"," "),l?formatTodosForDisplay(n):c?i?U.createElement(q,{width:"100%",flexDirection:"column"},U.createElement(K,null," "),U.createElement(K,{color:hr,wrap:"wrap",italic:!0},n)):null:d&&s?.oldValue&&s?.newValue?U.createElement(q,{flexDirection:"column"},(()=>{const e=i?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:g,permissionDenied:g,maxLines:e});return U.createElement(U.Fragment,null,n,r&&U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"… (",o-10," more lines) (",`${y}+o to expand`,")")))})(),g&&n&&U.createElement(q,{marginTop:1},U.createElement(K,{color:"red",wrap:"wrap"},n))):U.createElement(q,{width:"100%"},U.createElement(K,{color:o?"red":"",wrap:"wrap"},i?n:U.createElement(U.Fragment,null,truncateToolOutputForDisplay(n),n.includes("\n")&&U.createElement(K,{dimColor:!0}," ","(",`${y}+o to expand`,")"))))),r&&U.createElement(q,{columnGap:1,marginLeft:1},U.createElement(K,null,"⎿"," "),U.createElement(K,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,a;return n?(o="yellow",a="→"):r?(o="red",a="✗"):(o="green",a="✓"),U.createElement(q,null,U.createElement(K,{color:o},a),U.createElement(q,{flexDirection:"column",marginLeft:1},U.createElement(q,null,U.createElement(K,{color:"gray"},"$ "),U.createElement(K,{color:o,bold:!0},e)),U.createElement(q,{columnGap:1,marginLeft:1},U.createElement(K,null,"⎿"," "),U.createElement(K,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function loadCustomCommands(){const e=[],t=y.join(process.cwd(),".commandcode","commands"),n=y.join(T.homedir(),".commandcode","commands");function loadCommandsFromDirectory(t,n,r=""){if(R.existsSync(t))try{const o=R.readdirSync(t,{withFileTypes:!0});for(const a of o){const o=y.join(t,a.name);if(a.isDirectory())loadCommandsFromDirectory(o,n,r?`${r}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const t=y.basename(a.name,".md"),s=R.readFileSync(o,"utf-8").trim();e.push({name:t,source:n,content:s,subdirectory:r})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(n,"user"),loadCommandsFromDirectory(t,"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(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent");var fr=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.COMPACT="/compact",e.REWIND="/rewind",e))(fr||{}),yr=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}];function truncateText(e){const{text:t,maxWidth:n}=e;return t.length<=n?t:n<=3?t.substring(0,n):t.substring(0,n-3)+"..."}__name(truncateText,"truncateText");var wr=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=B(0),[a,s]=B(0),{stdout:i}=Y(),c=i?.columns??80,l=Math.max(20,c-12-2-1-2),d=G(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...isInternalFlagPresent()?yr:yr.filter(e=>"/provider"!==e.command)];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),u=G(()=>{const e=a,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,a]);return W(()=>{o(0),s(0)},[n]),J((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<a&&s(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=a+8&&s(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?U.createElement(q,{flexDirection:"column",paddingLeft:2},U.createElement(K,{color:"dim"},"No commands found")):(d.length,U.createElement(q,{flexDirection:"column",paddingLeft:1},U.createElement(q,{columnGap:2},U.createElement(q,{flexDirection:"column",width:12},u.map((e,t)=>{const n=a+t;return U.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),U.createElement(q,{flexDirection:"column"},u.map((e,t)=>{const n=a+t;return U.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateText({text:e.description,maxWidth:l}))})))))},"CommandMenu");function HelpMessage(){const e=yr.filter(e=>"/help"!==e.command&&"/provider"!==e.command),t=Math.max(...e.map(e=>e.command.length))+2;return U.createElement(q,{flexDirection:"column",paddingY:1},U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(q,null,U.createElement(K,{bold:!0},"Command Code"),U.createElement(K,{color:"gray"}," v","0.9.5")),U.createElement(K,{color:"gray"},"Coding agent that continuously learns your taste of writing code.")),U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{bold:!0},"KEYBOARD SHORTCUTS"),U.createElement(q,{flexDirection:"column",paddingLeft:2,marginTop:1},U.createElement(q,null,U.createElement(K,null,"Shift+Tab".padEnd(15)),U.createElement(K,{color:"gray"},"Toggle auto-accept mode")),U.createElement(q,null,U.createElement(K,null,"Ctrl+T".padEnd(15)),U.createElement(K,{color:"gray"},"Toggle learning feed")),U.createElement(q,null,U.createElement(K,null,"Ctrl+O".padEnd(15)),U.createElement(K,{color:"gray"},"Toggle expanded tool output (Shift+O in iTerm2)")),U.createElement(q,null,U.createElement(K,null,"Esc Esc".padEnd(15)),U.createElement(K,{color:"gray"},"Rewind to previous checkpoint")),U.createElement(q,null,U.createElement(K,null,"/".padEnd(15)),U.createElement(K,{color:"gray"},"Open command menu")))),U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{bold:!0},"COMMANDS"),U.createElement(q,{flexDirection:"column",paddingLeft:2,marginTop:1},e.map(e=>U.createElement(q,{key:e.command},U.createElement(K,null,e.command.padEnd(t)),U.createElement(K,{color:"gray"},e.description))))),U.createElement(q,{flexDirection:"column"},U.createElement(K,{bold:!0},"LINKS"),U.createElement(q,{flexDirection:"column",paddingLeft:2,marginTop:1},U.createElement(q,null,U.createElement(K,null,"Documentation".padEnd(25)),U.createElement(K,{color:"cyan"},"https://commandcode.ai/docs")),U.createElement(q,null,U.createElement(K,null,"Discord Community".padEnd(25)),U.createElement(K,{color:"cyan"},"https://commandcode.ai/discord")))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?U.createElement(HelpMessage,null):U.createElement(q,{flexDirection:"column"},U.createElement(K,{wrap:"wrap"},U.createElement(Markdown,null,e)))}function getTerminalWidth(){return process.stdout.columns||80}__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(getTerminalWidth,"getTerminalWidth");var Er=__name(()=>{const e=getTerminalWidth();return e>=70?" \n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":e>=50?"\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":br},"getResponsiveCommandLogo"),br="⌘ CMD\n";function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return U.createElement(q,null,U.createElement(K,{color:"red"},t?a.pointer:a.warning),U.createElement(q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},U.createElement(K,{color:"red"},e)))}function InfoMessage({content:e}){return U.createElement(q,null,U.createElement(K,{dimColor:!0},a.info),U.createElement(q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},U.createElement(K,{dimColor:!0},e)))}function getModelShortName(e){const t=Object.values(je).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet")?"sonnet-4.5":e.includes("opus")?"opus-4.5":"sonnet-4.5"}__name(ErrorMessage,"ErrorMessage"),__name(InfoMessage,"InfoMessage"),__name(getModelShortName,"getModelShortName");var vr=U.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const a=t?["header",...e]:e,s=Er();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~");return U.createElement(V,{items:a,key:n,style:{width:"100%"}},e=>{if("header"===e)return U.createElement(q,{key:"header",marginBottom:1,flexDirection:"column"},U.createElement(pe,{name:"vice"},U.createElement(K,null,s.trimEnd())),U.createElement(q,{flexDirection:"column",marginTop:1},U.createElement(q,null,U.createElement(K,{color:"gray"},"# "),U.createElement(K,{bold:!0},"Command Code"),U.createElement(K,{color:"gray"}," v",i)),U.createElement(K,{color:"gray"},"# models: ",c," · ","taste-1"),U.createElement(K,{color:"gray"},"# ",u)));const t=e,n=(()=>{switch(t.role){case"user":return U.createElement(UserMessage,{content:t.input});case"assistant":return U.createElement(AssistantMessage,{content:t.input});case"tool":return U.createElement(ToolMessage,{name:gn(t.name||""),input:t.input,output:t.output||"",isPending:dn(t),hasError:ln(t),metadata:t.metadata,expandedOutput:r});case"bash":return U.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:dn(t),hasError:ln(t)});case"system":return U.createElement(SystemMessage,{content:t.input});case"info":return U.createElement(InfoMessage,{content:t.input});case"error":return U.createElement(ErrorMessage,{content:t.input});default:return U.createElement(U.Fragment,null)}})();return U.createElement(q,{key:t.id,marginBottom:1,width:"90%"},n)})}),kr=__name(({messages:e})=>0===e.length?null:U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(q,{marginBottom:0},U.createElement(K,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>U.createElement(q,{key:t},U.createElement(K,{dimColor:!0},a.pointerSmall," "),U.createElement(K,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages"),Cr=["·","○","◇","☆","✧","☆","◇","○","⌘"],Tr=[8,5,4,4,4,4,4,5,20],Sr=[5,4,4,4,4,4,5],Pr=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Tr.length;e++)if(n+=Tr[e],t<n)return Cr[e];const r=t-58;n=0;for(let e=0;e<Sr.length;e++)if(n+=Sr[e],r<n)return Cr[7-e];return Cr[0]},"getWaveSymbol"),Ar=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=B(0);W(()=>{const t=setInterval(()=>{n(t=>(t+1)%(e.length+10))},50);return()=>clearInterval(t)},[e.length]);const r=__name(e=>{const n=e-(t-5);return n>=0&&n<Ar.length?Ar[n]:"#B799E6"},"getCharColor");return U.createElement(K,null,e.split("").map((e,t)=>U.createElement(K,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=B(0);return W(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),U.createElement(K,{color:"#E4CCFF",bold:!0},Pr(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var xr=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,a]=B(0),s=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}W(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),o=e>0?t:-t,s=setInterval(()=>{a(e=>{const t=e+o;return o>0&&t>=n||o<0&&t<=n?n:t})},30);return()=>clearInterval(s)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime");const i=s>70,c=s>40&&s<=70;return U.createElement(q,{width:s,height:1,paddingLeft:0,marginLeft:0},U.createElement(CMDIcon,null),U.createElement(q,{marginRight:1},U.createElement(ShimmerText,{text:e})),i?U.createElement(U.Fragment,null,U.createElement(q,{columnGap:1},U.createElement(K,{dimColor:!0},`(${formatTime(t)}`),U.createElement(K,{dimColor:!0},"•"),U.createElement(K,{color:"gray"},o.arrowDown),U.createElement(K,{dimColor:!0},`${formatToken(Math.round(r))}`),U.createElement(K,{dimColor:!0},"•"),U.createElement(q,{columnGap:1},U.createElement(K,{bold:!0,color:"gray"},"esc"),U.createElement(K,{dimColor:!0},"to interrupt)")))):c?U.createElement(q,{columnGap:1},U.createElement(K,{dimColor:!0},`(${formatToken(Math.round(r))})`)):U.createElement(U.Fragment,null))},"Status"),$r=__name(({usage:e})=>{if(!e)return null;const t=__name(e=>e>=1e3?`${Math.round(e/1e3)}K`:e.toString(),"formatNumber"),n=Math.min(e.current/e.limit*100,100),r=__name(e=>e>=90?"red":e>=70?"yellow":"gray","getColor");return U.createElement(q,{paddingRight:1},U.createElement(K,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage");function loadGitignore(e){const t=Ee(),n=E(e,".gitignore");if(M(n))try{const e=N(n,"utf8");t.add(e)}catch{}return t.add(".git"),t}__name(loadGitignore,"loadGitignore");var Ir=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=B(process.cwd()),[a,s]=B([]),[i,c]=B(0),[l,d]=B(0),u=n.trim()?15:10,m=H((e,t=process.cwd())=>{if(!e.trim())return[];const n=loadGitignore(t);if(e.endsWith("/")){const r=E(t,e);try{const e=L(r),o=[];return e.forEach(e=>{const a=E(r,e);try{const e=_(a),r=b(t,a);if(n.ignores(r))return;o.push({name:r,path:a,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{}}if(e.includes("/")){const r=e.split("/"),o=r.pop()||"",a=E(t,r.join("/"));try{const e=L(a),r=[],s=o.toLowerCase();return e.forEach(e=>{const i=e.toLowerCase();if(!o||i.includes(s)){const o=E(a,e);try{const e=_(o),a=b(t,o);if(n.ignores(a))return;r.push({name:a,path:o,isDirectory:e.isDirectory()})}catch{}}}),r.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),r.slice(0,50)}catch{}}const r=[],o=e.toLowerCase(),a=__name((e,s=0)=>{if(!(s>8))try{L(e).forEach(i=>{const c=E(e,i);try{const e=_(c),l=b(t,c);if(n.ignores(l))return;const d=l.toLowerCase();(i.toLowerCase().includes(o)||d.includes(o))&&r.push({name:l,path:c,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==i&&a(c,s+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),r.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),a=n===o,s=r===o;if(a&&!s)return-1;if(!a&&s)return 1;const i=n.split("/").pop()||"",c=r.split("/").pop()||"",l=i.includes(o),d=c.includes(o);if(l&&!d)return-1;if(!l&&d)return 1;const u=e.name.split("/").length,m=t.name.split("/").length;return u!==m?u-m:e.name.localeCompare(t.name)}),r.slice(0,50)},[]),g=H(e=>{try{const t=L(e),n=[],r=process.cwd(),o=loadGitignore(r);"/"!==e&&n.push({name:"..",path:w(e),isDirectory:!0}),t.forEach(t=>{const a=E(e,t);try{const e=_(a),s=b(r,a);if(o.ignores(s))return;n.push({name:t,path:a,isDirectory:e.isDirectory()})}catch{}}),n.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s(n),c(0),d(0)}catch{}},[]);W(()=>{if(n.trim()){const e=m(n);s(e),c(0),d(0)}else g(r)},[r,g,n,m]),J((r,s)=>{if(s.escape)t();else if(s.upArrow)c(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t});else if(s.downArrow)c(e=>{const t=Math.min(a.length-1,e+1);return t>=l+u&&d(t-u+1),t});else{if(s.rightArrow){const e=a[i];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(k(e.path)))}if(s.return){const t=a[i];if(!t)return;return void e(t.path)}}});const p=a.slice(l,l+u);return U.createElement(q,{flexDirection:"column",paddingLeft:1},U.createElement(q,{marginBottom:1,flexDirection:"column"},U.createElement(K,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),U.createElement(K,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===p.length?U.createElement(K,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):p.map((e,t)=>{const n=l+t,r=e.name,o=n===i;return U.createElement(K,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),Dr=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=B([]),[o,s]=B(0),[i,c]=B(!0);W(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await Xn.listSessions();r(e.slice(0,30)),c(!1)},"loadSessions");if(J((r,a)=>{a.escape?t():a.upArrow?s(e=>Math.max(0,e-1)):a.downArrow?s(e=>Math.min(n.length-1,e+1)):a.return&&n.length>0&&o<n.length&&e(n[o].id)}),i)return U.createElement(q,{flexDirection:"column",paddingLeft:2},U.createElement(K,{color:"gray"},"Loading sessions..."));if(0===n.length)return U.createElement(q,{flexDirection:"column",paddingLeft:2},U.createElement(K,{color:"gray"},"No previous sessions found"),U.createElement(K,{color:"dim",dimColor:!0},"Press ESC to go back"));const d=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),a=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${a}d ago`},"formatRelativeTime"),u=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return U.createElement(q,{flexDirection:"column",paddingLeft:1,width:"100%"},U.createElement(K,{color:"cyan",bold:!0},"Resume Session"),U.createElement(K,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),U.createElement(q,{marginTop:1}),U.createElement(q,{columnGap:2,marginBottom:1},U.createElement(q,{width:5},U.createElement(K,{color:"gray"}," ")),U.createElement(q,{width:13},U.createElement(K,{color:"gray"},"Modified")),U.createElement(q,{width:20},U.createElement(K,{color:"gray"},"Git Branch")),U.createElement(q,{width:11},U.createElement(K,{color:"gray"},"# Messages")),U.createElement(q,null,U.createElement(K,{color:"gray"},"Summary"))),U.createElement(q,{columnGap:2},U.createElement(q,{flexDirection:"column",width:5},n.map((e,t)=>U.createElement(K,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${a.pointer} ${t+1}.`:` ${t+1}.`))),U.createElement(q,{flexDirection:"column",width:13},n.map((e,t)=>U.createElement(K,{key:`mod-${e.id}`,color:o===t?"white":"gray"},d(e.lastModified)))),U.createElement(q,{flexDirection:"column",width:20},n.map((e,t)=>U.createElement(K,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),U.createElement(q,{flexDirection:"column",width:11},n.map((e,t)=>U.createElement(K,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),U.createElement(q,{flexDirection:"column"},n.map((e,t)=>U.createElement(K,{key:`summary-${e.id}`,color:o===t?"white":"gray"},u(e.firstMessage))))))},"SessionsResumeTable"),Fr=__name(()=>U.createElement(q,{flexDirection:"column",paddingLeft:1},U.createElement(K,{color:"dim",bold:!0},"Available Shortcuts:"),U.createElement(q,{columnGap:4},U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"dim"},"! for bash mode"),U.createElement(K,{color:"dim"},"/ for commands"),U.createElement(K,{color:"dim"},"@ for file paths"),U.createElement(K,{color:"dim"},"shift + tab to toggle auto-accept")),U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"dim"},"double tap esc to clear input"),U.createElement(K,{color:"dim"},"shift + ⏎ for newline"),U.createElement(K,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Rr=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:g=!1,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,updateStatus:w,updateFailedInfo:E,currentProvider:v,showProviderInfo:k,isOAuthMode:C=!1,autoAcceptMode:T=!1,onToggleAutoAccept:S,hintMessage:P})=>{const[A,x]=B(0),[$,I]=B(!1),[D,F]=B(!1),[R,M]=B(!1),[N,j]=B(!1),[O,L]=B(""),[_,V]=B(!1),[Y,Z]=B(null),[X,ee]=B([]),[te,ne]=B([]),[re,oe]=B(""),[ae,se]=B(""),ie=z(!1),[ce,le]=B(!1),de=G(()=>{const t=(process.stdout.columns||80)-4,n=(e.match(/\n/g)||[]).length;return Math.ceil(Math.max(1,e.length)/t)+n},[e]),[ue,me]=B(!0),ge=z(de);W(()=>{if(de!==ge.current){me(!1);const e=setTimeout(()=>{me(!0)},0);return ge.current=de,()=>clearTimeout(e)}},[de]);const pe=H(()=>{n(""),F(!1),j(!1),L(""),V(!1),ee([]),ne([]),oe(""),le(!1),x(e=>e+1)},[n]),he=H(e=>{if(0===e.length)return e;let t=e.length;for(;t>0&&/\s/.test(e[t-1]);)t--;for(;t>0&&!/\s/.test(e[t-1]);)t--;return e.slice(0,t)},[]),fe=H(()=>{const t=he(e);n(t),x(e=>e+1)},[e,he,n]);J(async(t,r)=>{if(getIsExpandToolShortcut(r,t))return ie.current=!0,n(e),void x(e=>e+1);if(!r.ctrl&&!r.meta&&!r.shift){if(""===t)return void pe();if(""===t)return void fe()}if(r.meta&&r.delete)return ie.current=!0,void fe();if(r.meta&&r.backspace)pe();else if(r.alt&&r.backspace)fe();else{if(r.ctrl&&"w"===t)return ie.current=!0,void fe();if(r.meta&&"w"===t)return ie.current=!0,void pe();if(r.meta&&"v"===t||r.ctrl&&"v"===t){if(r.ctrl&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();if(r){const e=`[Image#${te.length+1}]`;ne(e=>[...e,r]),n(t+e),x(e=>e+1)}return void(ie.current=!0)}}else{if((r.ctrl||r.meta)&&"u"===t)return ie.current=!0,void pe();if(r.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void pe();case"z":return M(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(r.escape){if(_)return V(!1),n(re),void x(e=>e+1);const e=Date.now(),t=500;return Y&&e-Y<t?(pe(),Z(null)):(Z(e),setTimeout(()=>Z(null),t)),I(!1),void F(!1)}$&&(r.backspace||r.delete)&&0===e.length&&I(!1)}}});const ye=H(async t=>{const r=processBracketedPaste(t);if(r.isPasteStart&&!ce){if(le(!0),se(e),!r.isPasteEnd)return;le(!1);const t=await detectClipboardImage();if(t){const r=`[Image#${te.length+1}]`;ne(e=>[...e,t]),n(e+r),x(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>300){const t=`[Text#${X.length+1}]`;ee(t=>[...t,e]),n(ae+t),x(e=>e+1)}else n(ae+e),x(e=>e+1)}return}if(ce&&!r.isPasteEnd)return;if(ce&&r.isPasteEnd){le(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${te.length+1}]`;ne(t=>[...t,e]),n(r.cleanedContent+t),x(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>300){const t=`[Text#${X.length+1}]`;ee(t=>[...t,e]),n(ae+t),x(e=>e+1)}else n(ae+e),x(e=>e+1)}return}if(r.isPasteEnd&&!r.isPasteStart)return;if(ie.current)return void(ie.current=!1);const o=1===t.length,a=t.slice(-1);if(o){if("?"===a&&!$)return I(!0),n(""),void x(e=>e+1);if("!"===a&&!D)return I(!1),F(!0),n(""),void x(e=>e+1);"/"!==a||N||(j(!0),L(""))}if(N){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);L(n)}}"@"!==a||s||(i(!0),l(""));const c=t.lastIndexOf("@");if(t.length<e.length&&-1!==c&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(c+1);!e.includes(" ")&&(i(!0),l(e))}if(s)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),l("");else{const n=t.substring(e+1);l(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);l(e),i(!1)}else l(n)}}$&&(t!==e||t.length<e.length)&&I(!1),0===t.length&&(F(!1),j(!1),L(""),V(!1),ne([]),ee([]),l(""),oe(""),le(!1)),n(t)},[$,e,n,s,i,D,ce,te]),we=H(async()=>{if($)return void I(!1);let n=e.trim();if(!D&&n.startsWith("/"))return d&&d(n),F(!1),j(!1),L(""),ne([]),void ee([]);let r=[];const o=te.length>0,a=X.length>0;if(!D&&o){const e=[];te.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!D&&a){let e=n;X.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:D?"bash":"user",images:r}),F(!1),j(!1),L(""),ne([]),ee([])},[t,d,$,e,D,te]),Ee=H(t=>{const r=b(process.cwd(),t);let o;if(s&&""!==c){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),i(!1),l(""),x(e=>e+1)},[n,i,e,s,c,l]),be=H(()=>{i(!1),l("")},[i,l]),ve=H(t=>{if("/resume"===t)oe(e),j(!1),L(""),V(!0),n(""),x(e=>e+1);else{const e=Object.values(fr).includes(t);j(!1),L(""),e?(n(""),x(e=>e+1),d&&d(t)):(n(t+" "),x(e=>e+1))}},[d,n,e]),ke=H(()=>{j(!1),L(""),n(""),x(e=>e+1)},[n]),Ce=H(e=>{V(!1),n(""),oe(""),x(e=>e+1),d&&d(`/resume:${e}`)},[d]),Te=H(()=>{V(!1),n(re),x(e=>e+1)},[re]),Se=G(()=>T?!$&&!_:!$&&0===e.length&&!D&&!_,[$,e,D,_,T]),Pe=__name(()=>$||s||N||_||R?0:Se||D?3:4,"getBottomMargin"),Ae=__name(()=>D?"green":e.length>0?"purple":"gray","getInputStateColor")(),xe="gray"===Ae?"dim":Ae;return U.createElement(q,{width:"100%",flexDirection:"column",marginBottom:Pe()},!_&&U.createElement(q,{borderStyle:ue?"round":void 0,borderRight:!1,borderLeft:!1,borderColor:Ae,paddingY:0,width:"100%"},U.createElement(K,{color:xe},D?"!":a.pointer),U.createElement(q,{flexGrow:1,paddingLeft:1},U.createElement(Q,{key:A,value:e,placeholder:o,onChange:ye,onSubmit:()=>{s||N||_||we()},showCursor:r}))),$&&U.createElement(Fr,null),R&&U.createElement(q,{paddingTop:1},U.createElement(K,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),s&&U.createElement(Ir,{onSelectFile:Ee,onClose:be,searchQuery:c}),N&&U.createElement(wr,{onSelectCommand:ve,onClose:ke,searchQuery:O}),_&&U.createElement(Dr,{onSelectSession:Ce,onClose:Te}),Se&&U.createElement(q,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1},U.createElement(q,null,T?U.createElement(q,{flexDirection:"row"},U.createElement(K,{color:"#E4CCFF"},"» accept edits on "),U.createElement(K,{dimColor:!0},"(shift+tab to toggle)")):U.createElement(K,{color:"dim"},"? for shortcuts")),U.createElement(q,{flexDirection:"row",columnGap:1},w&&U.createElement(q,null,U.createElement(K,null,U.createElement(K,null,a.tick," ","Command Code"," ","updated:"," "),U.createElement(K,{dimColor:!0},"v",w.updatedFrom),U.createElement(K,{dimColor:!0}," ",a.arrowRight," "),U.createElement(K,null,"v",w.updatedTo))),!w&&E&&U.createElement(U.Fragment,null,U.createElement(q,null,U.createElement(K,{color:"yellow",dimColor:!0},a.info," Update available:"," ",E.currentVersion," ",a.arrowRight," ",E.latestVersion)),(v||m||g||u)&&U.createElement(q,{marginLeft:1,marginRight:1},U.createElement(K,{dimColor:!0,color:"gray"},"•"))),k&&v&&U.createElement(U.Fragment,null,U.createElement(q,null,U.createElement(K,{color:"green",dimColor:!0},`${a.bullet} Provider: ${getProviderDisplayName(v)}`)),(u||C)&&U.createElement(q,{marginLeft:1,marginRight:1},U.createElement(K,{dimColor:!0,color:"gray"},"•"))),C&&U.createElement(U.Fragment,null,U.createElement(q,null,U.createElement(K,{color:"yellow",dimColor:!0},"--co")),u&&U.createElement(q,{marginLeft:1,marginRight:1},U.createElement(K,{dimColor:!0,color:"gray"},"•"))),U.createElement($r,{usage:u||null}))),D&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:"green"},"! for bash mode")),h&&p&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:"#E4CCFF"},"SHARED: ",p.url," (copied to clipboard)")),f&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:f.includes("NOT SHARED")?"red":"#E4CCFF"},f)),y&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:"#E4CCFF"},y)))},"InputBox"),Mr=__name(()=>{const[e,t]=B("continuous learning"),n=z([]),r=z(0),o=z(null),a=z(!1);W(()=>{const e=__name(e=>"analyzing"===e.type?(a.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):a.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(a.current=!1,void(n.current.length>0?(r.current=0,s()):t("continuous learning"))):void 0,"handleNewEvent"),s=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const a="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,s()},a)},"cycleThroughNextEvent");return cr.on("new-event",e),()=>{cr.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const s=9+e.length+19>100;let i=e;if(s){const t=100;e.length>t&&(i=e.substring(0,t-3)+"...")}else{const t=72;e.length>t&&(i=e.substring(0,t-3)+"...")}return U.createElement(q,null,!s&&U.createElement(K,{color:"green"},"● taste: "),U.createElement(K,null,i),!s&&U.createElement(K,{dimColor:!0}," (ctrl+t to expand)"))},"LearningFeedMini"),Nr=U.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:a,onSubmit:s,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:v,currentProvider:k,showProviderInfo:C,isOAuthMode:T,autoAcceptMode:S,onToggleAutoAccept:P,hintMessage:A})=>{const[x,$]=B(0);return W(()=>{if(!t)return void $(0);const e=setInterval(()=>{$(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),U.createElement(q,{flexDirection:"column"},U.createElement(kr,{messages:e}),U.createElement(q,{flexDirection:"row",justifyContent:"space-between"},U.createElement(q,{flexDirection:"column"},(t||n.isExecuting)&&U.createElement(xr,{tokens:m,timeElapsed:x,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),A&&U.createElement(q,{marginLeft:1},U.createElement(K,{dimColor:!0}," ","⎿"," Tip: ",A)))),U.createElement(Rr,{input:o,setInput:a,onSubmit:s,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:v,currentProvider:k,showProviderInfo:C,isOAuthMode:T,autoAcceptMode:S,onToggleAutoAccept:P,hintMessage:A}),p&&!o&&U.createElement(q,{justifyContent:"flex-end",marginTop:-3},U.createElement(Mr,null)))}),jr=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=X(),[r,o]=B([]),[s,i]=B(0),[c,l]=B(!0),[d,u]=B(0),m=30;W(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await Xn.listSessions();o(e),l(!1)},"loadSessions");if(J((t,o)=>{o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t}):o.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=d+m&&u(t-m+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),c)return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),a=Math.floor(n/864e5),s=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:a<7?`${a} day${a>1?"s":""} ago`:1===s?"1 week ago":`${s} weeks ago`},"formatRelativeTime"),h=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"gray"},"No sessions available"));const f=r.slice(d,d+m),y=d;return U.createElement(q,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"dim"},"Showing ",d+1,"-",Math.min(d+m,r.length)," ","of ",r.length," sessions",d>0&&" (↑ for more)",d+m<r.length&&" (↓ for more)")),U.createElement(q,{columnGap:2,marginBottom:1},U.createElement(q,{width:7},U.createElement(K,{color:"gray"}," ")),U.createElement(q,{width:13},U.createElement(K,{color:"gray"},"Modified")),U.createElement(q,{width:11},U.createElement(K,{color:"gray"},"# Messages")),U.createElement(q,{width:20},U.createElement(K,{color:"gray"},"Git Branch")),U.createElement(q,null,U.createElement(K,{color:"gray"},"Summary"))),U.createElement(q,{columnGap:2},U.createElement(q,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${a.pointer} ${n+1}.`:` ${n+1}.`)})),U.createElement(q,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`mod-${e.id}`,color:s===n?"white":"gray"},p(e.lastModified))})),U.createElement(q,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),U.createElement(q,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),U.createElement(q,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`summary-${e.id}`,color:s===n?"white":"gray"},h(e.firstMessage))}))))},"SessionTable");function RetryMessage({attempt:e}){const[t,n]=B(0);if(W(()=>{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 U.createElement(q,{marginBottom:1},U.createElement(K,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}__name(RetryMessage,"RetryMessage");var Or=__name(({onTrust:e,onExit:t})=>{const{exit:n}=X(),[r,o]=B(1),s=process.cwd().replace(process.env.HOME||"","~");return J((a,s)=>{s.upArrow||s.downArrow?o(1===r?2:1):s.return?1===r?e():(t(),n()):"1"===a?e():("2"===a||s.escape||s.ctrl&&"c"===a)&&(t(),n())}),U.createElement(q,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},U.createElement(K,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),U.createElement(q,{marginTop:1},U.createElement(K,{color:"gray"},s)),U.createElement(q,{marginTop:1,flexDirection:"column"},U.createElement(K,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),U.createElement(q,{marginTop:1},U.createElement(K,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),U.createElement(q,{marginTop:1,flexDirection:"column"},U.createElement(q,null,U.createElement(K,{color:1===r?"cyan":"gray"},1===r?a.pointer:" "," 1. Yes, proceed")),U.createElement(q,null,U.createElement(K,{color:2===r?"cyan":"gray"},2===r?a.pointer:" "," 2. No, exit"))))},"TrustPrompt"),Lr=class extends me{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||y.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 P.readFile(this.configPath,"utf-8"),t=JSON.parse(e);t.permissions&&("acceptEdits"===t.permissions.defaultMode&&(this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0),t.permissions.autoApprove&&(void 0!==t.permissions.autoApprove.create&&(this.config.autoApprove.create=t.permissions.autoApprove.create),void 0!==t.permissions.autoApprove.update&&(this.config.autoApprove.edit=t.permissions.autoApprove.update),void 0!==t.permissions.autoApprove.delete&&(this.config.autoApprove.delete=t.permissions.autoApprove.delete)),t.permissions.allow&&t.permissions.allow.forEach(e=>{if(e.startsWith("Bash(")&&e.endsWith(")")){const t=e.slice(5,-1);this.config.trustedCommands.push(t)}}))}catch(e){}}async requestPermission(e){if(!this.config.enabled)return{allowed:!0};const t=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)?{allowed:!0}:this.config.sessionPermissions.has(t)?{allowed:this.config.sessionPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("permission-request",e,n=>{this.handleUserChoice(e,n).then(t)})})}async handleUserChoice(e,t){const n=e.action,r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionPermissions.set(n,!0);break;case"project":await this.createCommandCodeSettings(),this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getFileKey(e){const t=y.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=y.relative(this.projectRoot,e);return this.config.trustedPaths.some(n=>t.startsWith(n)||e.startsWith(n))}async requestShellPermission(e){if(!this.config.enabled)return{allowed:!0};const t=this.getCommandKey(e);return this.config.autoApprove.shellCommands||this.isTrustedCommand(e.command)?{allowed:!0}:this.config.projectShellPermissions.has(t)?{allowed:this.config.projectShellPermissions.get(t)||!1,scope:"project"}:this.config.sessionShellPermissions.has(t)?{allowed:this.config.sessionShellPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("shell-permission-request",e,n=>{this.handleShellUserChoice(e,n).then(t)})})}async handleShellUserChoice(e,t){const n=this.getCommandKey(e),r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionShellPermissions.set(n,!0);break;case"project":await this.addCommandToSettings(e.command),this.config.projectShellPermissions.set(n,!0)}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getCommandKey(e){return`${e.command.split(" ")[0]}:${e.args?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand(e){return!!["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","grep","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))||this.config.trustedCommands.some(t=>{if(t===e)return!0;if(t.endsWith(":*")){const n=t.slice(0,-2);return e===n||e.startsWith(n+" ")}return e.startsWith(t)})}clearSessionPermissions(){this.config.sessionPermissions.clear(),this.config.sessionShellPermissions.clear()}clearProjectPermissions(){this.config.projectPermissions.clear(),this.config.projectShellPermissions.clear()}setAutoApprove(e,t){this.config.autoApprove[e]=t}addTrustedPath(e){this.config.trustedPaths.includes(e)||this.config.trustedPaths.push(e)}removeTrustedPath(e){const t=this.config.trustedPaths.indexOf(e);t>-1&&this.config.trustedPaths.splice(t,1)}addTrustedCommand(e){this.config.trustedCommands.includes(e)||this.config.trustedCommands.push(e)}removeTrustedCommand(e){const t=this.config.trustedCommands.indexOf(e);t>-1&&this.config.trustedCommands.splice(t,1)}setEnabled(e){this.config.enabled=e}getConfig(){return{...this.config}}async createCommandCodeSettings(){const e=y.join(this.projectRoot,".commandcode"),t=y.join(e,"settings.local.json");try{await P.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await P.readFile(t,"utf-8"),r=JSON.parse(e);r.permissions&&r.permissions.allow&&(n.permissions.allow=[...new Set([...r.permissions.allow,...n.permissions.allow])]),r.permissions&&r.permissions.deny&&(n.permissions.deny=r.permissions.deny)}catch(e){}await P.writeFile(t,JSON.stringify(n,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const t=y.join(this.projectRoot,".commandcode"),n=y.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await P.mkdir(t,{recursive:!0});try{const t=await P.readFile(n,"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(r)||e.permissions.allow.push(r),await P.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},_r=__name((e={})=>{const[t,n]=B(null),[r,o]=B(null),[a,s]=B(!1);return W(()=>{const t=e.projectRoot||process.cwd(),r=new Lr(t);return r.on("permission-request",(t,n)=>{o(t),s(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),s(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:H(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:H(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:H(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),s(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),s(!1)}},[t]),clearSessionPermissions:H(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:H(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:H((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:H(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:a,service:t}},"usePermissions"),Ur=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=B(0),o=[{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}],s=__name(e=>{const r=o.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),i=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),c=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const t=y.basename(e.filePath),n=y.relative(process.cwd(),e.filePath);return n&&!n.startsWith("../")&&n.length<50?n:t||e.filePath}catch{return e.filePath}},"getDisplayPath"),l=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return U.createElement(q,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"yellow"},`${l()} ${"edit"===e.action?c():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&U.createElement(q,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c(),marginLeft:0}).diffContent),U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0},"Do you want to ",i()," ",U.createElement(K,{color:"cyan"},c()),"?")),U.createElement(be,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>U.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?U.createElement(U.Fragment,null,e.split("(shift+tab)")[0],U.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?U.createElement(U.Fragment,null,e.split("(")[0],U.createElement(K,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),Br=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=B(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:"",n=t?`${e.command} ${t}`:e.command;return n.length>60?n.substring(0,57)+"...":n},"getCommandDisplay");return U.createElement(q,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"yellow"},"Execute Shell Command")),U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0},"Command Code needs to execute ",U.createElement(K,{color:"cyan"},i()),".")),e.workingDirectory&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"gray",italic:!0},e.description)),U.createElement(be,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>U.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?U.createElement(U.Fragment,null,e.split("(shift+tab)")[0],U.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt"),Wr=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole"),zr=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=B(!1),[a,s]=B(!0);W(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{s(!1)}},"loadSettings")()},[]),J((t,n)=>{if(!n.return&&" "!==t)return n.escape?(Wr(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return a?U.createElement(q,{key:n,borderStyle:"round",borderColor:"blue",padding:1,flexDirection:"column"},U.createElement(K,{color:"blue",bold:!0},"Taste Settings"),U.createElement(K,{dimColor:!0},"Loading configuration...")):U.createElement(q,{key:n,borderStyle:"round",borderColor:"gray",padding:1,flexDirection:"column"},U.createElement(K,{bold:!0},"Taste Learning"),U.createElement(K,{dimColor:!0},"Configure taste learning preferences for this project"),U.createElement(q,{marginTop:1}),U.createElement(q,{justifyContent:"space-between"},U.createElement(K,null,"Taste learning",U.createElement(K,{dimColor:!0}," - Learn from your interactions")),U.createElement(K,{color:r?"green":"gray"},r?"enabled":"disabled")),U.createElement(q,{marginTop:1}),U.createElement(K,{dimColor:!0},"Taste data stored in .commandcode/taste/"),U.createElement(K,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig"),Gr=__name(({onClose:e,staticKey:t})=>{const[n,r]=B([]),[o,a]=B(!0),[s,i]=B(null),{stdout:c}=Y(),l=c?.columns??80,d=__name((e,t)=>e.length<=t?e:t<=3?e.substring(0,t):e.substring(0,t-3)+"...","truncateText");W(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),n=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];r(n)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{a(!1)}},"loadSkills")()},[]);const u=__name(async t=>{const r=n.find(e=>e.value===t.value);if(r)try{await ne([{file:r.filePath,line:1}]),Wr(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(m()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelect");J((t,n)=>{n.escape&&(Wr(),e())});const m=__name(()=>{const e=process.platform;return"win32"===e?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===e?"~/.zshrc":"~/.bashrc")},"getEditorSetupMessage");return o?U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),U.createElement(K,{dimColor:!0},"Loading skills...")):s?U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(K,{color:"red",bold:!0},"Agent Skills"),U.createElement(K,{dimColor:!0},s),U.createElement(q,{marginTop:1}),U.createElement(K,{dimColor:!0},"Press ",U.createElement(K,{bold:!0},"Esc")," to close")):0===n.length?U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"No skills found")),U.createElement(K,{dimColor:!0},"Create skills in:"),U.createElement(K,{dimColor:!0}," ~/.commandcode/skills/ (user)"),U.createElement(K,{dimColor:!0}," .commandcode/skills/ (project)"),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press ",U.createElement(K,{bold:!0},"Esc")," to close"))):U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(q,null,U.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Select a skill to open in your editor. Skills provide specialized guidance for coding tasks.")),U.createElement(be,{items:n,onSelect:u,initialIndex:0,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const r=n.find(e=>e.label===t),o=r?.location?` (${r.location})`:"",a=Math.max(30,l-35),s=r?.description?d(r.description,a):"";return U.createElement(q,null,U.createElement(K,{color:e?"green":"white"},` ${t}`),U.createElement(K,{color:"gray"},o.padEnd(25-t.length)),U.createElement(K,{color:"gray"},s))}}),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press ",U.createElement(K,{bold:!0},"Esc")," to cancel")))},"SkillsConfig"),Hr=__name(({onClose:e})=>{const[t,n]=B(cr.getEvents());J((t,n)=>{n.ctrl&&"t"===t&&(Wr(),e())},{isActive:!0}),W(()=>{const e=__name(()=>{n(cr.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return cr.on("new-event",e),cr.on("cleared",t),()=>{cr.off("new-event",e),cr.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,a=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);a=`confidence: ${parseFloat(e).toString()}%`}const s={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:s,content:o,confidence:a}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),s=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),i=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails");return U.createElement(q,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(pe,{name:"vice"},U.createElement(K,null,Er()))),U.createElement(q,{marginBottom:1,width:"100%",justifyContent:"space-between"},U.createElement(q,null,U.createElement(K,{bold:!0},"Learning Feed"),U.createElement(K,{dimColor:!0}," - Real-time taste learning activity")),U.createElement(K,{dimColor:!0},"Press ctrl+t to close")),U.createElement(q,{flexDirection:"column"},0===t.length?U.createElement(q,null,U.createElement(K,{dimColor:!0},"No learning events yet...")):U.createElement(q,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:a}=o(e.message),c="moved"===t?i(e.details):null,l="upgraded"===t||"downgraded"===t?s(r):null;return U.createElement(q,{key:e.id,marginBottom:1},U.createElement(q,{flexDirection:"column"},U.createElement(q,null,U.createElement(K,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?U.createElement(K,{dimColor:!0}," (",c.fullPath,")"):e.details?U.createElement(K,{dimColor:!0}," (",e.details,")"):null),U.createElement(q,{marginLeft:1},U.createElement(K,{dimColor:!0},"⎿"," "),c?U.createElement(U.Fragment,null,U.createElement(K,null,c.category," package ("),U.createElement(K,{dimColor:!0},c.oldPath),U.createElement(K,null," → ",c.newPath),U.createElement(K,null,")")):l?U.createElement(U.Fragment,null,U.createElement(K,null,l.text," ("),U.createElement(K,{dimColor:!0},"confidence: "),U.createElement(K,{dimColor:!0},l.oldPercent,"%"),U.createElement(K,null," → "),U.createElement(K,{color:l.diff>0?"green":"red"},l.newPercent,"%"),U.createElement(K,null,")")):U.createElement(U.Fragment,null,U.createElement(K,null,r),a&&U.createElement(K,{dimColor:!0}," (",a,")")))))}return U.createElement(q,{key:e.id,marginBottom:1},U.createElement(K,{dimColor:!0},a.pointerSmall," ",e.message))}))))},"LearningFeedFull");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,a="";for(let e=0;e<t.length;e++){const s=t[e];'"'!==s&&"'"!==s||o?s===a&&o?(o=!1,a=""):" "!==s||o?r+=s:(r.trim()&&n.push(r.trim()),r=""):(o=!0,a=s)}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),a=n.substring(r+1).trim();return{commandName:o,rawArguments:a,positionalArgs:parsePositionalArguments({input:a})}}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}}__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate");var Vr=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");J((e,n)=>{n.escape&&t()});const a=n?r.findIndex(e=>e.value===n):0,s=n&&-1===a;return U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(q,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},U.createElement(q,null,U.createElement(K,{bold:!0},"Select AI Provider")),n&&U.createElement(q,{flexDirection:"row"},U.createElement(K,{dimColor:!0},"Current: "),U.createElement(K,{color:"green"},getProviderDisplayName(n)),s&&U.createElement(K,{color:"yellow"}," [OAuth enforced]"))),U.createElement(q,{marginBottom:0},U.createElement(K,{dimColor:!0},"Available Providers:")),U.createElement(be,{items:r,onSelect:o,initialIndex:a>=0?a:0,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"cyan":"gray",bold:e},` ${t}`)}),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");function getModelOptions(){return Object.values(je).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}__name(getModelOptions,"getModelOptions");var qr=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");J((e,n)=>{n.escape&&t()});const a=n?r.findIndex(e=>e.value===n):0;return U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(q,null,U.createElement(K,{color:"#E4CCFF",bold:!0},"Select model")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),U.createElement(be,{items:r,onSelect:o,initialIndex:a>=0?a:0,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),a=o?.value===n,s=o?.description?`${o.label} (${o.description})`:o?.label||t;return U.createElement(q,null,U.createElement(K,{color:e?"green":"gray"},` ${s.padEnd(24)}`),U.createElement(K,{color:e?"green":"gray"},o?.modelName),a&&U.createElement(K,{color:"green"}," ✓"))}}),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to cancel")))},"ModelSelector"),Kr=__name(({onClose:e})=>{const[t,n]=B([]),[r,o]=B(0),[a,s]=B(!0),[i,c]=B(null);W(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),s(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),s(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(J((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),a)return U.createElement(q,{paddingLeft:1,paddingTop:1},U.createElement(K,{color:"dim"},"Loading memory files..."));if(i)return U.createElement(q,{paddingLeft:1,paddingTop:1},U.createElement(K,{color:"red"},"❌ ",i));const u=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return U.createElement(q,{flexDirection:"column",width:"100%",borderStyle:"round",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},U.createElement(q,null,U.createElement(K,{color:"white",bold:!0},"Select memory to edit:")),U.createElement(q,{columnGap:4,marginTop:1},U.createElement(q,{flexDirection:"column"},u.map((e,t)=>U.createElement(K,{key:t,color:r===t?"white":"dim"},r===t?"> ":" ",e.label))),U.createElement(q,{flexDirection:"column"},u.map((e,t)=>U.createElement(K,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector"),Jr=class{static{__name(this,"TasteManager")}static async initializeProject(){const e=process.cwd(),t=f.join(e,".commandcode","taste");await S.mkdir(t,{recursive:!0});const n=f.join(t,"taste.md");try{await S.access(n);const e=await S.readFile(n,"utf-8"),t=migrateHeader({content:e});t!==e&&await S.writeFile(n,t,"utf-8")}catch{await S.writeFile(n,yt+"\n\n")}}static async isInitialized(){const e=process.cwd(),t=f.join(e,".commandcode","taste");try{return await S.access(t),!0}catch{return!1}}},Yr=__name(({staticKey:e})=>U.createElement(V,{items:[{staticKey:e}],key:e},()=>U.createElement(K,{key:e},"\0")),"Responsive"),Zr=__name(()=>y.join(T.homedir(),".commandcode","agents"),"getRootAgentDir"),Xr=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Qr=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=B("idle"),[a,s]=B(""),i=[...nr.map(e=>e.name),...rr.map(e=>e.name)],c=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void s("Agent configuration is incomplete");o("saving");try{const n="personal"===e.location?Zr():Xr();await P.mkdir(n,{recursive:!0});const r=`${e.agentType}.md`,o=y.join(n,r),a=Array.from(e.selectedTools).map(e=>ar[e]||e).join(", "),s=0===e.selectedTools.size?"none":e.selectedTools.size===i.length?'"*"':JSON.stringify(a),c=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${s}\n---\n\n${e.sysPrompt}\n`;await P.writeFile(o,c,"utf-8"),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),s(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");J((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||c()});const l=Array.from(e.selectedTools).map(e=>ar[e]||e).join(", "),d="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return U.createElement(q,{flexDirection:"column",gap:1},U.createElement(q,{flexDirection:"column"},U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Name:"),U.createElement(K,{color:"gray"},e.agentType)),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Location:"),U.createElement(K,{color:"gray"},d)),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Tools:"),U.createElement(K,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===i.length?"*":l))),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Description"),U.createElement(K,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),U.createElement(K,{color:"gray"},e.ccToolDefinition),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"System Prompt:")),U.createElement(K,{color:"gray"},e.sysPrompt),!n&&U.createElement(q,{marginTop:1},"idle"===r&&U.createElement(q,{gap:1},U.createElement(K,{color:"green",dimColor:!0},"Press"),U.createElement(K,{color:"green",bold:!0},"Enter"),U.createElement(K,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===r&&U.createElement(K,{color:"yellow"},"Saving agent..."),"saved"===r&&U.createElement(K,{color:"green"},"✓ ",a),"error"===r&&U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"red"},"✗ Error: ",a),U.createElement(K,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),eo=__name(({agent:e,onBack:t,setRevalidateAgent:n})=>{const[r,o]=B("menu"),a=[...nr.map(e=>e.name),...rr.map(e=>e.name)];let s=new Set;if("*"===e.tools||'"*"'===e.tools)s=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>sr[e]||e);s=new Set(t)}const i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:s},c=__name(e=>{"back"===e.value?t():"view"===e.value?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(J((e,n)=>{n.escape&&("menu"===r?t():o("menu")),n.return&&"view"===r&&o("menu")}),"view"===r)return U.createElement(q,{flexDirection:"column"},U.createElement(Qr,{config:i,onSaveComplete:()=>o("menu"),viewOnly:!0}),U.createElement(q,{marginTop:1},U.createElement(K,{color:"gray"},"Press Enter to go back")));if("edit"===r)return U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"yellow"},"Edit functionality coming soon..."),U.createElement(K,{color:"gray"},"Press Esc to go back"));if("delete"===r){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],a=__name(async r=>{if("confirm-delete"===r.value)try{await P.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return U.createElement(q,{flexDirection:"column",gap:1},U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"red"},"Delete agent"),U.createElement(K,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),U.createElement(q,null,U.createElement(be,{items:r,onSelect:a,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)})))}return U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white",bold:!0},e.name),U.createElement(q,{marginTop:1},U.createElement(be,{items:[{label:"1. View agent",value:"view"},{label:"2. Delete agent",value:"delete"},{label:"3. Back",value:"back"}],onSelect:c,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)})),U.createElement(q,{marginTop:1},U.createElement(K,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),to=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=B([]),[o,a]=B([]),[s,i]=B(!0),[c,l]=B(!1),[d,u]=B(null),[m,g]=B(!1),p=__name(()=>y.join(T.homedir(),".commandcode","agents"),"getRootAgentDir"),h=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),f=__name(async(e,t)=>{try{l(!1);const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=se(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,sysPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");W(()=>{__name(async()=>{i(!0);const[e,t]=await Promise.all([f(p(),"personal"),f(h(),"project")]);r(e),a(t),i(!1)},"loadAgents")()},[c]);const w=[{label:"Create new agent",value:"create_new_agent"}];n.forEach(e=>{w.push({label:e.name,value:e.filePath})}),o.forEach(e=>{w.push({label:e.name,value:e.filePath})});const E=n.length>0||o.length>0,b=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...n,...o].find(e=>e.filePath===t.value);e&&(u(e),g(!0))}},"handleAgentSelect");if(s)return U.createElement(K,{color:"gray"},"Loading agents...");if(m&&d)return U.createElement(eo,{agent:d,onBack:()=>{g(!1),u(null)},setRevalidateAgent:l});const v=__name(({isSelected:e,label:t})=>{const r=w.find(e=>e.label===t),a=r?.value||"",s=n[0]?.filePath===a,i=o[0]?.filePath===a;return U.createElement(q,{flexDirection:"column"},s&&n.length>0&&U.createElement(q,{marginTop:1,marginLeft:2},U.createElement(K,{color:"white"},"User agents (~/",".commandcode","/","agents",")")),i&&o.length>0&&U.createElement(q,{marginTop:1,marginLeft:2},U.createElement(K,{color:"white"},"Project agents")),U.createElement(q,null,U.createElement(K,{color:"white"},e?">":" "),U.createElement(K,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return U.createElement(q,{flexDirection:"column"},U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{color:"white",bold:!0},"Agents"),E?U.createElement(K,{color:"gray"},n.length+o.length," agents"):U.createElement(K,{color:"gray"},"No agents found")),t&&U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{color:"green",dimColor:!0},"Created agent: ",t)),U.createElement(be,{items:w,onSelect:b,indicatorComponent:()=>null,itemComponent:v}),!E&&U.createElement(q,{flexDirection:"column",marginTop:1},U.createElement(K,{color:"gray"},"No agents found. Create specialized subagents that Command Code can delegate to."),U.createElement(K,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools."),U.createElement(K,{color:"gray"},"Try creating: Code Reviewer, Code Simplifier, Security Reviewer, Tech Lead, or UX Reviewer.")))},"ManageAgents"),no=__name(({onSelect:e})=>U.createElement(be,{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})=>U.createElement(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector"),ro=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:a,onCCToolDefinitionChange:s,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=B(!1),[m,g]=B(!1),p=H(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[d,a]),h=H(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[m,s]);return"agentType"===e?U.createElement(U.Fragment,null,U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(ar).some(e=>ue(e)===ue(t))||Object.keys(ar).some(e=>ue(e)===ue(t)))&&U.createElement(K,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name.")),U.createElement(Q,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=ue(t);Object.values(ar).some(t=>ue(t)===e)||Object.keys(ar).some(t=>ue(t)===e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?U.createElement(U.Fragment,null,U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white"},"Enter the system prompt for your agent:"),U.createElement(K,{color:"gray"},"Be comprehensive for best results.")),U.createElement(Q,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?U.createElement(U.Fragment,null,U.createElement(K,{color:"white"},"When should ","Command Code"," use this agent?"),U.createElement(Q,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow"),oo=__name(({onSelect:e})=>U.createElement(be,{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})=>U.createElement(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector"),ao=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=B(!1),[c,l]=B(0),d=H(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 U.createElement(q,{flexDirection:"column"},r?U.createElement(q,null,U.createElement(CMDIcon,null),U.createElement(K,{color:"white"},"Generating agent from description...")):U.createElement(Q,{key:c,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:d,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&U.createElement(q,{marginTop:1},U.createElement(K,{color:"red"},`${a.warning} ${o}`)))},"RecommendedFlow"),so=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,a]=B(!1),[s,i]=B(0),c=G(()=>[...nr.map(e=>e.name),...rr.map(e=>e.name)],[]),l=G(()=>[{name:"All tools",tools:c},{name:"Read-only tools",tools:c.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:c.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:c.filter(e=>"shell_command"===e)},{name:"Search tools",tools:c.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:c.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[c]),d=G(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),c.forEach(t=>{e.push({type:"tool",value:t})})):(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,l,e,c]),u=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=l.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${ar[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),m=u.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return J((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[s];if(e){const s=d[e.value];if(!s)return;"continue"===s.type?r():"toggle"===s.type?(a(!o),i(0)):"category"===s.type?n(s.value):"tool"===s.type&&t(s.value)}}}),U.createElement(q,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===s;if("divider"===e.type)return U.createElement(q,{key:`divider-${t}`},U.createElement(K,{color:"gray"}," ",e.label));if("spacer"===e.type)return U.createElement(q,{key:`spacer-${t}`,height:1});if("label"===e.type)return U.createElement(q,{key:`label-${t}`},U.createElement(K,{color:"gray"}," ",e.label));const o="continue"===e.type;return U.createElement(q,{key:`item-${t}`},U.createElement(K,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),U.createElement(q,{marginTop:1},e.size===c.length&&U.createElement(K,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&U.createElement(K,{color:"gray"},e.size," tools selected"),0===e.size&&U.createElement(K,{color:"gray"},"No tools selected")))},"ToolsSelector"),io=__name(({onComplete:e})=>{const[t,n]=B("location"),[r,o]=B(!1),[a,s]=B(null),[i,c]=B("agentType"),l=G(()=>[...nr.map(e=>e.name),...rr.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=B(d()),g=__name(t=>{n("location"),c("agentType"),m(d()),e(t)},"resetToDefaults"),p=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===u.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===i)return"Agent type (identifier)";if("sysPrompt"===i)return"System prompt";if("ccToolDefinition"===i)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),h=__name(e=>{m({...u,location:e}),n("method")},"handleLocationSelect"),f=__name(e=>{m({...u,method:e}),n("configuration")},"handleMethodSelect"),y=__name(async()=>{try{s(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===Ne&&(r=await Ue.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const a={[xe]:t.toString()};r&&(a[$e]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new ht({baseUrl:i}),l=await c.post({headers:a,endpoint:Fe.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:ue(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof it&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?s(Be):s("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),w=__name(()=>{m({...u,agentType:ue(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),b=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),v=__name(()=>{n("summary")},"handleToolsComplete"),k=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),C=__name(e=>{const t=[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(u.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),m({...u,selectedTools:n})},"handleToggleCategory");return U.createElement(q,{flexDirection:"column",gap:1},U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white",bold:!0},"Create new agent"),U.createElement(K,{color:"gray"},p())),U.createElement(q,null,"location"===t&&U.createElement(no,{onSelect:h}),"method"===t&&U.createElement(oo,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&U.createElement(ao,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:a,onSubmit:y}),"configuration"===t&&"manual"===u.method&&U.createElement(q,{flexDirection:"column",gap:1},U.createElement(ro,{step:i,agentType:u.agentType,sysPrompt:u.sysPrompt,ccToolDefinition:u.ccToolDefinition,onAgentTypeChange:e=>m({...u,agentType:e}),onSysPromptChange:e=>m({...u,sysPrompt:e}),onCCToolDefinitionChange:e=>m({...u,ccToolDefinition:e}),onAgentTypeSubmit:w,onSysPromptSubmit:E,onCCToolDefinitionSubmit:b})),"tools"===t&&U.createElement(so,{selectedTools:u.selectedTools,onToggleTool:k,onToggleCategory:C,onComplete:v}),"summary"===t&&U.createElement(Qr,{config:u,onSaveComplete:g})))},"AgentNew"),co=__name(({onCancel:e})=>{const[t,n]=B(null),[r,o]=B(null),a=__name(e=>{n(e.value),o(null)},"handleSelect");return J((t,n)=>{n.escape&&e()}),U.createElement(q,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"round",flexDirection:"column"},null===t&&U.createElement(to,{handleSelect:a,createdAgentName:r}),"create_new_agent"===t&&U.createElement(io,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r=["create","edit","delete","execute","shellCommands"];for(const e of r)n.setAutoApprove(e,t)}__name(applyAutoAcceptMode,"applyAutoAcceptMode");var lo=[{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"}],uo=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const[r,o]=B(0),[a,s]=B(0),[i,c]=B("checkpoint"),[l,d]=B(null),[u,m]=B(0),g=G(()=>[...e].sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime()),[e]),p=G(()=>{if(!l)return!0;const e=g.findIndex(e=>e.messageId===l.messageId);if(-1===e)return!0;for(let t=0;t<=e;t++)if(g[t].filesModified.length>0)return!0;return!1},[l,g]),h=G(()=>p?lo:lo.filter(e=>"conversation"===e.mode),[p]);if(J((e,p)=>{p.escape?"mode"===i?(c("checkpoint"),d(null),m(0)):n():"checkpoint"===i?p.upArrow?o(e=>{const t=Math.max(0,e-1);return t<a&&s(t),t}):p.downArrow?o(e=>{const t=Math.min(g.length-1,e+1);return t>=a+8&&s(t-8+1),t}):p.return&&g.length>0&&(d(g[r]),c("mode"),m(0)):"mode"===i&&(p.upArrow?m(e=>Math.max(0,e-1)):p.downArrow?m(e=>Math.min(h.length-1,e+1)):p.return&&l&&h[u]&&t({messageId:l.messageId,mode:h[u].mode}))}),0===g.length)return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),U.createElement(K,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to close")));if("mode"===i&&l)return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Restore to: "),U.createElement(K,{color:"white"},truncateString({text:l.userPrompt||"checkpoint",maxLength:50}))),U.createElement(q,{flexDirection:"column"},h.map((e,t)=>{const n=u===t,r=t===h.length-1;return U.createElement(q,{key:e.mode,flexDirection:"column"},U.createElement(q,{flexDirection:"row"},U.createElement(K,{color:n?"#E4CCFF":void 0},n?"> ":" "),U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:n?"#E4CCFF":"white"},e.label),U.createElement(K,{dimColor:!0},e.description))),!r&&U.createElement(K,null," "))})),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Enter"),U.createElement(K,{dimColor:!0}," to confirm, "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to go back")));const f=g.slice(a,a+8);return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),U.createElement(K,{dimColor:!0},"Select a checkpoint to restore your session"),g.length>8&&U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,g.length)," ","of ",g.length)),U.createElement(q,{marginTop:1}),U.createElement(q,{flexDirection:"column"},f.map((e,t)=>{const n=r===a+t,o=e.filesModified.length,s=t===f.length-1;return U.createElement(q,{key:e.messageId,flexDirection:"column"},U.createElement(q,{flexDirection:"row"},U.createElement(K,{color:n?"#E4CCFF":void 0},n?"> ":" "),U.createElement(q,{flexDirection:"column"},U.createElement(q,null,U.createElement(K,{color:n?"#E4CCFF":"white"},truncateString({text:e.userPrompt||"(no prompt)",maxLength:60})),U.createElement(K,{dimColor:!0}," • "),U.createElement(K,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}))),U.createElement(K,{dimColor:!0},o>0?`${o} file${o>1?"s":""} changed`:"No code changes"))),!s&&U.createElement(K,null," "))})),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Enter"),U.createElement(K,{dimColor:!0}," to select, "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to cancel")))},"RewindSelector"),{setText:mo}=ge,go=__name(({resume:e=!1,continue:t=!1,trust:n=!1,updateStatus:r,updateFailedInfo:o,initialMessage:a})=>{const{exit:s}=X(),[i,c]=B(""),[l,d]=B("Ready..."),[u,m]=B(null),[g,p]=B(r);W(()=>{if(g){const e=setTimeout(()=>{p(null)},3e4);return()=>clearTimeout(e)}},[g]);const{stdout:h}=Y(),[f,y]=B(!1),[w,E]=B(!1),[b,v]=B(!1),[k,C]=B(!1),[T,S]=B(!1),[P,A]=B(!1),[x,$]=B(!1),[I,D]=B(!1),[F,R]=B(null),[M,N]=B(null),[j,O]=B(getConfiguredModel()),[L,_]=B(!1),[G,H]=B(!1),[V,Z]=B(!1),Q=z(null),ee=z(null),[te,ne]=B(0),[re,oe]=B(!1),{executeBash:ae,executionState:se}=fn(),[ie,ce]=B(""),[le,de]=B([]),[ue,me]=B(!1),[ge,pe]=B([]),[he,fe]=B(crypto.randomUUID()),[ye,we]=B(!1),[Ee,be]=B(!1),[ve,ke]=B(!1),[Ce,Te]=B(!1),[Se,Pe]=B(!0),[Ae,xe]=B(!1),[$e,Ie]=B(0),[De,Re]=B(null),[Me,Ne]=B(null),[Oe,Le]=B(null),_e=z(!1),Be=z(!1),We=z(Oe);W(()=>{We.current=Oe},[Oe]);const[ze,Ge]=B(!1),[He,Ve]=B(""),[qe,Ke]=B(!1),[Je,Ye]=B(!1),[Ze,Xe]=B(""),Qe=z(null),[et,tt]=B(!1),[nt,rt]=B(0),ot=__name(async()=>{try{const e=await isTasteLearningEnabled();Ke(e),e&&await Jr.initializeProject()}catch(e){}},"loadTasteStatus"),at=__name(async()=>{const e=await getConfiguredProvider();N(e);const t=await isOAuthEnforced();_(t)},"loadCurrentProvider"),st=z([]),it=z(null),[ct,lt]=B(null),{requestShellPermission:dt,service:ut,respondToPrompt:mt,clearSessionPermissions:gt,setEnabled:pt}=_r({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{lt({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),it.current&&d("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{lt({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),it.current&&d("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?d("Permission granted"):d("Permission denied")},"onPermissionResponse")}),ft=__name(e=>{Qe.current&&clearTimeout(Qe.current),Xe(e),Qe.current=setTimeout(()=>{Xe(""),Qe.current=null},5e3)},"showHintMessage");W(()=>()=>{Qe.current&&clearTimeout(Qe.current)},[]),W(()=>{ut&&applyAutoAcceptMode({enabled:Je,service:ut})},[Je,ut]),W(()=>{(async()=>{if(await Xn.isProjectInitialized())if(Te(!0),Pe(!1),ot(),at(),t){const e=await Xn.listSessions();if(e.length>0){const t=e[0];It(t.id)}}else e&&we(!0);else if(n)if(await Xn.initializeProject(),Te(!0),Pe(!1),ot(),at(),t){const e=await Xn.listSessions();if(e.length>0){const t=e[0];It(t.id)}}else e&&we(!0);else ke(!0),Pe(!1)})()},[e,t,n,s]),W(()=>{st.current=ge},[ge]),W(()=>{(async()=>{if(M&&"anthropic"===M&&L)try{await Ue.getValidAccessToken()||d("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){d("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[M,L]),W(()=>{if(!ue)return;const e=setInterval(()=>{d(mn())},7e3);return()=>clearInterval(e)},[ue]),W(()=>()=>{Q.current&&clearTimeout(Q.current),ee.current&&clearTimeout(ee.current)},[]);const yt=__name(()=>{Ye(e=>{const t=!e;return t&&ct&&(mt({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),ct.resolve(!0),lt(null)),t})},"handleToggleAutoAccept");async function getBillingLink(){if(Me)return Me;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return Ne(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return Ne(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}J((e,t)=>{if(t.shift&&t.tab||""===e)yt();else if(!(b||k||T||P||x||F||I||et)){if(t.ctrl&&"c"===e&&s(),t.ctrl&&"t"===e)return Wr(),D(e=>!e),void ne(e=>e+1);if(getIsExpandToolShortcut(t,e))return Wr(),oe(e=>!e),void ne(e=>e+1);if(t.escape){const e=Date.now(),t=e-nt;if(rt(e),t<500&&!ue&&!ct&&it.current?.hasCheckpoints())return void tt(!0);if(ct)mt({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ct.resolve(!1),lt(null),d("Permission denied");else if(ue&&it.current){it.current.interrupt(!0),me(!1),d("Interrupted by user");const e=an("Interrupted by user");de(t=>[...t,e])}}t.meta||t.ctrl}}),W(()=>{const e=__name(()=>{Wr(),ne(e=>e+1)},"handleResize");if(h)return h.on("resize",e),()=>{h.off("resize",e)}},[h]),W(()=>{it.current||!Ce||ye||Ee||(it.current=new gr({onFeedUpdate:__name(e=>{de(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...st.current];return st.current=[],pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ie(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Re(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{m(e)},"onRetryUpdate"),onProviderChange:__name(e=>{N(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&ut){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return ut.requestShellPermission(n).then(e=>e.allowed)}if(ut){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return ut.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=We.current;return e?{sessionId:he,secret:e.secret}:null},"getShareInfo")},he),(async()=>{await Pt()})())},[he,ye,Ee,Ce]),W(()=>{a&&Ce&&!Se&&it.current&&!ye&&!Be.current&&(Be.current=!0,wt({role:"user",input:a}))},[a,Ce,Se,ye]),__name(getBillingLink,"getBillingLink");const wt=__name(async({role:e,input:t,images:n})=>{if(t.length)if(g&&p(null),Ie(0),"bash"===e){if(_e.current)return;_e.current=!0;const e=rn(t);de([...le,e]),c(""),await ae(t,e=>{de(e)},()=>{Wr(),ne(e=>e+1)}),_e.current=!1}else{if(ue)return pe(e=>[...e,t]),void c("");if(_e.current)return;_e.current=!0,me(!0),d(mn()),c("");try{it.current&&await it.current.sendMessage(t,n)}catch(e){if("Interrupted by user"===e?.message||e?.message?.toLowerCase().includes("interrupt")||e?.message?.toLowerCase().includes("abort")||"InterruptedError"===e?.name||"AbortError"===e?.name||"ECONNABORTED"===e?.code);else if("Insufficient credits"===e.message){d("Insufficient credits");const e=await getBillingLink(),t=an(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);de(e=>[...e,t])}else if(e.message.startsWith("Error:")){d("Error");const t=an(e.message);de(e=>[...e,t])}else{d("Error");const t=e.message||"An unexpected error occurred",n=an(t);de(e=>[...e,n])}}finally{me(!1),"Interrupted by user"!==l&&"Permission denied"!==l&&"Insufficient credits"!==l&&d("Ready..."),_e.current=!1}}},"handleSubmit"),Et=__name(()=>{de(e=>[...e,on("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),bt=__name(async()=>{if(de([]),Wr(),Ye(!1),Le(null),Ge(!1),Ve(""),it.current){const e=it.current.getSessionManager();e&&await e.deleteShareInfo(),it.current=null;const t=crypto.randomUUID();fe(t),gt(),it.current=new gr({onFeedUpdate:__name(e=>{de(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...st.current];return st.current=[],pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ie(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Re(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{m(e)},"onRetryUpdate"),onProviderChange:__name(e=>{N(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&ut){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return ut.requestShellPermission(n).then(e=>e.allowed)}if(ut){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return ut.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=We.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}ne(e=>e+1),Re(null),Ie(0)},"handleClearCommand"),vt=__name(()=>{it.current?it.current.hasCheckpoints()?tt(!0):de(e=>[...e,en("No checkpoints available. Start sending messages to create checkpoints.")]):de(e=>[...e,en("No active conversation to rewind.")])},"handleRewindCommand"),kt=__name(async e=>{const{messageId:t,mode:n}=e;if(tt(!1),it.current)try{d("Restoring checkpoint...");const e=await it.current.restoreToCheckpoint({messageId:t,mode:n});if(e.success){const t=it.current.getSessionManager(),n=it.current.getMessages(),r=t.reconstructFeedFromMessages(n);de(r),Wr(),ne(e=>e+1);const o=[];e.filesRestored>0&&o.push(`${e.filesRestored} file${e.filesRestored>1?"s":""} restored`),e.filesDeleted>0&&o.push(`${e.filesDeleted} file${e.filesDeleted>1?"s":""} deleted`),e.messagesRemoved>0&&o.push(`${e.messagesRemoved} message${e.messagesRemoved>1?"s":""} removed`);const a=o.length>0?`Restored to checkpoint: ${o.join(", ")}.`:"Restored to checkpoint.";de(e=>[...e,en(a)]),d("Ready...")}else de(t=>[...t,an(`Failed to restore: ${e.error}`)]),d("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;de(e=>[...e,an(t)]),d("Ready...")}},"handleRewindSelect"),Ct=__name(()=>{tt(!1)},"handleRewindCancel"),Tt=__name(async()=>{if(it.current)if(it.current.isRequestInProgress())de(e=>[...e,en("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{d("Compacting conversation...");const e=await it.current.compactConversation();Wr(),ne(e=>e+1);const t=e.messagesRemoved>0?`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`:"Conversation is already compact.";de(e=>[...e,en(t)]),d("Ready..."),Re({current:it.current.getContextTokensUsed()||0,limit:Zn})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;de(e=>[...e,an(t)]),d("Ready...")}else de(e=>[...e,en("No active conversation to compact.")])},"handleCompactCommand"),St=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await It(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void s();case"/clear":return void await bt();case"/help":return void Et();case"/share":return void At();case"/unshare":return void $t();case"/taste":return void v(!0);case"/skills":return void C(!0);case"/provider":return void(isInternalFlagPresent()?S(!0):d("Provider selection not available"));case"/model":return void A(!0);case"/memory":return void $(!0);case"/init":return void xt();case"/agents":return void E(!0);case"/compact":return void await Tt();case"/rewind":return void vt()}const a=getCustomCommandContent(n);if(a){const e=processCommandTemplate({template:a,rawArguments:r,positionalArgs:o});await wt({input:e.content,role:"user"})}},"handleCommand"),Pt=__name(async()=>{const e=it.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&Le({url:t.url,secret:t.secret})}},"loadShareInfo"),At=__name(async()=>{if(he){if(Oe)return await mo(Oe.url),d(""),Ge(!0),void setTimeout(()=>{Ge(!1)},3e3);try{d("Creating share link...");const e=it.current?.getMessages()||[],t=ir.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new ht({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:Fe.ALPHA.SHARE.CREATE,body:{sessionId:he,messages:t}}),o={url:r.url,secret:r.secret};Le(o);const a=it.current?.getSessionManager();a&&await a.saveShareInfo({url:r.url,secret:r.secret}),await mo(r.url),d(""),Ge(!0),setTimeout(()=>{Ge(!1)},5e3)}catch(e){d(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else d("No active session to share")},"handleShareCommand"),xt=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;de(e=>[...e,en(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;de(e=>[...e,en(t)])}},"handleInitCommand"),$t=__name(async()=>{if(he){if(!Oe)return Ve("NOT SHARED: Session is not currently shared"),void setTimeout(()=>Ve(""),5e3);try{d("Removing share link...");const e=new ht({baseUrl:getApiBaseUrl()});await e.delete({endpoint:Fe.ALPHA.SHARE.DELETE,body:{sessionId:he,secret:Oe.secret}});const t=it.current?.getSessionManager();t&&await t.deleteShareInfo(),Ve("UNSHARED: Sharing has stopped"),d(""),Le(null),setTimeout(()=>{Ve("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;d(t),setTimeout(()=>d(""),5e3)}}else d("No active session to unshare")},"handleUnshareCommand"),It=__name(async e=>{try{de([]),it.current=null,Ye(!1),fe(e),we(!1),be(!0),await new Promise(e=>setTimeout(e,100)),it.current=new gr({onFeedUpdate:__name(e=>{de(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...st.current];return st.current=[],pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ie(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Re(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{m(e)},"onRetryUpdate"),onProviderChange:__name(e=>{N(e)},"onProviderChange"),getShareInfo:__name(()=>{const t=We.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await it.current.loadSession(e);await Pt(),de(t),Wr(),ne(e=>e+1)}catch(e){console.error("Failed to load session:",e),we(!0),fe(crypto.randomUUID())}},"handleSelectSession"),Dt=__name(async()=>{de([]),it.current=null,Ye(!1),fe(crypto.randomUUID()),we(!1),be(!1)},"handleNewSession"),Ft=__name(async()=>{try{await Xn.initializeProject(),ke(!1),e?(console.log("No conversations found to resume."),xe(!0),s()):(Te(!0),ot(),at())}catch(e){console.error("Failed to initialize project:",e),ke(!1),xe(!0),s()}},"handleTrust"),Rt=__name(()=>{s()},"handleNoTrust"),Mt=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void R({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),N(e),S(!1);const n=getProviderDisplayName(e);d(`Provider set to ${n}`),Q.current&&clearTimeout(Q.current),H(!0),Q.current=setTimeout(()=>{H(!1),Q.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),d("Failed to set provider"),S(!1)}},"handleProviderSelect"),Nt=__name(()=>{S(!1)},"handleProviderCancel"),jt=__name(e=>{const t=Object.values(je).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Ot=__name(async e=>{try{await setSelectedModel({model:e}),O(e),A(!1);const t=jt(e);d(`Model set to ${t}`),ee.current&&clearTimeout(ee.current),Z(!0),ee.current=setTimeout(()=>{Z(!1),ee.current=null},5e3)}catch(e){console.error("Failed to set model:",e),d("Failed to set model"),A(!1)}},"handleModelSelect"),Lt=__name(()=>{A(!1)},"handleModelCancel"),_t=__name(()=>{if(F){R(null),S(!1),N(F.provider);const e=getProviderDisplayName(F.provider);d(`${e} authentication successful`),Q.current&&clearTimeout(Q.current),H(!0),Q.current=setTimeout(()=>{H(!1),Q.current=null},5e3)}},"handleAuthSuccess"),Ut=__name(()=>{R(null)},"handleAuthCancel");if(Ae)return null;if(ve)return U.createElement(U.Fragment,null,U.createElement(Yr,{staticKey:te}),U.createElement(Or,{onTrust:Ft,onExit:Rt}));if(Se)return null;if(ye)return U.createElement(jr,{onSelectSession:It,onNewSession:Dt});if(!Ce)return null;if(ct){if("shell_command"===ct.toolName){const e=ct.params;return U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(vr,{staticKey:te,feed:le,showHeader:!0,expandedToolOutput:re,currentModel:j}),U.createElement(q,{marginY:1},U.createElement(Br,{request:e,onResponse:e=>{mt(e);const t="no"!==e.value;ct.resolve(t),lt(null),t?(d("Shell command allowed"),Je||ft("Use shift+tab to enable auto-accept")):d("Shell command denied")},onToggleAutoAccept:yt})))}{const e={action:ct.toolName.includes("edit")?"edit":ct.toolName.includes("write")?"create":ct.toolName.includes("delete")?"delete":"edit",filePath:ct.params.filePath||ct.params.file_path||ct.params.path||ct.params.absolutePath||ct.params.notebook_path||"unknown",description:`Allow ${ct.toolName} operation`,oldContent:"edit_file"===ct.toolName?ct.params.oldContent:void 0,newContent:"edit_file"===ct.toolName?ct.params.newContent:void 0};return U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(vr,{staticKey:te,feed:le,showHeader:!0,expandedToolOutput:re,currentModel:j}),U.createElement(q,{marginY:1},U.createElement(Ur,{request:e,onResponse:e=>{mt(e);const t="no"!==e.value;ct.resolve(t),lt(null),t?(d("File operation allowed"),Je||ft("Use shift+tab to enable auto-accept")):d("File operation denied")},onToggleAutoAccept:yt})))}}return I?U.createElement(Hr,{onClose:()=>{D(!1),ne(e=>e+1)}}):b?U.createElement(U.Fragment,null,U.createElement(Yr,{staticKey:te}),U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),U.createElement(zr,{onClose:()=>v(!1),onSettingsChange:ot,staticKey:te}))):k?U.createElement(U.Fragment,null,U.createElement(Yr,{staticKey:te}),U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),U.createElement(Gr,{onClose:()=>C(!1),staticKey:te}))):U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(vr,{staticKey:te,feed:le,showHeader:!0,expandedToolOutput:re,currentModel:j}),U.createElement(RetryMessage,{attempt:u}),!T&&!P&&!F&&!x&&!w&&!et&&U.createElement(Nr,{queuedMessages:ge,isProcessing:ue,executionState:se,status:l,input:i,setInput:c,onSubmit:wt,showFileList:f,setShowFileList:y,fileSearchQuery:ie,setFileSearchQuery:ce,onCommand:St,outputTokens:$e,contextUsage:De,tasteLearning:qe,shareInfo:Oe,showShareNotification:ze,unshareNotificationMessage:He,updateStatus:g,updateFailedInfo:o,currentProvider:M,showProviderInfo:G,isOAuthMode:L,autoAcceptMode:Je,onToggleAutoAccept:yt,hintMessage:Ze}),T&&U.createElement(q,{marginY:1},U.createElement(Vr,{onSelect:Mt,onCancel:Nt,currentProvider:M})),P&&U.createElement(q,{marginY:1},U.createElement(qr,{onSelect:Ot,onCancel:Lt,currentModel:j})),w&&U.createElement(q,{marginY:1},U.createElement(co,{onCancel:()=>E(!1)})),x&&U.createElement(q,{marginY:1},U.createElement(Kr,{onClose:()=>$(!1)})),et&&it.current&&U.createElement(q,{marginY:1},U.createElement(uo,{checkpoints:it.current.listCheckpoints(),onSelect:kt,onCancel:Ct})),F&&U.createElement(q,{marginY:1},U.createElement(F.Component,{onSuccess:_t,onCancel:Ut})))},"InteractiveCLI"),po=__name(async(e={})=>{process.stdin.isTTY||(console.error("Error: Interactive mode requires a TTY terminal."),console.error("Please run this command directly in your terminal, not through a pipe or redirect."),process.exit(1));const t=getUpdateStatus(),n=getFailedUpdateInfo();enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()}),(e.resume||e.continue)&&await Xn.isProjectInitialized()&&0===(await Xn.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),Z(U.createElement(go,{resume:e.resume,continue:e.continue,trust:e.trust,updateStatus:t,updateFailedInfo:n,initialMessage:e.initialMessage}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:ho,yellow:fo}=te,yo=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${ke.error} ${ho(e)}`),console.log(`${ke.error} ${ho("ERROR →")} ${t.name}`),console.log(`${ke.info} ${ho("REASON →")} ${t.message}`),console.log(`${ke.info} ${ho("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${ke.warning} ${fo(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),wo=__name(()=>{process.on("unhandledRejection",e=>{yo(ve`CRITICAL: Unhandled Promise Rejection!
3
- This is an unexpected error. Please file a bug report at https://github.com/LangbaseInc/command-code/issues/new`,e)})},"handleUnhandledErrors");async function checkAuthAndPromptLogin(){try{const e=await getAuthKey(),t="win32"===process.platform,r=He();if(!e){const e=Er();console.log(te.white(e)),r&&console.log(te.dim(`env: (${r.replace("--","")})`)),console.log(""),console.log(`${o.warning} Authentication required to use Command Code.`),console.log("");const a=Ce.createInterface({input:process.stdin,output:process.stdout});try{const e=await a.question(`Would you like to sign in now? ${te.dim("(y/n)")}: `);a.close();const s=e.trim().toLowerCase();if(""!==s&&"y"!==s&&"yes"!==s)return console.log(""),console.log(`${o.info} You can authenticate later by running: ${t?"command-code":"cmd"} login`),!1;console.log(""),console.log(`${o.arrowUp} Running: ${t?"command-code":"cmd"} login`),console.log("");try{return n(`${t?"command-code":"cmd"} login ${r}`,{stdio:"inherit",cwd:process.cwd()}),await getAuthKey()?(console.log(""),console.log(`${o.tick} Authentication successful! Starting Command Code...`),console.log(""),!0):(console.log(""),console.log(`${o.cross} Authentication failed. Please try again with: ${t?"command-code":"cmd"} login`),!1)}catch(e){return console.log(""),console.log(`${o.cross} Login command failed. Please run: ${t?"command-code":"cmd"} login`),!1}}catch(e){return a.close(),console.log(""),console.log(`${o.info} Authentication cancelled. You can authenticate later with: ${t?"command-code":"cmd"} login`),!1}}return!0}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var Eo=__name(()=>{const e=[];for(const t of process.argv)"-v"===t?e.push("--version"):"-CRUD"===t?e.push("--crud"):"-CRU"===t?e.push("--cru"):"-C"===t?e.push("--create"):"-R"===t?e.push("--read"):"-U"===t?e.push("--update"):"-D"===t?e.push("--delete"):"-T"===t?e.push("--trust"):e.push(t);process.argv=e},"preprocessCustomFlags");async function updateProjectPermissions(e){const t=process.cwd(),n=f.join(t,".commandcode"),r=f.join(n,"settings.local.json");try{await S.mkdir(n,{recursive:!0});const t=await loadOrCreateSettings(r);updatePermissionsInSettings({settings:t,permissions:e}),await saveSettings({settingsPath:r,settings:t})}catch(e){throw new Error(`Failed to update project permissions: ${e instanceof Error?e.message:String(e)}`)}}async function loadOrCreateSettings(e){try{const t=parseJSON(await S.readFile(e,"utf-8"))||{permissions:{allow:[],deny:[],autoApprove:{}}};return t.permissions||(t.permissions={allow:[],deny:[]}),t.permissions.autoApprove||(t.permissions.autoApprove={}),t}catch{return{permissions:{allow:[],deny:[],autoApprove:{}}}}}function updatePermissionsInSettings(e){const{settings:t,permissions:n}=e;void 0!==n.create&&(t.permissions.autoApprove.create=n.create),void 0!==n.read&&(t.permissions.autoApprove.read=n.read),void 0!==n.update&&(t.permissions.autoApprove.update=n.update),void 0!==n.delete&&(t.permissions.autoApprove.delete=n.delete)}async function saveSettings(e){const{settingsPath:t,settings:n}=e;await S.writeFile(t,JSON.stringify(n,null,2),"utf-8")}async function handleCrudFlags(e){if(!(e.crud||e.cru||e.create||e.read||e.update||e.delete))return;await Xn.initializeProject();const t={};e.crud&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!0),e.cru&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!1),e.create&&(t.create=!0),e.read&&(t.read=!0),e.update&&(t.update=!0),e.delete&&(t.delete=!0),await updateProjectPermissions(t)}async function migrateUserDirectory(){const e=T.homedir(),t=y.join(e,".command-code"),n=y.join(e,".commandcode");if(!R.existsSync(t))return{success:!0,message:"User directory migration not needed (old directory does not exist)",skipped:!0};if(R.existsSync(n))return console.warn("Both ~/.command-code and ~/.commandcode exist. Manual intervention required."),console.warn("Please manually merge or remove ~/.command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{R.renameSync(t,n);const e=y.join(n,"config.json");if(R.existsSync(e)){const t=R.readFileSync(e,"utf-8"),n=JSON.parse(t);delete n.tasteUsage,R.writeFileSync(e,JSON.stringify(n,null,2))}return{success:!0,message:"User directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("User directory migration failed:",t),console.error("Please manually rename ~/.command-code to ~/.commandcode"),{success:!1,message:`User directory migration failed: ${t}`}}}async function migrateProjectDirectory(e){const{projectRoot:t}=e,n=y.join(t,".command-code"),r=y.join(t,".commandcode");if(!R.existsSync(n))return{success:!0,message:"Project directory migration not needed (old directory does not exist)",skipped:!0};if(R.existsSync(r))return console.warn(`Both .command-code and .commandcode exist in ${t}`),console.warn("Manual intervention required. Please manually merge or remove .command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{return R.renameSync(n,r),{success:!0,message:"Project directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("Project directory migration failed:",t),console.error("Please manually rename .command-code to .commandcode"),{success:!1,message:`Project directory migration failed: ${t}`}}}async function migrateDirectories(e){const{projectRoot:t}=e,n=await migrateUserDirectory(),r=await migrateProjectDirectory({projectRoot:t}),o=n.skipped,a=r.skipped;return o&&a||n.success&&r.success||console.warn("\n⚠️ Some migrations failed. See messages above."),{userResult:n,projectResult:r}}__name(updateProjectPermissions,"updateProjectPermissions"),__name(loadOrCreateSettings,"loadOrCreateSettings"),__name(function createDefaultPermissionsStructure(){return{allow:[],deny:[]}},"createDefaultPermissionsStructure"),__name(updatePermissionsInSettings,"updatePermissionsInSettings"),__name(saveSettings,"saveSettings"),__name(handleCrudFlags,"handleCrudFlags"),__name(migrateUserDirectory,"migrateUserDirectory"),__name(migrateProjectDirectory,"migrateProjectDirectory"),__name(migrateDirectories,"migrateDirectories");var bo=getPackageJson(),vo=process.cwd();global.COMMAND_CODE_CWD=vo;var ko=new Se("CommandCode");wo();var Co=__name(()=>{const e=process.argv.slice(2);return!e.includes("--skip-update-check")&&0===e.length},"shouldAutoUpdate");(async()=>{if(Eo(),await migrateDirectories({projectRoot:vo}),Co()&&(process.env.NODE_NO_WARNINGS="1",(await performAutoUpdate({onProgress:__name(e=>{process.stdout.write("\r"+e)},"onProgress")})).success)){process.stdout.write("\r");const e=process.argv[1]?.includes("command-code")?"command-code":"cmd",t=r(e,["--skip-update-check"],{stdio:"inherit",detached:!1,shell:!0,env:{...process.env,NODE_NO_WARNINGS:"1"}});await new Promise(()=>{t.on("exit",e=>{process.exit(e||0)})})}const n=new e;async function commanderAction(e,t){const n=e.findIndex(e=>!e.startsWith("-")),r=[];if(n>=0)for(let t=n;t<e.length&&!e[t].startsWith("-");t++)r.push(e[t]);const o=r.length>0?r.join(" "):void 0;await checkAuthAndPromptLogin()||process.exit(1),await handleCrudFlags({crud:t.crud,cru:t.cru,create:t.create,read:t.read,update:t.update,delete:t.delete});const a={};switch(t.trust&&(a.trust=!0),!0){case t.resume:po({resume:!0,...a});break;case t.continue:po({continue:!0,...a});break;default:po({...a,initialMessage:o})}}__name(commanderAction,"commanderAction"),n.name(bo.name).description(bo.description||"Command Code — Coding Agent with taste by Langbase").version(bo.version,"-v, --version","output the version number").argument("[message...]","Initial message to send").option("-r, --resume","Resume a conversation").option("-c, --continue","Continue the last conversation").option("-T, --trust","Auto-trust project (skip initial permission prompt)").option("--crud","Enable all CRUD permissions (shortcut: -CRUD)").option("--cru","Enable Create, Read, Update (no Delete) (shortcut: -CRU)").option("--create","Enable Create permission (shortcut: -C)").option("--read","Enable Read permission (shortcut: -R)").option("--update","Enable Update permission (shortcut: -U)").option("--delete","Enable Delete permission (shortcut: -D)").addOption(new t(Pe).hideHelp()).addOption(new t(Ae).hideHelp()).action(commanderAction).allowUnknownOption(),n.addCommand(ot),n.addCommand(nt),n.addCommand(ft),n.addCommand(xt),n.addCommand(createTasteCommand()),n.addCommand(Ze),n.addCommand(Xe),n.addCommand(Qe),n.hook("preAction",()=>{ko.debug("Command starting...")}),n.hook("postAction",()=>{ko.debug("Command completed.")}),n.parse()})();
2
+ import"dotenv/config";import{Command as e,Option as t}from"commander";import{execSync as n,spawn as r}from"child_process";import o,{mainSymbols as a}from"figures";import*as s from"@clack/prompts";import{confirm as i,isCancel as c,cancel as l,note as d,password as u,select as m,outro as g}from"@clack/prompts";import p from"picocolors";import h from"open";import*as f from"path";import y,{dirname as w,join as E,relative as b,isAbsolute as k,resolve as v}from"path";import*as C from"os";import T from"os";import*as S from"fs/promises";import P,{mkdir as A,writeFile as x}from"fs/promises";import $ from"crypto";import I,{z as D}from"zod";import*as F from"fs";import R,{existsSync as M,readFileSync as N,promises as j,constants as O,readdirSync as L,statSync as _}from"fs";import U,{useState as B,useEffect as W,useRef as z,useMemo as G,useCallback as H}from"react";import{Static as V,Box as q,Text as K,useInput as J,useStdout as Y,render as Z,useApp as X}from"ink";import Q from"ink-text-input";import ee from"sharp";import te from"chalk";import ne from"open-editor";import*as re from"process";import oe from"semver";import{fileURLToPath as ae}from"url";import se from"gray-matter";import{minimatch as ie}from"minimatch";import{glob as ce}from"glob";import{quote as le}from"shell-quote";import{MessageStream as de}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import ue from"@sindresorhus/slugify";import{EventEmitter as me}from"events";import ge from"@crosscopy/clipboard";import pe from"ink-gradient";import{Marked as he}from"marked";import fe from"marked-terminal";import*as ye from"diff";import we from"ignore";import Ee from"ink-select-input";import be from"dedent";import ke from"log-symbols";import ve from"readline/promises";var Ce=Object.defineProperty,__name=(e,t)=>Ce(e,"name",{value:t,configurable:!0}),Te=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${o.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${o.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${o.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${o.warning} ${e}`)}debug(e){process.env.DEBUG&&console.log(`[${this.prefix}] ${o.bullet} ${e}`)}};function heading({text:e,sub:t,dim:n,green:r}){return r?`${p.bgGreen(p.black(` ${e} `))} ${t&&t}`:n?`${p.bgBlack(p.white(` ${e} `))} ${t&&t}`:`${p.bold(p.bgCyan(p.black(` ${e} `)))} ${t&&t}`}__name(heading,"heading");var Se="--co",Pe="--xco",Ae=`x-${Se.replace("--","")}-flag`,xe="x-oauth-token",$e="x-project-slug",Ie="x-taste-learning",De={ALPHA:{GENERATE:"/alpha/generate",WHOAMI:"/alpha/whoami",NAMESPACES:"/alpha/namespaces",AGENT:{GENERATE:"/alpha/agent/generate"},SHARE:{CREATE:"/alpha/share/create",DELETE:"/alpha/share/delete",DATA:"/alpha/share/data",APPEND:"/alpha/share/append",CONNECT:"/alpha/share/connect"},DEVREL_THREAD:{CREATE:"/alpha/devrel-thread/create",DELETE:"/alpha/devrel-thread/delete",DATA:"/alpha/devrel-thread/data",UPDATE:"/alpha/devrel-thread/update"},TASTE:{GET:"/alpha/taste/:projectSlug",UPDATE:"/alpha/taste/:projectSlug/update",DELETE:"/alpha/taste/:projectSlug",LEARN:"/alpha/learn"}},BETA:{TASTE:{PACKAGES:{UPLOAD:"/beta/taste/packages/:namespace",LIST:"/beta/taste/packages",GET:"/beta/taste/packages/:namespace/:packageName",FILES:"/beta/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/beta/taste/packages/:namespace/:packageName/download",DELETE:"/beta/taste/packages/:namespace/:packageName"}}},INTERNAL:{ADMIN:{USERS:"/internal/admin/users",GRANT_CREDITS:"/internal/admin/grant-credits",ORGS:"/internal/admin/orgs",GRANT_ORG_CREDITS:"/internal/admin/grant-org-credits",ENTITY_TYPE:"/internal/admin/entity-type"},PROFILE:{GET:"/internal/profile/:login",PACKAGES:"/internal/profile/:login/packages",PACKAGE_GET:"/internal/profile/:login/packages/:packageName",PACKAGE_DOWNLOAD:"/internal/profile/:login/packages/:packageName/download",FOLLOWERS:"/internal/profile/:login/followers",FOLLOWING:"/internal/profile/:login/following"},API_KEYS:{CREATE:"/internal/api-keys/create",LIST:"/internal/api-keys/list",DELETE:"/internal/api-keys/delete"},BILLING:{CREDITS:{GET:"/internal/billing/credits"},CUSTOMERS:{GET:"/internal/billing/customers",UPSERT:"/internal/billing/customers",SETUP_INTENT:"/internal/billing/customers/setup-intent",PAYMENT_METHOD:"/internal/billing/customers/payment-method",SET_DEFAULT_PAYMENT_METHOD:"/internal/billing/customers/payment-method/set-default",INVOICES:"/internal/billing/customers/invoices"},SUBSCRIPTIONS:{GET:"/internal/billing/subscriptions"},WEBHOOK:"/internal/billing/webhook"},ORGS:{LIST:"/internal/orgs",GET:"/internal/orgs/:login",CREATE:"/internal/orgs",UPDATE:"/internal/orgs/:id",DELETE:"/internal/orgs/:id",AVATAR:"/internal/orgs/:id/avatar",MEMBERS:{LIST:"/internal/orgs/:id/members",ADD:"/internal/orgs/:id/members",UPDATE:"/internal/orgs/:id/members/:userId",REMOVE:"/internal/orgs/:id/members/:userId"},INVITATIONS:{LIST:"/internal/orgs/:id/invitations",SEND:"/internal/orgs/:id/invitations",ACCEPT:"/internal/invitations/:token/accept",CANCEL:"/internal/invitations/:id"},FOLLOW:"/internal/orgs/:orgId/follow",FOLLOWERS:"/internal/orgs/:orgId/followers"},USER:{SETTINGS:"/internal/user/settings",AVATAR:"/internal/user/avatar",FOLLOW:"/internal/users/:userId/follow",FOLLOWERS:"/internal/users/:userId/followers",FOLLOWING:"/internal/users/:userId/following"},USAGE:{LIST:"/internal/usage",SUMMARY:"/internal/usage/summary"},TASTE:{PACKAGES:{LIST:"/internal/taste/packages",BATCH:"/internal/taste/packages",GET:"/internal/taste/packages/:namespace/:packageName",FILES:"/internal/taste/packages/:namespace/:packageName/files",DOWNLOAD:"/internal/taste/packages/:namespace/:packageName/download",DELETE:"/internal/taste/packages/:namespace/:packageName",UPDATE:"/internal/taste/packages/:namespace/:packageName/update",STAR:"/internal/taste/packages/:namespace/:packageName/star",PIN:"/internal/taste/packages/:namespace/:packageName/pin"}}}},Fe={ALPHA:{TASTE:{GET:new RegExp("/alpha/taste/[a-z0-9-]+"),UPDATE:new RegExp("/alpha/taste/[a-z0-9-]+/update"),DELETE:new RegExp("/alpha/taste/[a-z0-9-]+/rules/[a-z0-9-]+"),LIST:new RegExp("/alpha/taste/[a-z0-9-]+/rules")}},BETA:{TASTE_PACKAGES:{UPLOAD:new RegExp("^/beta/taste/packages/[a-zA-Z0-9_-]+$"),FILES:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}},INTERNAL:{ORGS:{GET:new RegExp("/internal/orgs/[a-zA-Z0-9_-]+"),FOLLOW:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/followers")},USER:{FOLLOW:new RegExp("/internal/users/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/users/[a-zA-Z0-9-]+/followers"),FOLLOWING:new RegExp("/internal/users/[a-zA-Z0-9-]+/following")},TASTE:{PACKAGES:{GET:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),FILES:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),DOWNLOAD:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download"),UPDATE:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/update"),STAR:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/star"),PIN:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pin")}}}};Object.values(Fe.ALPHA.TASTE),Object.values(Fe.BETA.TASTE_PACKAGES),De.ALPHA.GENERATE,De.ALPHA.AGENT.GENERATE,De.ALPHA.WHOAMI,De.ALPHA.NAMESPACES,De.ALPHA.SHARE.CREATE,De.ALPHA.SHARE.DELETE,De.ALPHA.SHARE.APPEND,De.ALPHA.DEVREL_THREAD.CREATE,De.ALPHA.DEVREL_THREAD.DELETE,De.ALPHA.DEVREL_THREAD.UPDATE,De.ALPHA.TASTE.LEARN,De.ALPHA.TASTE.DELETE,De.ALPHA.TASTE.GET,De.ALPHA.TASTE.UPDATE,Object.values(De.BETA.TASTE.PACKAGES),Object.values(Fe.INTERNAL.ORGS),Object.values(Fe.INTERNAL.USER),Object.values(Fe.INTERNAL.TASTE.PACKAGES);var Re={INTERNAL:{PROFILE:{GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+"),PACKAGES:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages"),FOLLOWING:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/following"),FOLLOWERS:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/followers"),PACKAGE_GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+"),PACKAGE_DOWNLOAD:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+/download")}}};function getStudioAuthUrl(e){return"dev"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}Object.values(Re.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl");var Me="anthropic";I.enum(["owner","admin","member"]);var Ne={SONNET_4_5:{id:"claude-sonnet-4-5-20250929",label:"Default",name:"Sonnet 4.5",description:"recommended"},OPUS_4_5:{id:"claude-opus-4-5-20251101",label:"Opus",name:"Opus 4.5",description:""}},je=Ne.SONNET_4_5.id;new Set([].map(e=>e.toLowerCase()));var Oe,Le=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];(e=>{e.OAuth=D.object({type:D.literal("oauth"),refresh:D.string(),access:D.string(),expires:D.number()}),e.ApiKey=D.object({type:D.literal("api"),key:D.string()}),e.Info=D.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),n=__name(()=>y.join(T.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=t(),r="dev"===e?"models.dev.json":"staging"===e?"models.staging.json":"models.json";return y.join(n(),r)},"getAuthFile");async function get(e){try{const t=await P.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),a=r();await P.mkdir(o,{recursive:!0});let s={};try{const e=await P.readFile(a,"utf-8");s=JSON.parse(e)}catch{}s[e]=t,await P.writeFile(a,JSON.stringify(s,null,2)),await P.chmod(a,384)}async function remove(e){const t=r();try{const n=await P.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await P.unlink(t):(await P.writeFile(t,JSON.stringify(r,null,2)),await P.chmod(t,384))}catch{}}async function list2(){try{const e=await P.readFile(r(),"utf-8");return JSON.parse(e)}catch{return{}}}e.get=get,__name(get,"get"),e.set=set,__name(set,"set"),e.remove=remove,__name(remove,"remove"),e.list=list2,__name(list2,"list")})(Oe||(Oe={}));var _e,Ue="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing";async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=ee(n),a=await o.metadata();if(!a.width||!a.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const s=1200;let i,c,{width:l,height:d}=a;(l>s||d>s)&&(l>d?(d=Math.round(d*s/l),l=s):(l=Math.round(l*s/d),d=s)),t.includes("png")&&a.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:u,compressionRatio:r/u}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}async function detectClipboardImage(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasImage())return null;let t=null;try{if(t=await e.default.getImageBase64(),!t){const n=e.default.getImageBase64();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}if(!t||0===t.length)return null;if(t.length>32e6)return console.log("Image too large:",t.length,"bytes"),null;try{const e=await compressImageForSharing(t,"image/png");return e?{data:e.compressedBase64,mediaType:e.mediaType}:(console.log("Failed to compress clipboard image"),null)}catch(e){return console.log("Failed to process clipboard image:",e),null}}catch(e){return null}}async function detectClipboardText(){try{const e=await import("@crosscopy/clipboard");if(!e.default.hasText())return null;let t=null;try{if(t=await e.default.getText(),!t){const n=e.default.getText();t=n&&"function"==typeof n.then?await n:n}}catch(e){return null}return t&&0!==t.length?t:null}catch(e){return null}}function processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};let r=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");return r=r.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),{isPasteStart:t,isPasteEnd:n,cleanedContent:r}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}(e=>{const t="9d1c250a-e61b-44d9-88ed-5944d1962f5e",n="https://console.anthropic.com/v1/oauth/token",r="https://console.anthropic.com/oauth/code/callback";function generateCodeVerifier(){return $.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return $.createHash("sha256").update(e).digest("base64url")}function generateState(){return $.randomBytes(32).toString("base64url")}function createAuthorizationUrl(){const e=generateCodeVerifier(),n=generateCodeChallenge(e),o=generateState();return{url:`https://claude.ai/oauth/authorize?${new URLSearchParams({code:"true",client_id:t,response_type:"code",redirect_uri:r,scope:"org:create_api_key user:profile user:inference",code_challenge:n,code_challenge_method:"S256",state:o}).toString()}`,verifier:e,state:o}}async function exchangeCodeForTokens(e,o,a){const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:a})});if(!s.ok){const e=await s.text();throw new Error(`Token exchange failed: ${e}`)}const i=await s.json();await Oe.set("anthropic",{type:"oauth",refresh:i.refresh_token,access:i.access_token,expires:Date.now()+1e3*i.expires_in})}async function refreshAccessToken(){const e=await Oe.get("anthropic");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return e.access;try{const r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t,refresh_token:e.refresh})});if(!r.ok)return void await Oe.remove("anthropic");const o=await r.json();return await Oe.set("anthropic",{type:"oauth",refresh:o.refresh_token,access:o.access_token,expires:Date.now()+1e3*o.expires_in}),o.access_token}catch(e){return void await Oe.remove("anthropic")}}}async function getValidAccessToken(){const e=await Oe.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens,__name(exchangeCodeForTokens,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken,__name(refreshAccessToken,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken,__name(getValidAccessToken,"getValidAccessToken")})(_e||(_e={})),__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var Be={"command-code":{id:"command-code",displayName:"Command Code",description:"recommended",requiresAuth:!1},anthropic:{id:"anthropic",displayName:"Anthropic",description:"Claude Pro/Max",requiresAuth:!0,hidden:!0,authComponent:__name(({onSuccess:e,onCancel:t})=>{const[n,r]=B(""),[o,a]=B(null),[s,i]=B(!1),[c,l]=B(null),[d,u]=B(!0),[m,g]=B(!1),[p,f]=B(!1);W(()=>{const{url:e,verifier:t,state:n}=_e.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=H(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}r(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();r(t)}else if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();r(e)}return}},[p]);J((e,n)=>{n.escape&&t(),d&&!m&&("y"===e||"Y"===e?o&&(h(o.url).catch(console.error),g(!0),u(!1)):"n"!==e&&"N"!==e||t())});const w=__name(async()=>{if(n.trim()&&o&&!s){i(!0),l(null);try{const t=n.split("#")[0].trim();await _e.exchangeCodeForTokens(t,o.verifier,o.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){l(e instanceof Error?e.message:"Authentication failed"),i(!1)}}},"handleSubmit");return d&&!m?U.createElement(q,{flexDirection:"column"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),U.createElement(q,{marginBottom:1},U.createElement(K,null,"Open the Anthropic auth page?",U.createElement(K,{dimColor:!0}," (Y/n)")))):U.createElement(q,{flexDirection:"column"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"cyan"},"Anthropic Authentication")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"After authorizing, copy the code and paste it below:")),c&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"red"},"Error: ",c)),U.createElement(q,null,U.createElement(K,null,"Authorization code: "),U.createElement(Q,{mask:"*",focus:!0,value:n,onChange:y,onSubmit:w,placeholder:"Paste code here..."})),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth"),checkAuth:__name(async()=>!!await _e.getValidAccessToken(),"checkAuth")}};function getProviderDisplayName(e){if(!e)return"None";const t=Be[e];return t?.displayName||e}function getProviderConfig(e){return Be[e]}function isInternalFlagPresent(){return process.argv.includes(Se)}function getProviderOptions(){const e=isInternalFlagPresent();return Object.values(Be).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}async function loadUserConfig(){try{const e=qe();return parseJSON(await S.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=qe();F.writeFileSync(t,JSON.stringify(e,null,2)),F.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=getConfiguredModel(),r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isTasteLearningEnabled(){return(await loadUserConfig()).tasteLearning??!0}async function setTasteLearning(e){const{tasteLearning:t}=e;await updateUserConfig({tasteLearning:t})}async function isOAuthEnforced(){return isInternalFlagPresent()?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),!0):(await loadUserConfig()).forceOAuth??!1}function validateOAuthToken(e){const{token:t,provider:n}=e;if("anthropic"===n&&!t)throw new Error('OAuth authentication required. Please use /provider command\nSelect "Anthropic (Claude Pro/Max)" and complete the OAuth setup.')}function getConfiguredModel(){try{const e=qe();return(parseJSON(F.readFileSync(e,"utf-8"))||{}).model??je}catch{return je}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalFlagPresent,"isInternalFlagPresent"),__name(getProviderOptions,"getProviderOptions"),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning"),__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel");var We=__name(()=>y.join(T.homedir(),".commandcode"),"getAuthDir"),ze=__name(()=>{const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"dev":t?"staging":"prod"},"getEnv"),Ge=__name(()=>{const e=ze();return"dev"===e?"--dev":"staging"===e?"--staging":""},"getEnvFlag"),He=__name(e=>{const t=e??ze(),n="dev"===t?"auth.dev.json":"staging"===t?"auth.staging.json":"auth.json";return y.join(We(),n)},"getAuthFile"),Ve=__name(()=>y.join(T.homedir(),".commandcode"),"getConfigDir"),qe=__name(e=>{const t=e??ze(),n="dev"===t?"config.dev.json":"staging"===t?"config.staging.json":"config.json";return y.join(Ve(),n)},"getConfigFile"),Ke=__name(e=>{const t=e??ze(),n="dev"===t?"models.dev.json":"staging"===t?"models.staging.json":"models.json";return y.join(Ve(),n)},"getModelsFile");async function loginAction(){try{const e=ze(),t=getStudioAuthUrl(e);console.log("\n"),s.intro(heading({text:"Command Code Authentication",sub:""}));const n=await i({message:`Open the authentication page? ${p.dim("— copy your API key from there and paste it here.")}`});c(n)&&(l(`${o.cross} Login cancelled.`),process.exit(0)),n&&(await h(t),d(p.yellow("Please copy your API key from the opened page and paste it here.")));const r=await u({message:"Paste your API key:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(0)),r.trim()||(console.log(`${o.cross} No API key provided.`),process.exit(1));const a=We(),f=He(e);await P.mkdir(a,{recursive:!0}),await P.writeFile(f,JSON.stringify({apiKey:r},null,2)),await P.chmod(f,384);const y=getProviderOptions();let w;if(1===y.length)w=y[0].value;else{const e=await m({message:"Select provider",options:y});if(c(e)&&(l(`${o.cross} No provider selected.`),process.exit(0)),w=e,"anthropic"===w){const e=await m({message:"Login method",options:[{value:"anthropic-oauth",label:"Claude Pro/Max"}]});c(e)?l(`${o.cross} No login method selected.`):"anthropic-oauth"===e&&await anthropicAuth()}}await updateUserConfig({provider:w});let E=`You are logged in. API key is stored in ~/.commandcode/${"dev"===e?"auth.dev.json":"staging"===e?"auth.staging.json":"auth.json"}. Run \`cmd\` to get started.`;g(p.green(E)),process.exit(0)}catch(e){console.error(`${o.cross} Login failed:`,e instanceof Error?e.message:"Unknown error"),process.exit(1)}}async function anthropicAuth(){try{const{url:e,verifier:t,state:n}=_e.createAuthorizationUrl();await i({message:"Open the Anthropic auth page?"})&&(await h(e),d(p.yellow("Please copy your authorization code from the opened page and paste it here.")));const r=await u({message:"Paste your authorization code:",mask:"*"});c(r)&&(l(`${o.cross} No API key provided.`),process.exit(1)),r.trim()||(console.log(`${o.cross} No authorization code provided`),process.exit(1));const a=r.split("#")[0].trim();return await _e.exchangeCodeForTokens(a,t,n),!0}catch(e){l(`${o.cross} Anthropic OAuth failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function logoutAction(){try{const e=ze(),t=He(e),n=Ke(e);try{await P.unlink(t)}catch(e){}try{const e=await loadUserConfig(),{provider:t,...n}=e;await saveUserConfig(n)}catch(e){}try{await P.unlink(n)}catch(e){}g(p.green("Successfully logged out from Command Code")),process.exit(0)}catch(e){l(`${o.cross} Logout failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}async function getAuthKey(e){try{const t=He(e),n=await P.readFile(t,"utf-8");return JSON.parse(n).apiKey||null}catch{return null}}async function statusAction(){try{const e=ze();await getAuthKey(e)||(l(`${o.cross} Not authenticated. Please login using "cmd auth login".`),process.exit(1)),g(p.green(`${o.tick} Authenticated with Command Code`)),process.exit(0)}catch(e){l(`${o.cross} Status check failed: ${e instanceof Error?e.message:"Unknown error"}`),process.exit(1)}}__name(loginAction,"loginAction"),__name(anthropicAuth,"anthropicAuth"),__name(logoutAction,"logoutAction"),__name(getAuthKey,"getAuthKey"),__name(statusAction,"statusAction");var Je=new e("auth").description("Manage authentication with Command Code");Je.command("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Je.command("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Je.command("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);var Ye=new e("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction),Ze=new e("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction),Xe=new e("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction);function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${T.platform()}-${T.arch()}, Node.js ${process.version}`}function getRootDirectoryStructure(){const e=getCurrentWorkingDirectory(),t=new Set(["node_modules","dist","build",".git",".svn",".hg","coverage",".nyc_output",".cache","tmp","temp",".next",".nuxt","out"]);try{return R.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function isGitRepository(){try{return n("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return n("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=n("git branch -r",{encoding:"utf8",cwd:getCurrentWorkingDirectory()});return e.includes("origin/main")?"main":e.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=n("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),r=t.filter(e=>e.startsWith(" M")).length,o=t.filter(e=>e.startsWith("A ")).length,a=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,i=[];return r>0&&i.push(`M ${r}`),o>0&&i.push(`A ${o}`),a>0&&i.push(`D ${a}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=n("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getRootDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[]}}function detectTerminal(){const e=process.env;if(e.TERM_PROGRAM){const t=e.TERM_PROGRAM;if("vscode"===t)return{name:"Visual Studio Code",type:"vscode",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("iTerm.app"===t)return{name:"iTerm2",type:"iterm2",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION,iterm2Profile:e.ITERM_PROFILE}};if("Apple_Terminal"===t)return{name:"macOS Terminal",type:"terminal",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("WarpTerminal"===t)return{name:"Warp",type:"warp",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}};if("Hyper"===t)return{name:"Hyper",type:"hyper",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}function isDisableOAuthFlagPresent(){return process.argv.includes(Pe)}function formatDate(e=new Date){return e.toISOString().split("T")[0]}function parseJSON(e){try{return JSON.parse(e)}catch{return null}}async function getConfiguredProvider(){try{const e=qe(),t=await P.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,a=isInternalFlagPresent();return isDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):a||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!e.ctrl||"o"!==t)}__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext"),__name(detectTerminal,"detectTerminal"),__name(getIsTerminalIterm2,"getIsTerminalIterm2"),__name(isDisableOAuthFlagPresent,"isDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut");var Qe=new Te("Config"),et=f.join(C.homedir(),".commandcode-config.json");async function loadConfig(){try{return parseJSON(await S.readFile(et,"utf-8"))||{}}catch{return{}}}async function saveConfig(e){await S.writeFile(et,JSON.stringify(e,null,2))}__name(loadConfig,"loadConfig"),__name(saveConfig,"saveConfig");var tt=new e("config").description("Manage CLI configuration").addCommand(new e("get").description("Get a configuration value").argument("<key>","Configuration key").action(async e=>{const t=(await loadConfig())[e];void 0!==t?Qe.info(`${e}: ${JSON.stringify(t)}`):Qe.warn(`Key "${e}" not found in configuration`)})).addCommand(new e("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action(async(e,t)=>{"provider"!==e||"anthropic"!==t||isInternalFlagPresent()||(Qe.error('Invalid provider "anthropic". Available provider: command-code'),process.exit(1));const n=await loadConfig();let r=t;"true"===t?r=!0:"false"===t?r=!1:isNaN(Number(t))||(r=Number(t)),n[e]=r,await saveConfig(n),Qe.success(`Set ${e} = ${JSON.stringify(r)}`)})).addCommand(new e("list").description("List all configuration values").action(async()=>{const e=await loadConfig();0===Object.keys(e).length?Qe.info("No configuration values set"):(Qe.info("Current configuration:"),Object.entries(e).forEach(([e,t])=>{console.log(` ${e}: ${JSON.stringify(t)}`)}))})).addCommand(new e("reset").description("Reset all configuration").action(async()=>{await saveConfig({}),Qe.success("Configuration reset successfully")})),nt=new Te("Info"),rt=new e("info").description("Display system information").option("-v, --verbose","Show verbose output").action(e=>{if(nt.info("System Information:"),console.log("-------------------"),console.log(`${o.info} Date: ${formatDate()}`),console.log(`${o.info} Platform: ${C.platform()}`),console.log(`${o.info} Architecture: ${C.arch()}`),console.log(`${o.info} CPUs: ${C.cpus().length}`),console.log(`${o.info} Memory: ${Math.round(C.totalmem()/1024/1024/1024)} GB`),console.log(`${o.info} Home Directory: ${C.homedir()}`),e.verbose){console.log("\nDetailed CPU Information:"),C.cpus().forEach((e,t)=>{console.log(` CPU ${t}: ${e.model} @ ${e.speed} MHz`)}),console.log("\nNetwork Interfaces:");const e=C.networkInterfaces();Object.keys(e).forEach(t=>{const n=e[t];n&&n.forEach(e=>{"IPv4"!==e.family||e.internal||console.log(` ${t}: ${e.address}`)})})}nt.success("Information displayed successfully!")});function getApiBaseUrl(){const e=process.argv.includes("--dev"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(getApiBaseUrl,"getApiBaseUrl");var ot=class _APIError extends Error{static{__name(this,"APIError")}status;headers;error;code;param;type;request_id;constructor(e,t,n,r){super(_APIError.makeMessage(e,t,n)),this.status=e,this.headers=r,this.request_id=r?.["lb-request-id"];const o=t;this.error=o,this.code=o?.code,this.status=o?.status}static makeMessage(e,t,n){const r=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e)return new at({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new st(e,o,n,r);case 401:return new it(e,o,n,r);case 403:return new ct(e,o,n,r);case 404:return new lt(e,o,n,r);case 409:return new dt(e,o,n,r);case 422:return new ut(e,o,n,r);case 429:return new mt(e,o,n,r);default:return e>=500?new gt(e,o,n,r):new _APIError(e,o,n,r)}}},at=class extends ot{static{__name(this,"APIConnectionError")}status=void 0;constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},st=class extends ot{static{__name(this,"BadRequestError")}status=400},it=class extends ot{static{__name(this,"AuthenticationError")}status=401},ct=class extends ot{static{__name(this,"PermissionDeniedError")}status=403},lt=class extends ot{static{__name(this,"NotFoundError")}status=404},dt=class extends ot{static{__name(this,"ConflictError")}status=409},ut=class extends ot{static{__name(this,"UnprocessableEntityError")}status=422},mt=class extends ot{static{__name(this,"RateLimitError")}status=429},gt=class extends ot{static{__name(this,"InternalServerError")}},pt=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=await this.buildHeaders({headers:e.headers});let o;try{o=await this.makeRequest({url:n,options:e,headers:r})}catch(e){throw new at({cause:e instanceof Error?e:void 0})}return o.ok||await this.handleErrorResponse({response:o}),e.stream?o.body:o.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const a=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),a}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={};throw e.headers.forEach((e,t)=>{n[t]=e}),ot.generate(e.status,t,e.statusText,n)}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"})}};async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new pt({baseUrl:e});return await t.get({endpoint:De.ALPHA.WHOAMI})}async function whoamiAction(){try{await getAuthKey()||(console.log(`${o.cross} ${p.red('Not authenticated. Please login using "cmd auth login"')}`),process.exit(1));const e=await getAuthenticatedEntity();e.success&&e.user||(console.log(`${o.cross} ${p.red("Failed to fetch user info")}`),process.exit(1)),console.log(`\n${p.bold("User Information:")}`),console.log(`${o.info} Name: ${p.cyan(e.user.name)}`),console.log(`${o.info} Email: ${p.cyan(e.user.email)}`),console.log(`${o.info} Username: ${p.cyan(e.user.userName)}`),e.org&&(console.log(`\n${p.bold("Organization:")}`),console.log(`${o.info} Name: ${p.cyan(e.org.name)}`),console.log(`${o.info} Login: ${p.cyan(e.org.login)}`)),console.log("")}catch(e){console.log(`${o.cross} ${p.red(`Error: ${e instanceof Error?e.message:"Unknown error"}`)}`),process.exit(1)}}__name(getAuthenticatedEntity,"getAuthenticatedEntity"),__name(whoamiAction,"whoamiAction");var ht=new e("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function getTastePath(e){const{target:t}=e;switch(t){case"local-project":return f.join(process.cwd(),".commandcode","taste");case"local-global":return f.join(C.homedir(),".commandcode","taste");case"remote-project":case"remote-user":throw new Error(`Remote storage not yet implemented: ${t}`);default:throw new Error(`Unknown storage target: ${t}`)}}function getRootTasteFile(e){const{target:t}=e;return f.join(getTastePath({target:t}),"taste.md")}function getCategoryPath(e){const{target:t,category:n}=e;return f.join(getTastePath({target:t}),n)}function getCategoryTasteFile(e){const{target:t,category:n}=e;return f.join(getCategoryPath({target:t,category:n}),"taste.md")}function parseTasteBuckets(e){const{content:t,sourcePath:n}=e,r=[],o=t.split(/^# /gm).filter(e=>e.trim());for(const e of o){const t=e.split("\n"),o=t[0].trim();if(e.includes("See ["))continue;const a=[];for(const e of t){const t=parseLearning({line:e});t&&a.push(t)}a.length>0&&r.push({category:normalizeCategory({category:o}),learnings:a,sourcePath:n})}return r}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatBucket(e){const{bucket:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),__name(parseTasteBuckets,"parseTasteBuckets"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),__name(formatBucket,"formatBucket");var ft="# Taste (Continuously Learned by CommandCode.ai)",yt=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return yt.test(t)?t.replace(yt,`$1${ft}`):t}__name(migrateHeader,"migrateHeader");var wt=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!M(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(M(n)){let e=await S.readFile(n,"utf-8");const r=migrateHeader({content:e});r!==e&&(await S.writeFile(n,r,"utf-8"),e=r);const o=parseTasteBuckets({content:e,sourcePath:n});t.push(...o)}const r=await S.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(M(n)){let r=await S.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await S.writeFile(n,o,"utf-8"),r=o);const a=parseTasteBuckets({content:r,sourcePath:n});for(const t of a)t.category=e.name;t.push(...a)}}return t}async getBucket(e){const{category:t}=e;return(await this.getAllBuckets()).find(e=>e.category===t)||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await S.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,a=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:a}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:a})}async removeBucket(e){const{category:t}=e,n=getRootTasteFile({target:this.target});let r=null;if(M(n)){let e=await S.readFile(n,"utf-8");e=migrateHeader({content:e});const o=e.split("\n");let a=-1,s=-1;const i=new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let e=0;e<o.length;e++)if(i.test(o[e])){a=e;for(let t=e+1;t<o.length;t++)if(o[t].startsWith("# ")){let n=t-1;for(;n>e&&""===o[n].trim();)n--;s=n;break}-1===s&&(s=o.length-1);break}if(-1!==a){const e=o.slice(0,a),t=s<o.length-1?o.slice(s+1):[];r={before:e.join("\n").trim(),after:t.join("\n").trim()};const i=[...e,...t].join("\n").trim();""===i?await S.rm(n,{force:!0}):await S.writeFile(n,i+"\n","utf-8")}}const o=getCategoryTasteFile({target:this.target,category:t}),a=f.dirname(o);return M(a)&&await S.rm(a,{recursive:!0,force:!0}),r}async writeToRoot(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=formatBucket({bucket:t});if(r){let e=r.before;e&&!e.trim().startsWith(ft)&&(e=ft+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o.trim(),r.after&&(e+="\n\n"+r.after),await S.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";M(n)&&(e=await S.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(ft)||(e=ft+"\n\n"+e):e=ft+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await S.writeFile(n,e.trim()+"\n","utf-8")}}async writeToSubdirectory(e){const{bucket:t,rootFile:n,categoryPosition:r}=e,o=getCategoryTasteFile({target:this.target,category:t.category}),a=f.dirname(o);await S.mkdir(a,{recursive:!0});const s=formatBucket({bucket:t});await S.writeFile(o,s,"utf-8");const i=`# ${t.category}\nSee [${t.category}/taste.md](${t.category}/taste.md)\n`;if(r){let e=r.before;e=migrateHeader({content:e}),e&&!e.trim().startsWith(ft)&&(e=ft+"\n\n"+e),e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i.trim(),r.after&&(e+="\n\n"+r.after),await S.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";M(n)&&(e=await S.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(ft)||(e=ft+"\n\n"+e):e=ft+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i,await S.writeFile(n,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return M(e)}},Et=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!M(e))return[];const t=[],n=await S.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(M(n)){let r=await S.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await S.writeFile(n,o,"utf-8"),r=o);const a=parseTasteBuckets({content:r,sourcePath:n});for(const t of a)t.category=e.name;t.push(...a)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});if(!M(n))return null;let r=await S.readFile(n,"utf-8");const o=migrateHeader({content:r});return o!==r&&(await S.writeFile(n,o,"utf-8"),r=o),parseTasteBuckets({content:r,sourcePath:n})[0]||null}async writeBucket(e){const{bucket:t}=e,n=getTastePath({target:this.target});await S.mkdir(n,{recursive:!0});const r=getCategoryTasteFile({target:this.target,category:t.category}),o=f.dirname(r);await S.mkdir(o,{recursive:!0});const a=formatBucket({bucket:t});await S.writeFile(r,a,"utf-8")}async deleteBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t}),r=f.dirname(n);M(r)&&await S.rm(r,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await S.stat(n.sourcePath)).mtime}catch{e=new Date}t.push({category:n.category,learningCount:n.learnings.length,lastUpdated:e,filePath:n.sourcePath})}return t}exists(){const e=getTastePath({target:this.target});return M(e)}};async function prepareUploadFormData(e){const{packageName:t,bucket:n,description:r,type:o="category",isPublic:a=!1}=e,s=new FormData;if(s.append("name",t),r&&s.append("description",r),s.append("type",o),s.append("isPublic",String(a)),"category"===o){const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",r)}else{const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",r);const o=getTastePath({target:"local-project"}),a=f.join(o,n.category);if(M(a)){const e=getCategoryTasteFile({target:"local-project",category:n.category});if(M(e)){const t=await S.readFile(e,"utf-8"),r=new Blob([t],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});s.append(`files[${n.category}/taste.md]`,o)}}}return s}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r,isPublic:o=!1}=e,a=new FormData;a.append("name",n),r&&a.append("description",r),a.append("type","project"),a.append("isPublic",String(o));const s=getRootTasteFile({target:"local-project"});if(M(s)){const e=await S.readFile(s,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});a.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(M(t)){const n=await S.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});a.append(`files[${e.category}/taste.md]`,o)}}return a}function parseTasteContent(e){const t=[],n=e.split("\n");for(const e of n){const n=e.trim();if(!n||n.startsWith("#")||!n.startsWith("-"))continue;const r=n.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(r){const e=r[1].trim(),n=parseFloat(r[2]);e&&!isNaN(n)&&t.push({text:e,confidence:n})}}return t}__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),__name(parseTasteContent,"parseTasteContent");var bt=class{static{__name(this,"RemoteStorage")}async getAllBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const a=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&a.push(t)}catch(t){console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return a}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=getApiBaseUrl(),o=`${r}${De.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",t).replace(":packageName",n)}`;try{const e=await fetch(o,{method:"GET"});if(e.ok){const{data:t}=await e.json();return{type:t.type||"category",files:t.files||[],isPublic:!0}}if(404!==e.status){let t="Failed to download taste package";try{const n=await e.json();t=n.error?.message||n.message||`${t} (${e.status})`}catch{t=`${t} (${e.status})`}throw new Error(t)}if(!await getAuthKey())throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`")}catch(e){if(e instanceof Error)throw e}const a=await getAuthKey();if(!a)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");const s=`${r}${De.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${a}`}});if(!i.ok){if(404===i.status)return null;let e="Failed to download taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:c}=await i.json();return{type:c.type||"category",files:c.files||[],isPublic:c.isPublic??!1}}async getBucket(e){const{category:t}=e;if(!await getAuthKey())throw new Error("No API key found. Please authenticate with: cmd login");const n=await getAuthenticatedEntity();if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");const r=n.user.userName;return this.downloadPackageToBucket({namespace:r,packageName:t})}async downloadPackageToBucket(e){const{namespace:t,packageName:n}=e,r=await this.downloadPackage({namespace:t,packageName:n});if(!r)return null;const o=r.files||[];if(0===o.length)return null;const a=o.find(e=>"taste.md"===e.file);if(!a)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async writeBucket(e){const{bucket:t,namespace:n,isPublic:r=!1}=e,o=await getAuthKey();if(!o)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category",isPublic:r}),s=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:a});if(!i.ok){let e="Failed to upload taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}await i.json()}async writeBuckets(e){const{buckets:t,projectName:n,namespace:r,isPublic:o=!1}=e,a=await getAuthKey();if(!a)throw new Error("No API key found. Please authenticate with: cmd login");const s=await prepareMultiplePackagesUpload({buckets:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:s});if(!c.ok){let e="Failed to upload taste packages";try{const t=await c.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}await c.json()}async deleteBucket(e){throw new Error("Remote storage not yet implemented")}async listBuckets(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");const t=`${getApiBaseUrl()}${De.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!n.ok){let e="Failed to list taste packages";try{const t=await n.json();e=t.error?.message||t.message||e}catch{}throw new Error(e)}const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}async importBucket(e){throw new Error("Remote storage not yet implemented")}};function mergeLearnings(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},o=new Map;for(const e of n)o.set(e.text,e);const a=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(a.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(a.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(a.values()),details:r}}__name(mergeLearnings,"mergeLearnings");var kt=/confidence:/i;function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const o=t.split("\n"),a=[];let s=0;for(;s<o.length;){const e=o[s],t=s+1,n=e.trim();if(n.startsWith("-"))if(kt.test(n))a.push({text:e,originalLineNum:t}),s++;else{let n=e,r=s+1;for(;r<o.length;){const e=o[r].trim();if(e.startsWith("#")||e.startsWith("-"))break;if(e.length>0&&(n=n+" "+e),kt.test(e)){r++;break}r++}a.push({text:n,originalLineNum:t}),s=r}else a.push({text:e,originalLineNum:t}),s++}let i=null,c=null,l=0;for(const{text:e,originalLineNum:t}of a){if(!e.trim())continue;if(e.trim().startsWith("# ")){if("# Taste (Continuously Learned by CommandCode.ai)"===e.trim()||"# Taste (Continuously Learned by CommandCode)"===e.trim())continue;i&&0===l&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),i=e.trim().substring(2).trim(),c=t,l=0;continue}if(e.trim().startsWith("-")){if(!i){r.push({line:t,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'});continue}l++;const n=validateLearningLine({line:e.trim(),lineNum:t});r.push(...n);continue}const n=e.trim();/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i.test(n)||r.push({line:t,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"})}return i&&0===l&&c&&(hasReferenceAfterCategory({lines:o,categoryLineIndex:c-1})||r.push({line:c,severity:"warning",message:`Category '${i}' has no learnings`,suggestion:"Add at least one learning or remove this category"})),buildResult({issues:r,filePath:n})}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=n+3;for(let e=n+1;e<t.length&&e<r;e++){const n=t[e];if(n.trim().startsWith("# "))break;if(n.includes("See [")&&n.includes("taste.md"))return!0}return!1}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!kt.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 a=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),s=a.length>0?a[a.length-1]:null;if(!s)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=s[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;c<0||c>1?r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}):0===c&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});let l="";return l=s&&void 0!==s.index?o.substring(0,s.index).trim():o.trim(),l&&0!==l.length?l.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}):r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),o=t.filter(e=>"warning"===e.severity),a=0===r.length;let s;if(0===t.length)s=`✓ ${n} is valid`;else{const e=[];r.length>0&&e.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&e.push(`${o.length} warning${o.length>1?"s":""}`),s=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:a,issues:t,summary:s}}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${te.green(e)} ${te.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity),a=[r.length>0?te.red(t.summary):te.yellow(t.summary),""];if(r.length>0){a.push(te.bold(te.red("Errors:")));for(const e of r){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.red(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}if(o.length>0){a.push(te.bold(te.yellow("Warnings:")));for(const e of o){const t=e.line?te.dim(` Line ${e.line}: `):" ";a.push(`${t}${te.yellow(e.message)}`),e.suggestion&&a.push(te.dim(` → ${e.suggestion}`))}a.push("")}return a.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:t,namespace:n,localBucket:r,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${r.learnings.length} learnings`),console.log(`Remote: ${a} learnings (from ${n})\n`);const i=await s.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} → ${a} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptPushStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteBucket:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${a.learnings.length} learnings (in ${n})\n`);const i=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${a.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return s.isCancel(i)&&(s.cancel("Operation cancelled"),process.exit(0)),i}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalBucket:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in global storage\n`)),console.log(`Local: ${n} learnings`),console.log(`Global: ${r.learnings.length} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function promptGlobalPullStrategy(e){const{packageName:t,localBucket:n,globalLearningsCount:r}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(te.yellow(`\n${o.warning} Package '${t}' already exists locally\n`)),console.log(`Local: ${n.learnings.length} learnings`),console.log(`Global: ${r} learnings\n`);const a=await s.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});return s.isCancel(a)&&(s.cancel("Operation cancelled"),process.exit(0)),a}async function promptTypeMismatchStrategy(e){const{packageName:t,namespace:n,localType:r,remoteType:a,localLearningsCount:i,remoteLearningsCount:c}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, skipping push`)),"skip";const l=`https://commandcode.ai/${n}/${t}`;console.log(te.yellow(`\n${o.warning} Pushing local project taste to individual package '${t}'\n`)),console.log(`Local: ${t} (${i} learnings)`),console.log(`Remote: ${t} (${c} learnings) in ${n}\n`),console.log(`Review package: ${te.cyan(l)}\n`);const d=await s.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});return s.isCancel(d)&&(s.cancel("Operation cancelled"),process.exit(0)),d}async function promptSameTypeStrategy(e){const{packageName:t,namespace:n,localLearningsCount:r,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(te.yellow(`\n${o.warning} Non-interactive terminal detected, skipping push`)),"skip";const i=`https://commandcode.ai/${n}/taste/${t}`;console.log(te.yellow(`\n${o.warning} Package '${t}' already exists in ${n}\n`)),console.log(`Local: ${r} learnings`),console.log(`Remote: ${a} learnings\n`),console.log(`Review taste package: ${te.cyan(i)}\n`);const c=await s.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 (${a} → ${r} learnings)`}],initialValue:"skip"});return s.isCancel(c)&&(s.cancel("Operation cancelled"),process.exit(0)),c}async function push(e){const t=void 0!==e.isPublic,{buckets:n,target:r,overwrite:o=!1,isPublic:a=!1}=e,s=new wt,i={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!s.exists())return i.success=!1,i.errors.push({bucket:"all",error:"No taste directory found in project"}),i;const c=await s.getAllBuckets();if(0===c.length)return i.success=!1,i.errors.push({bucket:"all",error:"No taste packages found in project"}),i;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){i.success=!1;const n=formatValidationIssues({result:t,verbose:!0});i.errors.push({bucket:e.category,error:`Validation failed for taste package in project:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in project has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(i.errors.length>0)return i;const l=n.length>0?c.filter(e=>n.includes(e.category)):c;if(n.length>0&&0===l.length){i.success=!1;for(const e of n)i.errors.push({bucket:e,error:"Taste package not found in project"});return i}let d,u;if("remote-project"===r||"remote-user"===r)try{const e=await getAuthenticatedEntity();e.success&&e.user?.userName&&(d=e.user.userName)}catch{}if("remote-project"===r&&0===n.length){const e=f.basename(process.cwd()),n=new bt;if(!d)return i.success=!1,i.errors.push({bucket:"all",error:"Failed to get user namespace for remote push"}),i;try{const r=await n.downloadPackage({namespace:d,packageName:e});let s="overwrite";const c="project",u=r?.type??"category",m=l.reduce((e,t)=>e+t.learnings.length,0),g=r?.files?r.files.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0):0;if(s=o?"overwrite":r?u!==c?await promptTypeMismatchStrategy({packageName:e,namespace:d,localType:c,remoteType:u,localLearningsCount:m,remoteLearningsCount:g}):await promptSameTypeStrategy({packageName:e,namespace:d,type:c,localLearningsCount:m,remoteLearningsCount:g}):"overwrite","skip"===s)return i;await n.writeBuckets({buckets:l,projectName:e,namespace:d,type:"project",isPublic:t?a:r?.isPublic??!1});for(const e of l)i.bucketsPushed.push(e.category),i.filePaths[e.category]=`${d}/${e.category}`,i.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if(r)for(const e of l)i.overwritten.push(e.category);return i}catch(e){return i.success=!1,i.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),i}}switch(r){case"local-global":u=new Et;break;case"remote-project":case"remote-user":u=new bt;break;default:return i.success=!1,i.errors.push({bucket:"all",error:`Invalid target: ${r}`}),i}for(const e of l)try{const t=await u.getBucket({category:e.category});let n;if(n=o?"overwrite":t&&"local-global"===r?await promptGlobalPushStrategy({packageName:e.category,localLearningsCount:e.learnings.length,globalBucket:t}):"merge","skip"===n)continue;if("overwrite"===n){if("local-global"===r)await u.writeBucket({bucket:e});else{if(!d)throw new Error("Failed to get user namespace for remote push");await u.writeBucket({bucket:e,namespace:d,isPublic:a})}i.bucketsPushed.push(e.category),i.overwritten.push(e.category)}else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},i.mergeDetails[e.category]=r.details}else n=e,i.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};if("local-global"===r)await u.writeBucket({bucket:n});else{if(!d)throw new Error("Failed to get user namespace for remote push");await u.writeBucket({bucket:n,namespace:d,isPublic:a})}i.bucketsPushed.push(e.category)}if("local-global"===r){const t=getCategoryTasteFile({target:"local-global",category:e.category});i.filePaths[e.category]=t}else"remote-project"!==r&&"remote-user"!==r||!d||(i.filePaths[e.category]=`${d}/${e.category}`)}catch(t){i.success=!1,i.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return i}async function pull(e){const{buckets:t,source:n,overwrite:r=!1}=e,o=new wt,a={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},s=__name(()=>{switch(n){case"local-global":return"global";case"remote-project":return"remote project";case"remote-user":return"remote";default:return"source"}},"getSourceName")();let i,c;switch(n){case"local-global":i=new Et;break;case"remote-project":case"remote-user":i=new bt;break;default:return a.success=!1,a.errors.push({bucket:"all",error:`Invalid source: ${n}`}),a}try{c=await i.getAllBuckets()}catch(e){return a.success=!1,a.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),a}if(0===c.length)return a.success=!1,a.errors.push({bucket:"all",error:`No taste packages found in ${s}`}),a;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){a.success=!1;const n=formatValidationIssues({result:t,verbose:!0});a.errors.push({bucket:e.category,error:`Validation failed for taste package in ${s}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${s} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(a.errors.length>0)return a;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){a.success=!1;for(const e of t)a.errors.push({bucket:e,error:`Taste package not found in ${s}`});return a}for(const e of l)try{const t=await o.getBucket({category:e.category});let s;if(s=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===s)continue;if("overwrite"===s)await o.writeBucket({bucket:e}),a.bucketsPulled.push(e.category),a.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},a.mergeDetails[e.category]=r.details}else n=e,a.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});a.filePaths[e.category]=i}catch(t){a.success=!1,a.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return a}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new wt,a=new bt,s={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await a.downloadPackage({namespace:t,packageName:n});if(!e)return s.success=!1,s.errors.push({bucket:n,error:"Taste package not found in remote"}),s;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){s.success=!1;const r=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:n,error:`Validation failed for ${e.file}:\n${r}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:s})}catch(e){s.success=!1,s.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return s}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(i){const e=parseTasteBuckets({content:i.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processBucket({bucket:t,namespace:r,overwrite:o,targetStorage:a,result:s})}for(const e of t){if("taste.md"===e.file)continue;const t=e.file.replace("/taste.md",""),i={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processBucket({bucket:i,namespace:r,overwrite:o,targetStorage:a,result:s})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:a}=e;try{const e=await o.getBucket({category:t.category});let s;if(s=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===s)return void a.skipped.push(t.category);if("overwrite"===s)await o.writeBucket({bucket:t}),a.bucketsPulled.push(t.category),a.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},a.mergeDetails[t.category]=r.details}else n=t,a.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),a.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});a.filePaths[t.category]=i}catch(e){a.success=!1,a.errors.push({bucket:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullCategoryPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:a,result:s}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return s.success=!1,void s.errors.push({bucket:n,error:"No taste.md file found in category package"});const c={category:n,learnings:parseTasteContent(i.content),sourcePath:`remote:${n}`};await processBucket({bucket:c,namespace:r,overwrite:o,targetStorage:a,result:s})}async function pushRemote(e){const{namespace:t,packageName:n,overwrite:r=!1,isPublic:o=!1}=e,a=new wt,s=new bt,i={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return i.success=!1,i.errors.push({bucket:n,error:"No taste directory found in project"}),i;try{const e=await a.getBucket({category:n});if(!e)return i.success=!1,i.errors.push({bucket:n,error:`Taste package '${n}' not found in local project`}),i;const c=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!c.valid){i.success=!1;const e=formatValidationIssues({result:c,verbose:!0});return i.errors.push({bucket:n,error:`Validation failed:\n${e}`}),i}if(c.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${n}' has validation warnings:\n`);const e=formatValidationIssues({result:c,verbose:!0});console.warn(e+"\n")}const l=await s.downloadPackageToBucket({namespace:t,packageName:n});let d;if(d=r?"overwrite":l?await promptPushStrategy({packageName:n,namespace:t,localLearningsCount:e.learnings.length,remoteBucket:l}):"merge","skip"===d)return i;if("overwrite"===d)await s.writeBucket({bucket:e,namespace:t,isPublic:o}),i.bucketsPushed.push(n),i.overwritten.push(n);else{let r;if(l){const t=mergeLearnings({source:e.learnings,target:l.learnings});r={...e,learnings:t.merged},i.mergeDetails[n]=t.details}else r=e,i.mergeDetails[n]={added:e.learnings.length,updated:0,unchanged:0};await s.writeBucket({bucket:r,namespace:t,isPublic:o}),i.bucketsPushed.push(n)}i.filePaths[n]=`${t}/${n}`}catch(e){i.success=!1,i.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return i}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new wt;break;case"local-global":n=new Et;break;case"remote-project":case"remote-user":n=new bt;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof Et||n instanceof bt?await n.listBuckets():(await n.getAllBuckets()).map(e=>({category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}))}async function deleteBuckets(e){const{buckets:t,location:n}=e,r={success:!0,bucketsDeleted:[],errors:[]};let o;switch(n){case"local-global":o=new Et;break;case"remote-project":case"remote-user":o=new bt;break;case"local-project":return r.success=!1,r.errors.push({bucket:"all",error:"Cannot delete from local project via sync. Use taste clear instead."}),r;default:return r.success=!1,r.errors.push({bucket:"all",error:`Invalid location: ${n}`}),r}if(0===t.length)return r.success=!1,r.errors.push({bucket:"all",error:"No taste packages specified for deletion"}),r;for(const e of t)try{await o.deleteBucket({category:e}),r.bucketsDeleted.push(e)}catch(t){r.success=!1,r.errors.push({bucket:e,error:t instanceof Error?t.message:String(t)})}return r}async function lint(e){const{packages:t,target:n}=e,r={success:!0,filesLinted:[],errors:[],totalErrors:0,totalWarnings:0},o=getTastePath({target:n});if(!M(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const a=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});M(t)?a.push({path:t,displayName:`${e}/taste.md`}):(r.success=!1,r.errors.push({file:e,error:`Taste package '${e}' not found in ${"local-global"===n?"global":"project"}`}))}else{const e=getRootTasteFile({target:n});M(e)&&a.push({path:e,displayName:"taste.md"});const t=await S.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});M(t)&&a.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===a.length&&r.errors.length>0)return r;if(0===a.length)return r.success=!1,r.errors.push({file:"all",error:"No taste files found in "+("local-global"===n?"global":"project")}),r;for(const e of a){let t=await S.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await S.writeFile(e.path,n,"utf-8"),t=n);const o=validateTasteFile({content:t,filePath:e.displayName}),a=o.issues.filter(e=>"error"===e.severity),s=o.issues.filter(e=>"warning"===e.severity);r.totalErrors+=a.length,r.totalWarnings+=s.length,o.valid||(r.success=!1);const i=formatValidationIssues({result:o});r.filesLinted.push({file:e.displayName,valid:o.valid,errors:a.length,warnings:s.length,formatted:i})}return r}async function open3(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new wt;break;case"local-global":e=new Et;break;case"remote-project":case"remote-user":e=new bt;break;default:throw new Error(`Invalid target: ${n}`)}const r=(await e.getAllBuckets()).find(e=>e.category===t);if(!r)return{success:!1,error:`Taste package '${t}' not found in ${"local-global"===n?"global":"project"}`};const o=r.sourcePath,a=await findCategoryLineNumber({filePath:o,category:t});return await ne([{file:o,line:a}]),{success:!0,filePath:o,lineNumber:a}}catch(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}}async function findCategoryLineNumber(e){const{filePath:t,category:n}=e;try{const e=await S.readFile(t,"utf-8");if("taste.md"===f.basename(t)&&f.basename(f.dirname(t))===n)return 1;const r=e.split("\n");for(let e=0;e<r.length;e++)if(r[e].trim().toLowerCase()===`# ${n.toLowerCase()}`)return e+1;return 1}catch{return 1}}function getEditorSetupInstructions(){const e=re.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}async function runMigrations(){await removeMetadataFile()}async function removeMetadataFile(){const e=f.join(C.homedir(),".commandcode","taste",".metadata.json");if(M(e))try{await S.unlink(e)}catch{}}__name(validateTasteFile,"validateTasteFile"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(validateLearningLine,"validateLearningLine"),__name(buildResult,"buildResult"),__name(formatValidationIssues,"formatValidationIssues"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptPushStrategy,"promptPushStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),__name(push,"push"),__name(pull,"pull"),__name(pullRemote,"pullRemote"),__name(pullProjectPackage,"pullProjectPackage"),__name(processBucket,"processBucket"),__name(pullCategoryPackage,"pullCategoryPackage"),__name(pushRemote,"pushRemote"),__name(list,"list"),__name(deleteBuckets,"deleteBuckets"),__name(lint,"lint"),__name(open3,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var vt=class{static{__name(this,"TasteSyncManager")}constructor(){runMigrations().catch(()=>{})}async push(e){return await push(e)}async pull(e){return await pull(e)}async pullRemote(e){return await pullRemote(e)}async pushRemote(e){return await pushRemote(e)}async list(e){return await list(e)}async delete(e){return await deleteBuckets(e)}async lint(e){return await lint(e)}async open(e){return await open3(e)}};async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new pt({baseUrl:e}),n=await t.get({endpoint:De.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}}async function promptNamespaceSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],o=await s.select({message:"Select namespace to push to\n",options:r,initialValue:t});return s.isCancel(o)&&(s.cancel("Operation cancelled"),process.exit(0)),o}function createTasteCommand(){const n=new e("taste");n.description("Manage taste learning packages");const r=new vt;return n.command("push").argument("[package]","Package name (optional if using --all)").option("-g, --global","Push to global storage").option("--remote","Push to remote (default)").option("--all","Push all packages").option("--overwrite","Overwrite target without prompting (default: interactive merge)").option("--public","Make this package publicly discoverable").addOption(new t("--dev","Push to dev environment").hideHelp()).addOption(new t("--staging","Push to staging environment").hideHelp()).description("Push packages from project to remote or global storage (prompts on conflicts)").action(async(e,t)=>{try{let n;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(te.gray(" cmd taste push --all (pushes whole project)")),console.error(te.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote)if(t.all)n=await r.push({buckets:[],target:"remote-project",overwrite:t.overwrite,isPublic:t.public});else{let o,a;if(e&&e.includes("/")){const[t,n]=e.split("/");t&&n||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste push --remote username/packageName")),console.error(te.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),o=t,a=n}else{e||(console.error(te.red("Error: Please specify a package name")),console.error(te.gray("Usage: cmd taste push <namespace>/<package>")),console.error(te.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),a=e;let t;(await r.list({location:"local-project"})).some(e=>e.category===a)||(console.error(te.red(`Error: Taste package '${a}' not found in local project`)),process.exit(1));try{t=await fetchUserNamespaces()}catch(e){throw e}o=t.orgs.length>0?await promptNamespaceSelection(t):t.userName}n=await r.pushRemote({namespace:o,packageName:a,overwrite:t.overwrite,isPublic:t.public})}else{const o="local-global",a=t.all?[]:[e];n=await r.push({buckets:a,target:o,overwrite:t.overwrite})}if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}let o=!1;if(1===n.bucketsPushed.length){const e=n.bucketsPushed[0],r=n.filePaths?.[e];if(t.overwrite)t.remote&&r?console.log(te.green(`✓ Replaced '${e}' taste package in ${r}`)):(console.log(te.green(`✓ Replaced '${e}' taste package in global`)),r&&console.log(te.gray(` Path: ${r}`)));else if(n.mergeDetails?.[e]){const a=n.mergeDetails[e],s=[];a.added>0&&s.push(`${a.added} ${1===a.added?"learning":"learnings"} added`),a.updated>0&&s.push(`${a.updated} ${1===a.updated?"learning":"learnings"} updated`),a.unchanged>0&&s.push(`${a.unchanged} ${1===a.unchanged?"learning":"learnings"} unchanged`),t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r} (${s.join(", ")})`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global (${s.join(", ")})`)),r&&console.log(te.gray(` Path: ${r}`))),(a.added>0||a.updated>0)&&a.unchanged>0&&(o=!0)}else t.remote&&r?console.log(te.green(`✓ Pushed '${e}' taste package to ${r}`)):(console.log(te.green(`✓ Pushed '${e}' taste package to global`)),r&&console.log(te.gray(` Path: ${r}`)))}else if(n.bucketsPushed.length>0){const e=t.remote?"remote":"global";if(console.log(te.green(`✓ Pushed ${n.bucketsPushed.length} taste packages (${n.bucketsPushed.join(", ")}) to ${e}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){o=!0;break}}o&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,t)=>{try{let n,o;if(t.global||t.remote||(t.remote=!0),t.global&&t.remote&&(console.error(te.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),t.remote&&t.all&&(console.error(te.red("Error: The --all flag is not supported for remote pull")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),t.remote&&!e&&(console.error(te.red("Error: Please provide both namespace and package name")),process.exit(1)),t.remote&&e&&!e.includes("/")&&(console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(te.gray(" cmd taste pull <package> -g (from global)")),console.error(te.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1)),t.remote){e.includes("/")||(console.error(te.red("Error: Package name must include namespace")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[a,s]=e.split("/");a&&s||(console.error(te.red("Error: Invalid namespace/package format")),console.error(te.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),o=a,n=await r.pullRemote({namespace:o,packageName:s,overwrite:t.overwrite})}else{const o="local-global",a=t.all?[]:[e];n=await r.pull({buckets:a,source:o,overwrite:t.overwrite})}const a=t.remote?o?`${o}`:"remote":"global";if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}if(n.skipped&&n.skipped.length>0)for(const e of n.skipped)console.log(te.yellow(`⊘ Skipped '${e}' - kept local version`));let s=!1;if(1===n.bucketsPulled.length){const e=n.bucketsPulled[0],r=n.filePaths?.[e];if(t.overwrite)console.log(te.green(`✓ Replaced '${e}' taste package in project`)),r&&console.log(te.gray(` Saved to: ${r}`));else if(n.mergeDetails?.[e]){const t=n.mergeDetails[e],o=[];t.added>0&&o.push(`${t.added} ${1===t.added?"learning":"learnings"} added`),t.updated>0&&o.push(`${t.updated} ${1===t.updated?"learning":"learnings"} updated`),t.unchanged>0&&o.push(`${t.unchanged} ${1===t.unchanged?"learning":"learnings"} unchanged`),console.log(te.green(`✓ Pulled '${e}' taste package from ${a} (${o.join(", ")})`)),r&&console.log(te.gray(` Saved to: ${r}`)),(t.added>0||t.updated>0)&&t.unchanged>0&&(s=!0)}else console.log(te.green(`✓ Pulled '${e}' taste package from ${a}`)),r&&console.log(te.gray(` Saved to: ${r}`))}else if(n.bucketsPulled.length>0){const e=` (${n.bucketsPulled.join(", ")})`;if(console.log(te.green(`✓ Pulled ${n.bucketsPulled.length} taste packages${e} from ${a}`)),!t.overwrite&&n.mergeDetails)for(const e of Object.values(n.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){s=!0;break}}s&&console.log(te.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("list").option("-g, --global","List global packages").option("--remote","List remote packages").addOption(new t("--dev","Use dev environment").hideHelp()).addOption(new t("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let t,n;e.global&&e.remote&&(console.error(te.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(t="remote-project",n="remote"):e.global?(t="local-global",n="global"):(t="local-project",n="project");const o=await r.list({location:t});if(0===o.length)return void console.log(te.yellow(`No taste packages found in ${n}`));let a;console.log(te.hex("#E4CCFF").bold("\nTaste Packages")),a="remote-project"===t?"Stored in your commandcode.ai account":"local-global"===t?"Stored globally in ~/.commandcode/taste":"Stored locally in .commandcode/taste",console.log(te.dim(a+"\n"));let s=0;const i=__name(e=>{let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ★${e.starCount}`.length),e.downloadCount&&(t+=` ↓${e.downloadCount}`.length),t},"getDisplayLength"),c=Math.max(...o.map(i));for(const e of o){s+=e.learningCount;const t=getTimeAgo(e.lastUpdated),n=" ".repeat(c-i(e)+2),r=te.white(e.category),o=e.isPublic?te.green(" [public]"):"",a=e.isPublic&&e.starCount?te.yellow(` ★${e.starCount}`):"",l=e.downloadCount?te.gray(` ↓${e.downloadCount}`):"";console.log(` ${r}${o}${a}${l}${n}${te.dim.gray(`(${e.learningCount} learnings, updated ${t})`)}`)}console.log(te.dim(`\nTotal: ${o.length} packages, ${s} learnings\n`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("delete").argument("<package>","Package name to delete").option("-g, --global","Delete from global").description("Delete a package").action(async(e,t)=>{try{t.global||(console.error(te.red("Error: Currently only global is supported. Use -g flag.")),process.exit(1));const n=await r.delete({buckets:[e],location:"local-global"});if(!n.success){for(const e of n.errors){const t=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(te.red(`Error: ${t}`))}process.exit(1)}console.log(te.green(`✓ Deleted '${e}' taste package from global`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("lint").argument("[package]","Package name (required unless using --all)").option("-g, --global","Lint global taste files").option("--all","Lint all packages").description("Validate taste file format and structure").action(async(e,t)=>{try{e||t.all||(console.error(te.red("Error: Please specify a package name or use --all flag")),console.error(te.gray("Usage: cmd taste lint <package>")),console.error(te.gray(" cmd taste lint --all")),process.exit(1)),e&&t.all&&(console.error(te.red("Error: Cannot use both package name and --all flag")),process.exit(1));const n=await r.lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(te.red(`Error: ${e.error}`));process.exit(1)}for(const e of n.filesLinted)console.log(e.formatted);if(n.filesLinted.length>1)if(console.log(""),0===n.totalErrors&&0===n.totalWarnings)console.log(te.green(`✓ All ${n.filesLinted.length} taste files are valid`));else{const e=[];n.totalErrors>0&&e.push(te.red(`${n.totalErrors} error${n.totalErrors>1?"s":""}`)),n.totalWarnings>0&&e.push(te.yellow(`${n.totalWarnings} warning${n.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${n.filesLinted.length} files`)}n.success||process.exit(1)}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,t)=>{try{const n=t.global?"local-global":"local-project",o=await r.open({package:e,target:n});o.success||(console.error(te.red(o.error)),process.exit(1)),console.log(te.green(`✓ Opened '${e}' taste package from ${t.global?"global":"project"}`))}catch(e){console.error(te.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),n}function getTimeAgo(e){const t=(new Date).getTime()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}function getPackageJson(){const e=import.meta.url,t=ae(e),n=w(t);return JSON.parse(N(E(n,"./../package.json"),"utf8"))}__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(promptNamespaceSelection,"promptNamespaceSelection"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),__name(getPackageJson,"getPackageJson");var Ct=getPackageJson(),Tt=y.join(T.homedir(),".commandcode"),St=y.join(Tt,"update-status.json"),Pt=y.join(Tt,"update-failed.json");function ensureCommandCodeDir(){R.existsSync(Tt)||R.mkdirSync(Tt,{recursive:!0})}async function checkForUpdateAvailable(){try{const e=n("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3}),t=JSON.parse(e),r=Ct.version,o=r.includes("alpha"),a=t.filter(e=>!e.includes("alpha")),s=t.filter(e=>e.includes("alpha"));let i=r,c=!1;if(a.length>0){const e=a.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}if(!c&&o&&s.length>0){const e=s.sort(oe.rcompare)[0];oe.gt(e,r)&&(i=e,c=!0)}return{currentVersion:r,latestVersion:i,updateAvailable:c}}catch(e){return null}}async function performAutoUpdate(e){const{silent:t=!1,updateInfo:r,onProgress:o}=e||{},a=r||await checkForUpdateAvailable();if(!a||!a.updateAvailable)return{success:!1};o?.(`Updating to v${a.latestVersion}...`);try{n(`npm i -g command-code@${a.latestVersion}`,{stdio:"ignore",env:{...process.env,NODE_NO_WARNINGS:"1"}}),ensureCommandCodeDir();const e={updatedFrom:a.currentVersion,updatedTo:a.latestVersion,updatedAt:Date.now()};return R.writeFileSync(St,JSON.stringify(e,null,2)),{success:!0}}catch(e){console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code"),ensureCommandCodeDir();const t={currentVersion:a.currentVersion,latestVersion:a.latestVersion,failedAt:Date.now()};return R.writeFileSync(Pt,JSON.stringify(t,null,2)),{success:!1,updateInfo:a}}}function getUpdateStatus(){try{if(ensureCommandCodeDir(),R.existsSync(St)){const e=JSON.parse(R.readFileSync(St,"utf-8"));return R.unlinkSync(St),e}}catch(e){}return null}function getFailedUpdateInfo(){try{if(ensureCommandCodeDir(),R.existsSync(Pt)){const e=JSON.parse(R.readFileSync(Pt,"utf-8"));return R.unlinkSync(Pt),{currentVersion:e.currentVersion,latestVersion:e.latestVersion}}}catch(e){}return null}__name(ensureCommandCodeDir,"ensureCommandCodeDir"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(performAutoUpdate,"performAutoUpdate"),__name(getUpdateStatus,"getUpdateStatus"),__name(getFailedUpdateInfo,"getFailedUpdateInfo");var At=new e("update").description("Update Command Code to the latest version").option("--check","Check for updates without installing").action(async e=>{if(e.check){console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));e.updateAvailable?(console.log(te.bold("Update available!")),console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd update")+te.dim(" to install."))):console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`))}else{console.log(te.dim("Checking for updates..."));const e=await checkForUpdateAvailable();if(!e)return console.log(te.red("✗ Failed to check for updates")),void console.log(te.dim("Please check your internet connection or try again later."));if(!e.updateAvailable)return void console.log(te.green("✓ Already on latest version ")+te.dim(`(${e.currentVersion})`));console.log(te.dim("Current: ")+te.white(e.currentVersion)),console.log(te.dim("Latest: ")+te.bold.green(e.latestVersion)),console.log(te.dim(`\nUpdating command-code from ${e.currentVersion} → `)+te.white(e.latestVersion)+te.dim("...")),(await performAutoUpdate({silent:!0,updateInfo:e})).success?(console.log(te.green("\n✓ Successfully updated to ")+te.bold(e.latestVersion)),console.log(te.dim("Run ")+te.cyan("cmd")+te.dim(" to start using the new version."))):(console.log(te.red("✗ Update failed")),console.log(te.dim("Please try updating manually:")),console.log(te.cyan("npm i -g command-code")),process.exit(1))}}),xt=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:o=process.cwd(),env:a=process.env}=t;return new Promise(t=>{const s=r("/bin/bash",["-c",e],{cwd:o,env:{...a},stdio:["pipe","pipe","pipe"]});let i="",c="",l=null;n>0&&(l=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:i,stderr:c+(c?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{i+=e.toString()}),s.stderr?.on("data",e=>{c+=e.toString()}),s.on("close",n=>{l&&clearTimeout(l),t({stdout:i.trim(),stderr:c.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{l&&clearTimeout(l),t({stdout:i,stderr:c+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),$t=__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"),It="read_file",Dt="edit_file",Ft="write_file",Rt="read_directory",Mt="read_multiple_files",Nt="grep",jt="shell_command",Ot="think",Lt="todo_write",_t="web_search",Ut="web_fetch",Bt=__name(e=>e===_t,"isWebSearchTool");function toRelativePath(e){const t=global.COMMAND_CODE_CWD||process.cwd(),n=process.env.HOME||process.env.USERPROFILE||"",r=f.relative(t,e);return r.startsWith("..")?n&&e.startsWith(n)?e.replace(n,"~"):e:""===r?f.basename(e):r}function replacePathsInText(e){if(!e||"string"!=typeof e)return e;let t=e;return t=t.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,e=>f.isAbsolute(e)?toRelativePath(e):e),t=t.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),t}__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var Wt=D.object({id:D.string(),timestamp:D.number(),type:D.literal("image"),source:D.object({type:D.enum(["base64","url"]),media_type:D.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:D.string()})}),zt=D.object({id:D.string(),timestamp:D.number(),input:D.string(),output:D.string().optional(),metadata:D.record(D.string(),D.any()).optional(),images:D.array(Wt).optional().default([])}),Gt=zt.extend({role:D.literal("user")}),Ht=zt.extend({role:D.literal("assistant")}),Vt=zt.extend({role:D.literal("tool"),name:D.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),qt=zt.extend({role:D.literal("bash"),command:D.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),Kt=zt.extend({role:D.literal("system")}),Jt=zt.extend({role:D.literal("error")}),Yt=zt.extend({role:D.literal("info")}),Zt=D.discriminatedUnion("role",[Gt,Ht,Vt,qt,Kt,Jt,Yt]),Xt=__name((e,t)=>Zt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),Qt=__name(e=>Zt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),en=__name(e=>Zt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),tn=__name((e,t,n)=>Zt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),nn=__name(e=>Zt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),rn=__name(e=>Zt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),on=__name(e=>Zt.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),an=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return Zt.parse(n)},"updateEntryWithOutput"),sn=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),cn=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),ln=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),dn=["Thinking…","Yapping…","Yawning…","Brewing…","Contemplating…","Conjuring…","Pondering…","Mixing…","Stirring…","Channeling…","Sculpting…","Crystallizing…","Spinning…","Tuning…","Sparking…","Revving…","Cruising…","Exploring…","Blazing…","Climbing…","Diving…","Surfing…","Riding…","Dancing…","Juggling…","Performing…","Casting…","Cooking…","Baking…","Seasoning…","Garnishing…","Vibing…","Chilling…","Grooving…","Jamming…","Swaying…","Bouncing…","Flowing…","Gliding…","Floating…","Drifting…","Wandering…","Meandering…","Strolling…","Skipping…","Hopping…","Leaping…","Soaring…","Glowing…","Shimmering…","Twinkling…","Flickering…","Pulsing…","Humming…","Buzzing…","Whirring…","Purring…","Chirping…","Whistling…","Giggling…","Snickering…","Chuckling…","Grinning…","Smirking…","Winking…","Nodding…","Stretching…","Flexing…","Wiggling…","Swirling…","Twirling…","Spiraling…","Weaving…","Bobbing…","Rocking…","Swinging…","Swooshing…","Zipping…","Zooming…","Whizzing…","Zapping…","Popping…","Snapping…","Crackling…","Sizzling…","Bubbling…","Fizzing…"],un=__name(()=>dn[Math.floor(Math.random()*dn.length)],"getRandomLLMStatus"),mn=__name(e=>{switch(e){case It:return"Read";case Dt:return"Edit";case Ft:return"Write";case Rt:return"List";case Mt:return"Read Multiple";case Nt:return"Search";case jt:return"Shell";case Lt:return"Todos";case Ot:return"Thinking…";case _t:return"Web Search";case Ut:return"Web Fetch";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),gn=__name((e,t)=>{try{switch(e){case It:case Ft:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case Dt:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Rt:return toRelativePath(t.path||"directory");case Nt:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case jt: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 Lt:return`${t.todos?t.todos.length:0} items`;case Ot:return t.content||"planning";case Mt:const r=t.include||[];return Array.isArray(r)?r.join(", "):"multiple files";case _t:return t.query||"search";case Ut:return t.url||"fetch";default:const o=t?.messages||[];if(Array.isArray(o)&&o.length>0&&o[0]&&"object"==typeof o[0]&&"content"in o[0]){const e=o[0].content;if("string"==typeof e)return e.slice(0,50)+(e.length>50?"...":"")}return JSON.stringify(t||{})}}catch{return"parameters"}},"getToolInputContent"),pn=__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"),hn=__name(()=>{const[e,t]=B({isExecuting:!1,currentCommand:null});return{executeBash:H(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await xt(e,{timeout:3e4,cwd:process.cwd()}),o=$t(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]=an(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]=an(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),fn=D.object({name:D.string().min(1,"Skill name is required").max(64,"Skill name must be 64 characters or less").regex(/^[a-z0-9-]+$/,"Skill name must contain only lowercase letters, numbers, and hyphens").refine(e=>!e.startsWith("-")&&!e.endsWith("-"),"Skill name cannot start or end with a hyphen").refine(e=>!e.includes("--"),"Skill name cannot contain consecutive hyphens"),description:D.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:D.string().optional(),compatibility:D.array(D.string()).optional(),metadata:D.record(D.string(),D.any()).optional(),"allowed-tools":D.array(D.string()).optional()});function getPersonalSkillsDir(){return y.join(T.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return y.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:t}=e;try{await P.access(t);const e=(await P.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory());return(await Promise.all(e.map(async e=>{try{const n=y.join(t,e.name,"SKILL.md");await P.access(n);const r=await P.readFile(n,"utf-8"),{data:o}=se(r),a=fn.parse(o);return{name:a.name,description:a.description,filePath:n}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getPersonalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{personal:e,project:t}}function escapeXML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function generateSkillsXML(e){const{personal:t,project:n}=e,r=[...t,...n];return 0===r.length?"":`<available_skills>\n${r.map(e=>{const t=y.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(t)}\n</location>\n</skill>`}).join("\n")}\n</available_skills>`}function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}D.object({name:D.string(),description:D.string(),license:D.string().optional(),compatibility:D.array(D.string()).optional(),metadata:D.record(D.string(),D.any()).optional(),"allowed-tools":D.array(D.string()).optional(),content:D.string(),filePath:D.string()}),D.object({name:D.string(),description:D.string(),filePath:D.string()}),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var yn=D.object({absolutePath:D.string().describe("The absolute path to the file to read"),offset:D.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:D.number().optional().describe("Optional number of lines to read")});D.object({content:D.union([D.string(),D.instanceof(Buffer)]),contentType:D.enum(["text","binary"]),fileType:D.string(),size:D.number(),linesRead:D.number().optional()});var wn=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}};async function readFileContent(e){const{absolutePath:t,offset:n,limit:r}=e;if(!f.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new wn("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=f.normalize(t);try{await S.access(o,F.constants.F_OK|F.constants.R_OK)}catch{throw new wn(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await S.stat(o)).isFile())throw new wn("Path does not point to a file","NOT_A_FILE");const a=getFileType(o),s=isBinaryFile(a);if(void 0!==n&&void 0===r||void 0===n&&void 0!==r)throw new wn("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new wn("Offset must be >= 0","INVALID_OFFSET");if(void 0!==r&&r<=0)throw new wn("Limit must be > 0","INVALID_LIMIT");try{if(s){const e=await S.readFile(o);return{fileType:a,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==r){const e=await readTextFileLines(o,n,r);return{fileType:a,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await S.readFile(o,"utf8");return{content:e,fileType:a,contentType:"text",size:e.length}}}catch(e){if(e instanceof wn)throw e;throw new wn(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var En={".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(e){const t=f.extname(e).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",...En}[t]||"unknown"}function isBinaryFile(e){return Object.values(En).includes(e)}async function readTextFileLines(e,t,n){const r=(await S.readFile(e,"utf8")).split(/\r?\n/),o=t,a=Math.min(o+n,r.length),s=r.slice(o,a);return{content:s.join("\n"),linesRead:s.length}}async function processFileReferences(e){const t=[];let n=e;const r=[...e.matchAll(/@([^\s@]+)/g)];for(const e of r){const r=e[0],o=e[1];try{const e=f.isAbsolute(o)?o:f.resolve(process.cwd(),o),a=await readFileContent({absolutePath:e});if("binary"===a.contentType)continue;const s=String(a.content),i=f.relative(process.cwd(),e),c=1e5;if(s.length>c){t.push({token:r,resolvedPath:e,content:"",tooLarge:!0});const o=`${i}`;n=n.replace(r,o);continue}t.push({token:r,resolvedPath:e,content:s});const l=`{${i}: ${s}}`;n=n.replace(r,l)}catch(e){continue}}return{displayContent:e,processedContent:n,fileReferences:t}}function reconstructContent(e,t){let n=e;for(const e of t){const t=`{${f.relative(process.cwd(),e.resolvedPath)}: ${e.content}}`;n=n.replace(e.token,t)}return n}function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent"),__name(formatOutput,"formatOutput");var bn={name:"read_file",description:"Reads the contents of a file from the local filesystem, handling both text and binary files appropriately. \nThis tool automatically detects the file type based on extension and processes it accordingly - text files are returned as readable strings while binary files return metadata about the file type and size. \nFor large text files, you can optionally read specific line ranges using the offset and limit parameters to avoid loading the entire file into memory. \nThe tool validates that the provided path is absolute and that the file exists and is readable before attempting to read it. \nIt should be used when you need to examine file contents, verify file existence, or extract specific portions of text files for analysis or processing.",input_schema:{type:"object",properties:{absolutePath:{type:"string",description:'The absolute path to the file to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). Relative paths like "./file.txt" or "../file.txt" are not accepted. The file must exist and be readable by the current process.'},offset:{type:"number",description:"The line number to start reading from (0-based index, where 0 is the first line). This parameter must be used together with the limit parameter for reading specific line ranges. Cannot be negative. Use this when you need to read a specific section of a large file without loading the entire content."},limit:{type:"number",description:"The maximum number of lines to read starting from the offset. Must be a positive integer and used together with the offset parameter. This helps manage memory usage when dealing with large files by reading only the necessary portion."}},required:["absolutePath"]},execute:__name(async e=>{try{const t=yn.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading file`}},"execute")},kn=D.object({filePath:D.string().describe("The absolute path to the file to edit"),oldValue:D.string().describe("The text to replace"),newValue:D.string().describe("The new text to insert"),replacementCount:D.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:D.boolean().optional().describe("Whether to replace all occurrences (default: false)")});D.object({path:D.string(),replacementsCount:D.number(),oldContent:D.string(),newContent:D.string()}),D.object({name:D.string(),message:D.string(),code:D.string().optional()});var vn=D.object({backupFileName:D.string().nullable(),version:D.number().int().positive(),backupTime:D.string().datetime()}),Cn=D.object({messageId:D.string().uuid(),trackedFileBackups:D.record(D.string(),vn),timestamp:D.string().datetime()});D.object({type:D.literal("file-history-snapshot"),messageId:D.string().uuid(),snapshot:Cn,isSnapshotUpdate:D.boolean()}),D.object({maxFileSize:D.number().int().positive().default(10485760),retentionDays:D.number().int().positive().default(30)});var Tn=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`${$.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 y.join(T.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:t}=e;return y.join(getCommandCodeBasePath(),"file-history",t)}function getBackupFilePath(e){const{sessionId:t,backupFileName:n}=e;return y.join(getFileHistoryPath({sessionId:t}),n)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await P.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 P.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await P.writeFile(r,n);const e=await P.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 P.rename(r,t)}catch(e){try{await P.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await P.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await P.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function truncateString(e){const{text:t,maxLength:n}=e;return t.length<=n?t:n<=3?t.slice(0,n):t.slice(0,n-3)+"..."}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),a=Math.floor(o/60),s=Math.floor(a/24);return s>0?`${s}d ago`:a>0?`${a}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:t}=e;return y.basename(t)}function isWithinRetentionPeriod(e){const{timestamp:t,retentionDays:n}=e,r=new Date(t).getTime();return Date.now()-r<=24*n*60*60*1e3}__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(truncateString,"truncateString"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod");var Sn={maxFileSize:10485760,retentionDays:30},Pn=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Sn,...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 P.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const a=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:a,content:e});const s={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,s),this.trackedState.versions.set(t,n),{success:!0,backup:s,skipped:!1}}catch(e){return{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 P.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r}))throw new Tn(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");const o=await P.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 P.access(t,P.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 P.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await P.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await P.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}},An=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new Pn({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,maxLength:100}))}const o=Object.keys(n.trackedFileBackups);let a=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(a={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:a})}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,a=0,s=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{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?a++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(s=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:a,messagesRemoved:s}}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}},xn=null;function initializeCheckpointService(e){const{sessionId:t}=e;return xn=new An({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return xn?xn.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(e){const{filePath:t,oldValue:n,newValue:r,replaceAll:o=!1,replacementCount:a=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!f.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!n)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==r)throw createFileEditError("newValue is required","INVALID_INPUT");if(!o&&a<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await j.access(t,O.F_OK|O.R_OK|O.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let s;try{const e=await readFileContent({absolutePath:t});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");s=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 i=(s.match(new RegExp(escapeRegExp(n),"g"))||[]).length;if(0===i)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let c,l;if(o)c=i;else if(c=a,c>i)throw createFileEditError(`Expected ${c} replacements, but only found ${i} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||c===i)l=s.split(n).join(r),d=i;else{l=s;for(let e=0;e<c;e++){const e=l.indexOf(n);-1!==e&&(l=l.substring(0,e)+r+l.substring(e+n.length),d++)}}if(0===d)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:t}),await j.writeFile(t,l,"utf-8"),{path:t,replacementsCount:d,oldContent:s,newContent:l}}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"),__name(formatOutput2,"formatOutput");var $n={name:"edit_file",description:"Performs precise text replacements in files by finding and replacing exact string matches, similar to a str_replace operation.\nThis tool is designed for making targeted edits to text files, allowing you to replace specific occurrences of text with new content while preserving the rest of the file unchanged.\nIt validates that the file exists, is accessible, and is a text file (not binary) before attempting any modifications, ensuring data integrity.\nThe tool can replace a single occurrence, a specific number of occurrences, or all occurrences of the target text based on your requirements.\nIt should be used when you need to fix typos, update variable names, modify configuration values, or make any other precise text changes in code or text files.\nThe tool will report the exact number of replacements made and will fail safely if the target text is not found or if multiple matches exist when expecting a unique match.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path to the file to edit. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The file must exist and have write permissions. Binary files cannot be edited with this tool."},oldValue:{type:"string",description:"The exact text string to search for in the file. This must match exactly including whitespace, indentation, and line breaks. The match is case-sensitive. If multiple matches exist and replaceAll is false, only the first occurrence from the beginning of the file will be replaced."},newValue:{type:"string",description:"The replacement text that will be inserted in place of each matched occurrence of oldValue. Can be an empty string to effectively delete the matched text. Preserves any surrounding whitespace and formatting."},replaceAll:{type:"boolean",description:"When true, replaces all occurrences of oldValue in the file. When false (default), replaces only the number of occurrences specified by replacementCount. Use true when you need to update all instances, such as renaming a variable throughout a file."},replacementCount:{type:"number",description:"The number of occurrences to replace when replaceAll is false. Default is 1. Must be a positive integer. If set higher than the actual number of occurrences, the tool will report an error. Use this for controlled, partial replacements."}},required:["filePath","oldValue","newValue"]},execute:__name(async e=>{try{const t=kn.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while editing file`}},"execute")},In=D.object({path:D.string().describe("The absolute path to the directory to read"),exclude:D.array(D.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:D.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});D.object({files:D.array(D.string()),directories:D.array(D.string())});var Dn=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}};async function readDirectory(e){const{path:t,exclude:n=[],respectGitIgnore:r=!1}=e;if(!f.isAbsolute(t))throw new Dn("Path must be absolute, not relative","INVALID_PATH");try{if(!(await S.stat(t)).isDirectory())throw new Dn("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Dn)throw e;throw new Dn(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await S.readdir(t);let o=[];r&&(o=await loadGitIgnorePatterns(t));const a=[...n,...o],s=[],i=[];for(const n of e){if(shouldIgnoreEntry(n,a))continue;const e=f.join(t,n);try{const t=await S.stat(e);t.isDirectory()?i.push(n):t.isFile()&&s.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:s.sort(),directories:i.sort()}}catch(e){if(e instanceof Dn)throw e;throw new Dn(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(e){const t=[];try{if(!await isInGitRepository(e))return t;let n=f.resolve(e);const r=await findGitRoot(e);for(;n&&isWithinGitRoot(n,r);){const e=f.join(n,".gitignore");try{const n=(await S.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const r=f.dirname(n);if(r===n)break;n=r}}catch(e){}return t}async function isInGitRepository(e){try{return null!==await findGitRoot(e)}catch{return!1}}async function findGitRoot(e){let t=f.resolve(e);for(;;){try{const e=f.join(t,".git");if((await S.stat(e)).isDirectory())return t}catch{}const e=f.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=f.resolve(e),r=f.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(ie(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")}__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry"),__name(formatOutput3,"formatOutput");var Fn={name:"read_directory",description:"Lists the contents of a directory, providing separate arrays of files and subdirectories found at the specified path.\nThis tool is essential for exploring project structure, discovering available files, and understanding directory organization before performing operations on specific files.\nIt automatically respects .gitignore patterns by default when operating within git repositories, ensuring you don't see files that are intentionally excluded from version control.\nThe tool supports custom exclusion patterns using glob syntax, allowing you to filter out specific files or directories based on your needs, such as build artifacts or temporary files.\nResults are always sorted alphabetically for consistent output, making it easier to locate specific items in large directories.\nIt should be used when you need to explore a directory's contents, verify file existence, or understand project structure before performing file operations.",input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the directory to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The directory must exist and be accessible. Returns an error if the path points to a file instead of a directory."},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude from results. Uses minimatch syntax for pattern matching. Examples: ["*.log", "temp*", "**/*.tmp"] would exclude all log files, anything starting with "temp", and all .tmp files in any subdirectory. Patterns are applied in addition to any .gitignore rules.'}},required:["path"]},execute:__name(async e=>{try{const t=In.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading directory`}},"execute")},Rn=D.object({filePath:D.string().describe("The absolute path where the file should be written"),content:D.string().describe("The content to write to the file")});async function writeFile5({filePath:e,content:t}){if(!k(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=w(e);return M(n)||await A(n,{recursive:!0}),await backupFileBeforeEdit({filePath:e}),await x(e,t,"utf-8"),{path:e,bytesWritten:Buffer.byteLength(t,"utf-8")}}catch(t){const n=t instanceof Error?t.message:"Unknown error occurred";throw new Error(`Failed to write file '${e}': ${n}`)}}function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}D.object({success:D.boolean(),message:D.string(),path:D.string().optional()}),__name(writeFile5,"writeFile"),__name(formatOutput4,"formatOutput");var Mn={name:"write_file",description:"Creates or overwrites a file with the specified content at the given absolute path, automatically creating any necessary parent directories.\nThis tool handles the complete file writing process, including directory creation, making it ideal for generating new files, saving processed output, or creating configuration files.\nIf the file already exists, it will be completely overwritten with the new content - the previous contents will be lost, so use with caution on existing files.\nThe tool automatically creates any missing parent directories in the path, eliminating the need to manually ensure directory structure exists before writing.\nIt should be used when you need to create new files, save generated content, write configuration files, or output processed data to the filesystem.\nAll content is written as UTF-8 encoded text, making it suitable for source code, configuration files, documentation, and other text-based formats.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path where the file should be written. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). If parent directories do not exist, they will be created automatically. Existing files at this path will be overwritten without warning."},content:{type:"string",description:"The text content to write to the file. Can be any UTF-8 string including multi-line text, JSON, XML, source code, or any other text format. Empty strings are valid and will create an empty file. Line endings are preserved as provided."}},required:["filePath","content"]},execute:__name(async e=>{try{const t=Rn.parse(e),n=await writeFile5(t);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")},Nn=D.object({include:D.array(D.string()).describe("Array of glob patterns to include files"),exclude:D.array(D.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:D.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:D.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:D.string().optional().describe("Base directory for relative paths. Default: current working directory")}),jn=D.object({filePath:D.string(),content:D.string(),fileType:D.string(),size:D.number()});D.object({content:D.string(),filesRead:D.array(D.string()),errors:D.array(D.object({file:D.string(),error:D.string()})),fileDetails:D.array(jn)});var On=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},Ln=["**/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 a of e)try{(await ce(a,{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 "${a}": ${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:t,exclude:n=[],gitIgnore:r=!0,defaultExclude:o=!0,targetDirectory:a=process.cwd()}=e;if(!t||0===t.length)throw new On("At least one include pattern must be provided","NO_PATTERNS");const s=y.resolve(a),i={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...Ln);const a=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:s});for(const e of a)try{const t=y.resolve(s,e),n=await readFileContent({absolutePath:t}),r=processFileResult({content:n,filePath:e});i.fileDetails.push(r),i.content+=`\n// File: ${e} (${n.fileType})\n`,i.content+=r.content,i.content+="\n",i.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);i.errors.push({file:e,error:n}),i.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return i}catch(e){if(e instanceof On)throw e;throw new On(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getReadSummary(e){return{totalFiles:e.fileDetails.length,successfulReads:e.filesRead.length,failedReads:e.errors.length,totalSize:e.fileDetails.reduce((e,t)=>e+t.size,0),fileTypesCounts:e.fileDetails.reduce((e,t)=>(e[t.fileType]=(e[t.fileType]||0)+1,e),{}),contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];return n.push(`Read ${t.successfulReads}/${t.totalFiles} files (${t.totalSize} bytes)`),e.errors.length>0&&(n.push("\nErrors:"),e.errors.forEach(e=>n.push(` - ${e.file}: ${e.error}`))),n.push("\n--- File Contents ---"),n.push(e.content),n.join("\n")}__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles"),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput");var _n={name:"read_multiple_files",description:"Reads multiple files simultaneously based on glob patterns, returning their contents concatenated with clear file headers for easy identification.\nThis tool is designed for bulk file operations, such as analyzing all source files in a project, reviewing multiple configuration files, or processing sets of related documents.\nIt automatically excludes common non-source directories like node_modules and build folders by default, and respects .gitignore patterns to avoid processing files that shouldn't be analyzed.\nThe tool handles both text and binary files appropriately - text files have their content included while binary files are noted with their type and size information.\nEach file's content is clearly separated with a header showing the file path and type, making it easy to distinguish between different files in the concatenated output.\nIt should be used when you need to analyze multiple files at once, search across multiple files for patterns, or gather content from various sources for processing or review.\nThe tool provides detailed feedback including which files were successfully read, any errors encountered, and statistics about the operation.",input_schema:{type:"object",properties:{include:{type:"array",items:{type:"string"},description:'Array of glob patterns to match files for reading. Uses standard glob syntax with support for wildcards (* for single level, ** for recursive). Examples: ["**/*.ts"] matches all TypeScript files, ["src/**/*.js", "lib/**/*.js"] matches JavaScript files in src and lib directories. At least one pattern must be provided.'},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude files from reading. Applied after include patterns. Examples: ["**/*.test.ts", "**/*.spec.js"] excludes test files, ["**/generated/**"] excludes generated directories. These patterns are additive with default exclusions and .gitignore rules.'},defaultExclude:{type:"boolean",description:"Whether to apply default exclusions for common non-source directories and files. Default is true. When enabled, automatically excludes: node_modules, dist, build, .git, coverage, tmp, temp, .DS_Store, *.log, *.tmp, *.cache, and other common build artifacts. Set to false to read all matching files regardless of common conventions."},gitIgnore:{type:"boolean",description:"Whether to respect .gitignore files when matching patterns. Default is true. When enabled, any files or directories listed in .gitignore files will be excluded from results. Useful for avoiding generated files, secrets, or other intentionally untracked files. Set to false to include all files matching your patterns."},targetDirectory:{type:"string",description:"The base directory from which to resolve glob patterns. Default is the current working directory. Must be an absolute path. All include and exclude patterns will be resolved relative to this directory. Use this to scope your file search to a specific part of the filesystem."}},required:["include"]},execute:__name(async e=>{try{const t=Nn.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while reading multiple files`}},"execute")},Un=D.object({pattern:D.string().min(1,"Pattern is required"),include:D.array(D.string()).optional(),directory:D.string().optional()});function execCommand({args:e,command:t}){return new Promise((n,o)=>{const a=r(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",i="";a.stdout?.on("data",e=>{s+=e.toString()}),a.stderr?.on("data",e=>{i+=e.toString()}),a.on("close",e=>{0===e?n(s):1!==e||i?o(new Error(i||`Command failed with exit code ${e}`)):n("")}),a.on("error",e=>{o(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(a){if(!(a instanceof Error&&a.message.includes("ENOENT")))throw a;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 a=e.trim().split("\n"),s=[];for(const e of a){const t=parseGrepLine(e);t&&s.push(t)}return s}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),__name(formatGrepResults,"formatGrepResults");var Bn={name:"grep",description:"Searches for text patterns across files in a directory using regular expressions, providing powerful pattern matching capabilities for code analysis, debugging, and content discovery.\nThis tool performs recursive searches through directory structures, examining file contents to find all occurrences of the specified pattern, making it ideal for locating specific code implementations, finding TODO comments, searching for function usage, or identifying configuration values.\nThe search uses Perl-compatible regular expressions (PCRE), supporting advanced patterns including lookaheads, lookbehinds, character classes, and quantifiers, with results showing file paths and line numbers for each match.\nFile filtering can be applied using glob patterns to search only specific file types, improving performance and relevance by focusing on the files that matter for your search.\nIt should be used when you need to find where something is defined or used in a codebase, locate specific text patterns across multiple files, verify the presence of certain code patterns, or analyze code structure and dependencies.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'The regular expression pattern to search for in file contents. Supports full PCRE syntax including special characters (\\d, \\w, \\s), quantifiers (*, +, ?, {n,m}), anchors (^, $), and groups. Special regex characters like ., *, [, ], (, ), {, }, |, \\, ^, $ must be escaped with backslash when matching literally. Examples: "TODO.*urgent" finds TODO comments marked urgent, "function\\s+\\w+\\(" finds function definitions, "import.*from.*react" finds React imports.'},include:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to filter which files to search. Only files matching at least one pattern will be searched. Supports standard glob syntax: * matches any characters except /, ** matches any characters including /, ? matches single character, [abc] matches character set. Examples: ["*.ts", "*.tsx"] searches TypeScript files, ["src/**/*.js"] searches JavaScript files in src directory, ["*.{js,jsx,ts,tsx}"] searches all JavaScript/TypeScript files. If omitted, searches all files except those in .gitignore.'},directory:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=Un.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while searching files`}},"execute")},Wn=D.object({pattern:D.string().min(1,"Pattern is required"),path:D.string().optional()}),zn=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:t,path:n="."}=e;if(!t)throw new zn("Pattern parameter is required","INVALID_PATTERN");try{const e=y.resolve(process.cwd(),n),r=process.cwd(),o=r.endsWith(y.sep)?r:r+y.sep;if(e!==r&&!e.startsWith(o))throw new zn("Search path must be within the current working directory","INVALID_PATH");const a=await ce(t,{cwd:e,ignore:Le,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),s=await Promise.all(a.map(async t=>{const n=y.join(e,t);try{return{file:t,mtime:(await P.stat(n)).mtimeMs}}catch{return{file:t,mtime:0}}}));return s.sort((e,t)=>t.mtime-e.mtime),{files:s.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof zn)throw e;if(e instanceof Error)throw new zn(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new zn("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")}__name(globSearch,"globSearch"),__name(formatGlobResults,"formatGlobResults");var Gn={name:"glob",description:"Searches for files in a directory tree using glob-style path patterns, enabling fast and flexible discovery of files across codebases of any size.\nThis tool matches file paths against glob patterns such as **/*.js or src/**/*.ts, making it ideal for locating files by name, extension, or directory structure without inspecting file contents. It performs recursive traversal where applicable and efficiently handles large repositories.\nResults are returned as a list of matching file paths, sorted by modification time, allowing you to quickly identify the most recently changed or relevant files.\nFile pattern matching can be refined using inclusive or exclusive glob expressions to narrow down results, improving performance and focus when working with large or complex projects.\nIt should be used when you need to find files based on naming or path patterns, explore the structure of an unfamiliar codebase, locate configuration or entry-point files, or prepare a targeted set of files for further inspection with tools like grep.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files. Supports wildcards: * matches any characters except /, ** matches any characters including / (for recursive search), ? matches single character, [abc] matches character set, {js,ts} matches alternatives. Examples: "**/*.ts" finds all TypeScript files recursively, "src/**/*.{js,jsx}" finds JavaScript files in src directory, "*.json" finds JSON files in current directory, "**/test/**/*.spec.ts" finds test spec files.'},path:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=Wn.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${o.cross} Error: ${e.message}`:`${o.cross} Error: Unknown error occurred while finding files`}},"execute")},Hn=D.object({command:D.string().min(1,"Command cannot be empty"),args:D.array(D.string()).optional(),directory:D.string().optional(),timeout:D.number().optional()}),Vn=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,a,s){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=a,this.duration=s}};async function executeShellCommand(e){const{command:t,args:n=[],directory:o,timeout:a=3e4}=e,s=Date.now();if(!t.trim())throw new Vn("Command cannot be empty","EMPTY_COMMAND");let i;if(o){if(f.isAbsolute(o))throw new Vn("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");i=f.resolve(process.cwd(),o)}else i=process.cwd();try{if(!(await P.stat(i)).isDirectory())throw new Vn(`Path is not a directory: ${o}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof Vn)throw e;throw new Vn(`Directory does not exist or is not accessible: ${o||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:i,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((o,i)=>{let c="",l="",d=!1;const u=n.length>0?le([t,...n]):t,m=setTimeout(()=>{if(!d){g.kill("SIGTERM");const e=Date.now()-s;i(new Vn(`Command timed out after ${a}ms`,"TIMEOUT",null,"SIGTERM",c,l,e))}},a),g=r(u,[],e);g.stdout?.on("data",e=>{c+=e.toString()}),g.stderr?.on("data",e=>{l+=e.toString()}),g.on("close",(e,t)=>{d=!0,clearTimeout(m);const n=Date.now()-s;0===e?o({stdout:c.trim(),stderr:l.trim(),exitCode:e,signal:t,duration:n}):i(new Vn(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,c.trim(),l.trim(),n))}),g.on("error",e=>{d=!0,clearTimeout(m);const t=Date.now()-s;i(new Vn(`Failed to start command: ${e.message}`,"START_FAILED",null,null,c.trim(),l.trim(),t))})})}catch(e){if(e instanceof Vn)throw e;throw new Vn(`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")}__name(executeShellCommand,"executeShellCommand"),__name(formatShellCommandResult,"formatShellCommandResult");var qn={name:"shell_command",description:"Executes shell commands in a controlled environment with comprehensive output capture, timeout protection, and working directory management, enabling system operations, build processes, and tool integrations.\nThis tool spawns commands as child processes with full control over execution environment, capturing both standard output and error streams while monitoring exit codes and signals, making it ideal for running build scripts, executing CLI tools, performing system operations, or integrating with external programs.\nCommands run with shell interpretation enabled for cross-platform compatibility, supporting pipes, redirections, and shell built-ins, with automatic timeout termination to prevent hanging processes from blocking execution.\nThe tool provides detailed execution results including stdout, stderr, exit codes, and execution duration, helping diagnose issues and verify successful completion of operations.\nIt should be used when you need to run build or test commands, execute system utilities, interact with CLI tools, perform file operations that require shell commands, or integrate with external programs and scripts.\nImportant: Commands execute with the permissions of the current process. Be cautious with commands that modify the filesystem or system state. Always validate and sanitize any user-provided input before including it in commands.",input_schema:{type:"object",properties:{command:{type:"string",description:'The shell command to execute. Can be any valid shell command available in the system PATH or built-in shell commands. Common commands include: "npm" for Node.js packages, "git" for version control, "ls"/"dir" for listing files, "echo" for output, "cat"/"type" for file contents. The command string is passed to the system shell (sh on Unix, cmd.exe on Windows). Special characters should be properly escaped. Cannot be empty.'},args:{type:"array",items:{type:"string"},description:'Optional array of arguments to pass to the command. Each argument is passed as a separate string and is automatically escaped for shell safety. Use this instead of including arguments in the command string for better security and cross-platform compatibility. Examples: ["install", "--save-dev", "typescript"] for npm, ["status", "--short"] for git, ["-la", "/usr"] for ls. Arguments containing spaces or special characters are automatically quoted.'},directory:{type:"string",description:'Optional working directory where the command should be executed, specified as a relative path from the current working directory. Must be a relative path (absolute paths are not allowed for security). The directory must exist and be accessible. Examples: "src" runs in src folder, "packages/core" runs in packages/core, "../sibling" runs in sibling directory. If omitted, uses the current working directory. Useful for running commands that depend on specific file locations or configurations.'},timeout:{type:"number",description:"Optional maximum time in milliseconds to wait for the command to complete before forcibly terminating it. Must be between 100 and 300000 (5 minutes). Defaults to 30000ms (30 seconds). The command process is killed with SIGTERM if it exceeds this duration. Useful for preventing long-running or hanging processes. Set higher for operations known to take time (builds, installs), lower for quick operations. Examples: 5000 for quick commands, 60000 for npm install, 120000 for large builds."}},required:["command"]},execute:__name(async e=>{try{const t=Hn.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${o.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${o.cross} Error: ${e.message}`}return`${o.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var Kn={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)}__name(todoWrite,"todoWrite");var Jn={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};function getRootAgentDir(){return y.join(T.homedir(),".commandcode","agents")}function getLocalAgentDir(){return y.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,t){try{const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=se(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,systemPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,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(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents");var Yn=2e5;function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.max(0,Math.ceil(t-n))}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>25e3}function getOversizedOutputError(e,t){return`Error: Output too large (${e.toLocaleString()} tokens, max ${25e3.toLocaleString()}). Try using grep or ripgrep with more specific patterns to filter results.`}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?getOversizedOutputError(estimateTokens(e)):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 getEnterpriseMemoryPath(){switch(C.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return f.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const e=C.homedir();return f.join(e,".commandcode","AGENTS.md")}function getProjectMemoryPaths(e){return[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:M(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(M(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:M(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return M(e)?await S.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}async function processImports(e,t,n=0,r=5){if(n>=r)return e;const o=[],a=e.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),s=Array.from(a.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let i=a;for(const e of s){const o=e[1];let a=o;o.startsWith("~/")?a=f.join(C.homedir(),o.slice(2)):f.isAbsolute(o)||(a=f.resolve(f.dirname(t),o));const s=await loadMemoryFile(a);if(s){const t=await processImports(s,a,n+1,r);i=i.replace(e[0],`\n# Imported from ${o}\n${t}\n`)}}return i=i.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>o[parseInt(t)]),i}async function loadAllMemories(e,t){const n=new Map,r=getEnterpriseMemoryPath();if(M(r)){const e=await loadMemoryFile(r);if(e){const t=await processImports(e,r);n.set(r,t)}}const o=getUserMemoryPath();if(M(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);n.set(o,t)}}const a=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of a)if(M(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}if(t&&t.length>0)for(const r of t){const t=f.isAbsolute(r)?f.dirname(r):f.dirname(f.resolve(e,r));if(t.startsWith(e)&&t!==e){const r=[];let o=t;for(;o.startsWith(e)&&o!==e;)r.push(o),o=f.dirname(o);for(const e of r.reverse()){const t=[f.join(e,"AGENTS.md"),f.join(e,".commandcode","AGENTS.md")];for(const e of t)if(M(e)&&!n.has(e)){const t=await loadMemoryFile(e);if(t){const r=await processImports(t,e);n.set(e,r)}break}}}}return n}async function openInEditor(e){const t=process.env.EDITOR||process.env.VISUAL||"code",n=f.dirname(e);return M(n)||await S.mkdir(n,{recursive:!0}),M(e)||await S.writeFile(e,"# AGENTS.md\n\n","utf-8"),new Promise((n,o)=>{const a=r(t,[e],{stdio:"inherit",shell:!0});a.on("exit",e=>{0===e?n():o(new Error(`Editor exited with code ${e}`))}),a.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),o(e)})})}async function initProjectMemory(e){const t=f.join(e,"AGENTS.md");return M(t)||await S.writeFile(t,"# 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"),t}async function getMemoryContent(e){try{const t=process.cwd(),n=await loadAllMemories(t,e);if(0===n.size)return null;const r=[],o=getEnterpriseMemoryPath(),a=getUserMemoryPath(),s=[f.join(t,"AGENTS.md"),f.join(t,".commandcode","AGENTS.md")];n.has(o)&&r.push(`# Memory from: ${o}\n\n${n.get(o)}`),n.has(a)&&r.push(`# Memory from: ${a}\n\n${n.get(a)}`);for(const e of s)if(n.has(e)){r.push(`# Memory from: ${e}\n\n${n.get(e)}`);break}for(const[e,t]of n)e===o||e===a||s.includes(e)||r.push(`# Memory from: ${e}\n\n${t}`);return r.join("\n\n---\n\n")}catch(e){return null}}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__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");var Zn=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return y.join(T.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return ue(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=y.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=y.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=n("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await P.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await P.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),o={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await P.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 t=e||this.sessionId,n=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.readFile(n,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading messages:",e),[]}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n&&t.push({id:o,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)t.push({id:o,timestamp:r,role:"assistant",input:e.content,images:[]});else if(Array.isArray(e.content)){for(const r of e.content)if("text"===r.type)n+=r.text;else if("tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=gn(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}else if("server_tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=gn(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}n.trim()&&t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]})}}}return t}async loadSession(e){const t=e||this.sessionId,n=y.join(this.projectPath,`${t}.jsonl`);try{const e=(await P.readFile(n,"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(),t=_SessionManager.getCurrentProjectDirName(),n=y.join(e,t);try{return(await P.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=y.join(e,t);try{return await P.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=y.join(_SessionManager.getProjectsBasePath(),e);try{try{await P.access(t)}catch{return[]}const e=(await P.readdir(t)).filter(e=>e.endsWith(".jsonl")),n=[];for(const r of e){const e=r.replace(".jsonl",""),o=y.join(t,r);try{const r=await P.stat(o),a=(await P.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(a.length>0){let o="",s="";const i=JSON.parse(a[0]);i.gitBranch&&(s=i.gitBranch);for(const e of a){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}n.push({id:e,createdAt:r.birthtime.toISOString(),lastModified:r.mtime.toISOString(),firstMessage:o||"No messages",messageCount:a.length,projectPath:t,gitBranch:s||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return n.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 t=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await P.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=y.join(this.projectPath,`${this.sessionId}.share.json`);try{await P.unlink(e)}catch(e){}}getCheckpointsFilePath(){return y.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 P.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 a=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await P.writeFile(r,a)}else await P.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 P.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 P.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 a=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await P.writeFile(r,a)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return await this.saveMessages(r),r}},Xn=new Te("AgentExecutor");function agentToTool(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;return{name:e.name,description:e.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object"}}},required:["messages"]},execute:__name(async(t,s)=>{let i=getAvailableTools(e,{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a});if(s?.onFeedUpdate){const n=gn(e.name,t),r={id:`${e.name}-tool-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Running..."};s.onFeedUpdate(r)}const c=await getConfiguredProvider(),l=await isOAuthEnforced();let d;c===Me&&(d=await _e.getValidAccessToken(),validateOAuthToken({token:d,provider:c}));const u=getApiBaseUrl(),m=new pt({baseUrl:u});let g=0;const p=[];if(Array.isArray(t?.messages)&&t?.messages.length>0)for(const e of t.messages)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&p.push({role:"user",content:t})}const h={stream:!0,messages:p,max_tokens:64e3,system:e.systemPrompt,temperature:.3,tools:i,model:`anthropic:${getConfiguredModel()}`},y=await isTasteLearningEnabled(),w={[$e]:Zn.getCurrentProjectDirName(),[Ie]:y.toString(),[Ae]:l.toString()};d&&(w[xe]=`Bearer ${d}`);const E=getEnvironmentContext(),b=await getMemoryContent([]),k=crypto.randomUUID();let v="",C=!0;for(;C;){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");if(0===g&&p.length>0){const e=p[p.length-1];g=estimateTokens(e)}const e=await callAPIWithRetry({request:m,body:{mode:"custom-agent",config:E,memory:b,threadId:k,params:{...h,messages:p}},headers:w,abortSignal:s?.abortSignal,onTextDelta:__name(e=>{g+=estimateTokens(e)},"onTextDelta")}),t=e.content.filter(e=>"tool_use"===e.type);if(v=e.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(e,s):e.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===t.length){const t=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);t.length>0&&p.push({role:"assistant",content:t}),C=!1;break}const n=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);n.length>0&&p.push({role:"assistant",content:n});const r=[],o=new Set;let a=!1;for(const e of t){if(s?.abortSignal?.aborted)throw new Error("Interrupted by user");let t=e.input;try{if(["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&s?.onPermissionRequest&&!await s.onPermissionRequest(e.name,t)){Xn.debug(`Permission denied for tool: ${e.name}`),a=!0;break}if("object"==typeof t&&null!==t){const n={...t};let r=!1;const o=["path","file_path","absolutePath","filePath","directory","folder"];for(const e of o)if(e in n&&"string"==typeof n[e]){const t=n[e];if(!f.isAbsolute(t)){const o=f.resolve(process.cwd(),t);n[e]=o,r=!0,Xn.debug(`Converted '${e}': '${t}' -> '${o}'`)}}"paths"in n&&Array.isArray(n.paths)&&(n.paths=n.paths.map(e=>"string"!=typeof e||f.isAbsolute(e)?e:(r=!0,f.resolve(process.cwd(),e)))),r?(t=n,Xn.debug(`Resolved input for ${e.name}: ${JSON.stringify(t,null,2)}`)):Xn.debug(`No path resolution needed for ${e.name}: ${JSON.stringify(t,null,2)}`)}if(s?.onFeedUpdate){const n=gn(e.name,t),r={id:`${e.name}-${e.id}-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:"Processing…"};s.onFeedUpdate(r)}const n=await executeTool(e.name,t,s),i=estimateTokens(n);if(g+=i,s?.abortSignal?.aborted)throw new Error("Interrupted by user");const c=checkToolOutputTokensLimit(n,e.name);if(r.push({type:"tool_result",tool_use_id:e.id,content:c}),o.add(e.id),s?.onFeedUpdate){const n=gn(e.name,t),r={id:`${e.name}-${e.id}-complete-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:c};s.onFeedUpdate(r)}Xn.debug(`Tool executed successfully: ${e.name}`)}catch(n){const a=n instanceof Error?n.message:"Unknown error";if(r.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${a}`,is_error:!0}),o.add(e.id),s?.onFeedUpdate){const n=gn(e.name,t),r={id:`${e.name}-${e.id}-error-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:n,output:`Error: ${a}`};s.onFeedUpdate(r)}Xn.error(`Tool execution failed: ${e.name} - ${a}`)}}if(a){const e=p[p.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:p.pop()}C=!1;break}const i=[...r];p.push({role:"user",content:i})}return v||"DONE"},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:a}=t;let s=[];if("*"===e.tools)s=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){const t=a[e];if(t){const e=o.get(t);if(e)s.push(e);else{const e=r.find(e=>e.name===t);e&&s.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){const e=a[t];if(e){const t=o.get(e);if(t)s.push(t);else{const t=r.find(t=>t.name===e);t&&s.push(t)}}}return s}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:a}=e;let s=null;for(let e=0;e<5;e++)try{const e=await t.post({body:n,stream:!0,endpoint:De.ALPHA.GENERATE,signal:o,headers:r}),s=de.fromReadableStream(e);a&&s.on("text",a);let i=null;s.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await s.finalMessage();if(i)throw i;return c}catch(t){if(s=t,isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Xn.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await new Promise(e=>setTimeout(e,n))}throw s||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 st&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ct||403===e?.status}function isRetryableError(e){return!!e?.message&&!!['Unexpected event order, got error before "message_start"',"API Error: Unexpected event order","Body is unusable: Body has already been read"].some(t=>e.message.includes(t))}function formatAPIError(e,t){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||t?.aborted)return new Error("Interrupted by user");if(e instanceof st&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof ct||403===e?.status)return e;if(e?.message?.startsWith("Error:"))return e;let n="Error: ";return e.message?n+="Something went wrong. Please try again or contact support if the issue persists.":e.toString?n+=e.toString():n+="Unknown error occurred",new Error(n)}function processServerToolBlocks(e,t){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let n="";for(const r of e.content)if("text"===r.type)n+=r.text;else if("server_tool_use"===r.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const e=gn(r.name,r.input),n=Bt(r.name)?"Found 10 results":"Content fetched",o={id:`${r.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:r.name,input:e,output:n};t.onFeedUpdate(o)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}__name(agentToTool,"agentToTool"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks");var Qn=new Map,er=null;function initializeAgentManager(e){er=e}async function loadAgentTools(){if(!er)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");const{personal:e,project:t}=await loadAllAgents();Qn.clear();const n=[...e,...t];for(const e of n){const t=agentToTool(e,er);Qn.set(t.name,t)}}async function getAgentTools(){return 0===Qn.size&&await loadAgentTools(),Array.from(Qn.values())}async function getAgentTool(e){return 0===Qn.size&&await loadAgentTools(),Qn.get(e)}function isPathInTasteDirectory(e){const{filePath:t,projectRoot:n}=e,r=f.join(n,".commandcode","taste"),o=f.normalize(f.resolve(n,t)),a=f.normalize(r);return o.startsWith(a)}function getTasteFileInfo(e){const t=f.normalize(f.resolve(e)),n=f.normalize(f.join(process.cwd(),".commandcode","taste")),r=f.normalize(f.join(C.homedir(),".commandcode","taste"));let o=null;if(t.startsWith(n)?o=n:t.startsWith(r)&&(o=r),!o)return{isTaste:!1};if(!t.endsWith("taste.md"))return{isTaste:!1};const a=f.relative(o,t).split(f.sep);return 1===a.length?{isTaste:!0}:2===a.length?{isTaste:!0,category:a[0]}:{isTaste:!1}}__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool"),__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");var tr=[bn,$n,Fn,Mn,_n,Bn,Gn,qn,Kn,Jn],nr=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],rr=new Map(tr.map(e=>[e.name,e]));async function executeTool(e,t,n){let r=rr.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from(rr.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: ",""))}try{return!rr.has(e)&&n?await r.execute(t,n):await r.execute(t)}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message)throw e;return e instanceof Error?`Error: ${e.message}`:"Error: Unknown error occurred"}}async function getToolSchemas(){return[...tr.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...(await getAgentTools()).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),...nr]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var or={};tr.forEach(e=>{or[e.name]=toPascalCase(e.name)}),nr.forEach(e=>{or[e.name]=toPascalCase(e.name)});var ar={};Object.entries(or).forEach(([e,t])=>{ar[t]=e}),initializeAgentManager({clientTools:tr,serverTools:nr,toolsMap:rr,displayNameToToolName:ar});var sr=class _PathSanitizer{static{__name(this,"PathSanitizer")}projectRoot;homeDir;options;constructor(e={}){this.projectRoot=e.projectRoot||process.cwd(),this.homeDir=this.getHomeDirectory(),this.options={projectRoot:this.projectRoot,useHomeShorthand:e.useHomeShorthand??!0,customReplacements:e.customReplacements||[]}}sanitizeMessage(e){if(!e)return e;const t=JSON.parse(JSON.stringify(e)),n=t.message||t;return"string"==typeof n.content?n.content=this.sanitizeText(n.content):Array.isArray(n.content)?n.content=n.content.map(e=>"text"===e.type&&"string"==typeof e.text?{...e,text:this.sanitizeText(e.text)}:"tool_use"===e.type&&e.input?{...e,input:this.sanitizeToolInput(e.input)}:e):n.content&&"object"==typeof n.content&&(n.content.input&&(n.content.input=this.sanitizeText(n.content.input)),n.content.output&&(n.content.output=this.sanitizeText(n.content.output))),t.message&&(t.message=n),t.metadata&&(t.metadata=this.sanitizeObject(t.metadata)),t}sanitizeToolInput(e){if(!e||"object"!=typeof e)return e;const t={...e},n=["absolutePath","filePath","path","file_path"];for(const e of n)t[e]&&"string"==typeof t[e]&&(t[e]=this.sanitizePath(t[e]));return t.directory&&"string"==typeof t.directory&&(t.directory=this.sanitizePath(t.directory)),t.content&&"string"==typeof t.content&&(t.content=this.sanitizeText(t.content)),t}sanitizeText(e){if(!e||"string"!=typeof e)return e;let t=e;for(const{pattern:e,replacement:n}of this.options.customReplacements)t=t.replace(e,n);return t=this.replaceAbsolutePaths(t),t}sanitizePath(e){if(!e||"string"!=typeof e)return e;if(!y.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=y.relative(this.projectRoot,e);if(!t.startsWith("../../../"))return t.startsWith("../")?t:`./${t}`}catch(e){}if(this.options.useHomeShorthand&&e.startsWith(this.homeDir))return e.replace(this.homeDir,"~");const t=y.basename(e);return y.dirname(e),this.isUserPath(e)?`<user-home>/${y.relative(this.homeDir,e)}`:`<system-path>/${t}`}replaceAbsolutePaths(e){return e.match(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g),(e=e.replace(/\/(?:Users|home)\/[^\/\s]+(?:\/[^\s]*)?/g,e=>this.sanitizePath(e))).match(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g),(e=e.replace(/[A-Za-z]:\\(?:Users\\[^\\]+(?:\\[^\\]*)*|[^\s]*)/g,e=>this.sanitizePath(e))).match(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g),e.replace(/(?:^|\s)([A-Za-z]:\\[^\s]*|\/[^\s]*)/g,(e,t)=>e.substring(0,e.length-t.length)+this.sanitizePath(t))}sanitizeObject(e){if(!e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.sanitizeObject(e));const t={};for(const[n,r]of Object.entries(e))t[n]="string"==typeof r?this.sanitizeText(r):"object"==typeof r?this.sanitizeObject(r):r;return t}isWindowsAbsolutePath(e){return/^[A-Za-z]:\\/.test(e)}isUserPath(e){return e.includes("/Users/")||e.includes("/home/")||e.includes("\\Users\\")}getHomeDirectory(){return process.env.HOME||process.env.USERPROFILE||""}static forProject(e){return new _PathSanitizer({projectRoot:e,useHomeShorthand:!0})}static sanitizeMessage(e,t){return _PathSanitizer.forProject(t).sanitizeMessage(e)}static sanitizeMessages(e,t){const n=_PathSanitizer.forProject(t);return e.map(e=>n.sanitizeMessage(e))}},ir=new class extends me{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;addEvent(e){const{type:t,message:n,details:r}=e,o={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r};this.events.unshift(o),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",o)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}};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}),a=new Map(r.map(e=>[e.text,e.confidence])),s=[],i=[],c=[];return o.forEach(e=>{const t=a.get(e.text);void 0===t?s.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:s,upgraded:i,downgraded:c}}__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings");var cr=__name((e,t)=>{},"dlog"),lr=new Te("LearningAgent"),dr=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=5;request;projectRoot;tasteDir;sessionId;constructor(e){this.request=e.request,this.sessionId=e.sessionId,this.projectRoot=e.projectRoot,this.tasteDir=f.join(e.projectRoot,".commandcode","taste")}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)this.pendingMessages=t;else if(0!==t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length){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)}}catch(e){ir.addEvent({type:"error",message:"learning pass failed",details:e instanceof Error?e.message:String(e)}),this.lastProcessedMessageIndex=t.length-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)];ir.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),a=t.length-this.lastProcessedMessageIndex-1,s=Math.max(20,a),i=Math.max(0,t.length-s),c=t.slice(i);let l=0,d=!1;cr("New messages count",a),cr("Context window size",s),cr("Sending conversation messages",c.length);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){cr(`Starting learning turn ${l+1}/${this.maxTurns}`);const e=await this.callLearningAPI({conversation:u});cr("Received response from learning API"),cr("Response content blocks",e.content.length);const t=this.extractToolCalls({content:e.content});if(cr("Extracted tool calls",t.length),t.length>0&&cr("Tool calls",t.map(e=>({name:e.name,id:e.id}))),0===t.length){cr("No tool calls found, checking for text response");const t=e.content.filter(e=>"text"===e.type);if(t.length>0){const e=t[0].text||"";cr("Text response from LLM",e.substring(0,300))}break}cr("Executing tools");const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});cr("Tools executed, learnings found?",r),r&&(d=!0),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&lr.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||ir.addEvent({type:"no_learnings",message:"no changes to taste"}),ir.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{cr(`Executing tool: ${e.name}`),this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",a="";if("write_file"===e.name||"edit_file"===e.name){cr("Tool is write/edit, will track changes");const e=t;if(a=String(e.filePath||e.file_path||""),a)try{o=await F.promises.readFile(a,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const s=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&a)try{i=await F.promises.readFile(a,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=a.replace(`${this.projectRoot}/`,"");cr("Target file path",e);const t=compareLearnings({oldText:o,newText:i});cr("Diff results",{added:t.added.length,upgraded:t.upgraded.length,downgraded:t.downgraded.length}),t.added.forEach(t=>{ir.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{ir.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{ir.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:s})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(e){const{toolName:t,input:n}=e,r={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(!r||!n[r])return;const o=String(n[r]);if(f.isAbsolute(o))throw new Error(`Security: ${t} received absolute path. Only taste-relative paths are allowed (e.g., " .commandcode/taste/cli/taste.md" or " .commandcode/taste/taste.md"). Attempted: ${o}`);const a=f.join(this.tasteDir,o);if(!f.normalize(a).startsWith(this.tasteDir))throw new Error(`Security: ${t} can only access files within .commandcode/taste/. Attempted: ${o}`)}adjustPathsForTaste(e){const{toolName:t,input:n}=e,r={...n},o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[t];if(o&&r[o]){const e=String(r[o]);let n;const a="write_file"===t||"edit_file"===t;if(f.isAbsolute(e)&&e.startsWith(this.tasteDir))if(a){if(!this.isValidTasteFilePath(e))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${e}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);n=e}else n=e;else{if(f.isAbsolute(e))throw new Error(`Invalid path: Absolute path outside taste directory: ${e}`);if(n=e.startsWith(".commandcode/taste")?e.replace(".commandcode/taste",this.tasteDir):f.join(this.tasteDir,e),a&&!this.isValidTasteFilePath(n))throw new Error(`Invalid adjusted path: ${n}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}r[o]=n}return r}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isValidTasteFilePath(e))throw new Error(`Security: Invalid taste file path. Only allowed:\n - {project}/.commandcode/taste/taste.md\n - {project}/.commandcode/taste/{category}/taste.md\nAttempted: ${e}`)}async initializeTasteDirectory(){if(!F.existsSync(this.tasteDir)){F.mkdirSync(this.tasteDir,{recursive:!0});const e=f.join(this.tasteDir,"taste.md");F.writeFileSync(e,"","utf-8")}}async reorganizeIfNeeded(){const e=f.join(this.tasteDir,"taste.md");if(!F.existsSync(e))return!1;const t=F.readFileSync(e,"utf-8"),n=this.parseCategories({content:t}).filter(e=>e.learningCount>5);if(0===n.length)return!1;let r=t;for(const e of n){const t=e.name.toLowerCase().replace(/\s+/g,"-"),n=f.join(this.tasteDir,t),o=f.join(n,"taste.md");F.mkdirSync(n,{recursive:!0}),ir.addEvent({type:"refactored",message:`moved: ${e.name} package`,details:`moved to ${t}/taste.md`});const a=`# ${e.name}\n${e.learnings.join("\n")}\n`;F.writeFileSync(o,a,"utf-8");const s=`# ${e.name}\nSee [${t}/taste.md](${t}/taste.md)\n`;r=r.replace(e.fullSection,s)}return F.writeFileSync(e,r,"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 F.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(e){const{dir:t,prefix:n}=e,r=F.readdirSync(t,{withFileTypes:!0});let o="";for(let e=0;e<r.length;e++){const a=r[e],s=e===r.length-1,i=s?"└── ":"├── ";if(a.isDirectory()){o+=`${n}${i}${a.name}/\n`;const e=n+(s?" ":"│ ");o+=await this.buildTree({dir:f.join(t,a.name),prefix:e})}else if("taste.md"===a.name){const e=(F.readFileSync(f.join(t,a.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${n}${i}${a.name} (${e} learnings)\n`}else o+=`${n}${i}${a.name}\n`}return o}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;n===Me&&(o=await _e.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const a={[$e]:Zn.getCurrentProjectDirName(),[Ae]:r.toString()};o&&(a[xe]=`Bearer ${o}`);let s=0,i=null;for(;s<=this.maxApiRetries;)try{return await this.request.post({endpoint:De.ALPHA.TASTE.LEARN,body:{conversation:t,tools:await this.getTasteTools(),model:`anthropic:${getConfiguredModel()}`,threadId:this.sessionId},headers:a})}catch(e){if(i=e instanceof Error?e:new Error(String(e)),s++,s>this.maxApiRetries)throw i;const t=2e3*Math.pow(2,s);await this.sleep({ms:t})}throw i||new Error("API call failed")}sleep(e){const{ms:t}=e;return new Promise(e=>setTimeout(e,t))}static async isInitialized(e){const{projectRoot:t}=e,n=f.join(t,".commandcode","taste");return F.existsSync(n)}};async function getTasteContent(){try{const e=process.cwd(),t=f.join(e,".commandcode","taste","taste.md");if(!M(t))return null;const n=await S.readFile(t,"utf-8"),r=n.trim();return r&&"# Taste (Continuously Learned by CommandCode.ai)"!==r&&"# Taste (Continuously Learned by CommandCode)"!==r?n:null}catch(e){return null}}__name(getTasteContent,"getTasteContent");var ur=new Te("ContextEngine"),mr=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];learningAgent;checkpointManager;constructor(e,t){const n=getApiBaseUrl();this.request=new pt({baseUrl:n}),this.callbacks=e,this.sessionManager=new Zn(t),this.learningAgent=new dr({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}createSessionStoreAdapter(){return{saveSnapshot:__name(async e=>{await this.sessionManager.saveSnapshot(e)},"saveSnapshot"),loadSnapshots:__name(async()=>this.sessionManager.loadSnapshots(),"loadSnapshots"),deleteSnapshotsAfter:__name(async e=>{await this.sessionManager.deleteSnapshotsAfter(e)},"deleteSnapshotsAfter"),getMessageAtIndex:__name(e=>this.sessionManager.getMessageAtIndex({index:e.index,messages:this.messages}),"getMessageAtIndex"),getMessageIndexById:__name(e=>this.sessionManager.getMessageIndexById({messageId:e.messageId,messages:this.messages}),"getMessageIndexById"),truncateMessagesAtIndex:__name(async e=>{const t=await this.sessionManager.truncateMessagesAtIndex({index:e.index,messages:this.messages});this.messages=t},"truncateMessagesAtIndex"),getMessageCount:__name(()=>this.sessionManager.getMessageCount({messages:this.messages}),"getMessageCount")}}setupCheckpointSessionStore(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),this.checkpointManager.runCleanup().catch(()=>{})}async interrupt(e=!1){if(this.abortController){this.abortController.abort(),this.abortController=null,ur.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)&&t.message.content.some(e=>"tool_use"===e.type)&&(this.messages.pop(),ur.debug("Removed assistant message with pending tool calls to prevent API errors")),e){this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[{type:"text",text:"Interrupted by user"}]}));const e=Xt("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>ur.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t){let n=e,r=[];try{const t=await processFileReferences(e);if(n=t.processedContent,r=t.fileReferences,r.length>0){const e=r.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}const o=Xt(e);t&&t.length>0&&(o.metadata={...o.metadata,images:t}),r&&r.length>0&&(o.metadata={...o.metadata,fileReferences:r}),this.callbacks.onFeedUpdate(o);const a=[];t&&t.length>0&&t.forEach(e=>{a.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&a.push({type:"text",text:n});const s={role:"user",content:a},i=crypto.randomUUID(),c=this.createMessageWithMeta(s,{messageId:i});return this.addMessageAndSync(c),this.checkpointManager.createSnapshot({messageId:i}).catch(e=>ur.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,o).catch(e=>ur.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent(),await this.processMessages()}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.getRawMessages();await this.learningAgent.checkAndProcess({messages:e})}catch(e){ur.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}async processMessages(){let e="";this.abortController=new AbortController;let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.updateContextUsage(o);const a=o.content.filter(e=>"tool_use"===e.type),s=o.content.filter(e=>"server_tool_use"===e.type);if(e=s.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===a.length){const t=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===s.length){const t=en(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>ur.error(`Failed to save messages: ${e}`))}if(0!==s.length&&this.sessionManager.saveMessages(this.messages).catch(e=>ur.error(`Failed to save messages: ${e}`)),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0){const t=[];for(const n of e){t.push({type:"text",text:n});const e=Xt(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>ur.error(`Failed to save messages: ${e}`)),this.triggerLearningAgent();continue}}break}const i=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(i.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:i})),e.trim()){const t=en(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:a}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=Xt(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>ur.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&ur.debug("Request interrupted or insufficient credits"),this.formatAPIError(e)}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const t=await this.sessionManager.loadMessages(e);this.messages=t,await this.loadCheckpoints();const n=this.sessionManager.reconstructFeedFromMessages(t);return ur.debug(`Loaded session ${e} with ${t.length} messages`),n}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async 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 a=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],s=n.message.role;if(e&&t>=r&&-1!==r)a.push(n);else{if("user"===s){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}a.push(n)}else a.push(n)}else if("assistant"===s){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?a.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&a.push(n)}"user"!==s&&"assistant"!==s&&(o+=estimateTokens(n.message))}}this.messages=a,await this.sessionManager.saveMessages(this.messages);const s=Math.max(0,n-o);return this.contextTokensUsed=s,this.callbacks.onContextUsageUpdate?.({current:s,limit:Yn}),{messagesRemoved:t-a.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){}}))}async syncMessageToShare(e,t){try{const n=sr.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:De.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.abortController?.signal.aborted)throw new Error("Interrupted by user")}initializeInteractionTokens(){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message)}async prepareAPICall(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(t),t===Me&&(r=await _e.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId()};ur.debug(`🔍 API Call: ${o.model}, ${this.messages.length} messages, ${e.length} tools, streaming: true`);const s=await isTasteLearningEnabled(),i={[$e]:Zn.getCurrentProjectDirName(),[Ie]:s.toString(),[Ae]:n.toString()};return r&&(i[xe]=`Bearer ${r}`),{body:a,headers:i}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++)try{const t=await this.request.post({body:e.body,stream:!0,endpoint:De.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers}),n=de.fromReadableStream(t);n.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let r=null;n.on("error",e=>{r="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const o=await n.finalMessage();if(r)throw r;return this.callbacks.onRetryUpdate?.(null),o}catch(e){if(t=e,this.isNonRetryableError(e))throw this.formatAPIError(e);if(9===n)throw this.callbacks.onRetryUpdate?.(null),this.formatAPIError(e);const r=Math.min(n,10),o=100*Math.pow(2,r),a=Math.max(o,1e3),s=Math.min(a,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await new Promise(e=>setTimeout(e,s))}throw t||new Error("Failed to get response after retries")}isNonRetryableError(e){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||this.abortController?.signal.aborted||e instanceof st&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ct||403===e?.status}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=e.message?.toLowerCase().includes("insufficient credits");if(t)return new Error("Insufficient credits");const n=e.message?.toLowerCase().includes("oauth authentication required");if(n)return e;if(e instanceof ct||403===e?.status)return e;let r="Error: ";return e.message?e.message.includes("Invalid 'Authorization' header")?r+='Authentication failed. Run "cmd login" to sign in again.':r+='Something went wrong. Type "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord.':e.toString?r+=e.toString():r+="Unknown error occurred",new Error(r)}async executeToolBlocks(e){const t=[],n=new Set;let r=!1;for(const o of e.toolBlocks){this.checkIfInterrupted();try{const e=await this.checkToolPermission(o);if(e.needsPermission&&!e.allowed){this.handlePermissionDenied(o),r=!0;break}const a=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:a}),n.add(o.id),this.showToolSuccess(o,a)}catch(e){const r=e instanceof Error?e.message:"Unknown error";t.push({type:"tool_result",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}),n.add(o.id),this.showToolError(o,r)}}return{toolResults:t,executedToolIds:n,permissionDenied:r}}async checkToolPermission(e){return["edit_file","write_file","create_file","delete_file","shell_command"].includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=await executeTool(e.name,e.input,{onPermissionRequest:this.callbacks.onPermissionRequest,abortSignal:this.abortController?.signal,onFeedUpdate:this.callbacks.onFeedUpdate});this.checkIfInterrupted();const n=checkToolOutputTokensLimit(t,e.name),r=estimateTokens(n);return this.currentInteractionTokens+=r,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),n}handlePermissionDenied(e){const t=gn(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=tn(e.name,t,n),o=an(r,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}showToolSuccess(e,t){let n="edit_file"===e.name?e.input:void 0;if("read_file"===e.name){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(n={...n||{},isTasteFile:!0,tasteCategory:e.category})}}const r={...e.input,...n?.isTasteFile?{isTasteFile:n.isTasteFile}:{},...n?.tasteCategory?{tasteCategory:n.tasteCategory}:{}},o=gn(e.name,r),a=tn(e.name,o,n),s=an(a,t);this.callbacks.onFeedUpdate(s)}showToolError(e,t){const n=gn(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=tn(e.name,n,r),a=an(o,sn(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let t="";for(const n of e.content)if("text"===n.type)t+=n.text;else if("server_tool_use"===n.type){if(t.trim()){const e=en(t.trim());this.callbacks.onFeedUpdate(e),t=""}const e=gn(n.name,n.input),r=tn(n.name,e),o=Bt(n.name)?"Found 10 results":"Content fetched",a=an(r,o);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=en(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:Yn}),this.checkAndCompactIfNeeded()}async checkAndCompactIfNeeded(){const e=Math.floor(17e4);if(this.contextTokensUsed>e){ur.debug(`Context tokens (${this.contextTokensUsed}) exceeded threshold (${e}), triggering automatic compaction`);try{const e=await this.compactConversation({preserveCurrentInteraction:!0});ur.debug(`Automatic compaction completed: removed ${e.messagesRemoved} messages, saved ${e.tokensSaved} tokens`)}catch(e){ur.error(`Failed to automatically compact conversation: ${e}`)}}}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 a=await this.checkpointManager.restore({messageId:t,mode:n});return!a.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Yn})),a}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}},gr=new he;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=G(()=>{if(!e)return"";try{const t=gr.parse(e);return"string"!=typeof t?e:t.trim()}catch{return e}},[e]);return U.createElement(K,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return U.createElement(q,null,U.createElement(K,null,a.nodejs),U.createElement(q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},U.createElement(Markdown,null,e)))}gr.setOptions({renderer:new fe({strong:te.bold,em:te.italic,del:te.strikethrough,codespan:te.yellow,code:te.yellow,heading:te.bold.underline,firstHeading:te.bold.underline,link:te.cyan,href:te.cyan.underline,blockquote:te.gray.italic,listitem:te.reset,table:te.reset,hr:te.reset,paragraph:te.reset,html:te.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0}),__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var pr={"Interrupted by user":"Interrupted by user","Insufficient credits":Ue};function UserMessage({content:e}){const t="Interrupted by user"===e,n="Insufficient credits"===e,r=e.startsWith("Error:"),o=t||n||r;let s=o&&pr[e]||e;return U.createElement(q,{paddingX:1,backgroundColor:o?void 0:"#333333"},U.createElement(K,{color:o?"red":"#AAAAAA",bold:!o},a.pointer),U.createElement(q,{marginLeft:1},U.createElement(K,{color:o?"red":"white",wrap:"wrap"},s)))}__name(UserMessage,"UserMessage");var hr="#6B7280";function truncateToolOutputForDisplay(e){const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),n=t.split("\n");if(n.length<=1)return t;const r=n.slice(0,1).join("\n");return n.length,r}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:a=2,dimDiff:s=!1,maxLines:i}){const c=ye.diffLines(e,t);let l=0,d=0,u=0,m=0;c.forEach(e=>{e.added?(l+=e.count||1,m+=e.count||1):e.removed&&(d+=e.count||1,m+=e.count||1)});const g=[];c.forEach((e,t)=>{const n=e.value.split("\n").filter(e=>e);e.added||e.removed?n.forEach((n,r)=>{e.removed?(u++,g.push(U.createElement(q,{key:`${t}-${r}-removed`,width:"100%"},U.createElement(K,{color:"gray",dimColor:s},u.toString().padStart(3)," "),U.createElement(q,{backgroundColor:"#712F37"},U.createElement(K,{dimColor:s},"-"),U.createElement(K,{dimColor:s}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(U.createElement(q,{key:`${t}-${r}-added`,width:"100%"},U.createElement(K,{color:"gray",dimColor:s},u.toString().padStart(3)," "),U.createElement(q,{backgroundColor:"#325B30"},U.createElement(K,{dimColor:s},"+"),U.createElement(K,{dimColor:s}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:U.createElement(q,{flexDirection:"column"},o&&!r&&U.createElement(K,{color:"gray"},"Updated"," ",U.createElement(K,{color:"white",bold:!0},n)," ","with ",U.createElement(K,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",U.createElement(K,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&U.createElement(K,{color:"red"},"Rejected update to",U.createElement(K,{color:"red"},` ${n}`)),U.createElement(q,{flexDirection:"column",marginLeft:a},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=pn(e);return t?U.createElement(q,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?"☒":"☐";let r,o=!1;switch(e.status){case"completed":r="#22C55E",o=!0;break;case"in_progress":r="#E4CCFF";break;default:r="white"}return U.createElement(q,{key:e.id||t,flexDirection:"row"},U.createElement(q,{width:2},U.createElement(K,{color:r},n)),U.createElement(K,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):U.createElement(K,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:i=!1}){const c="Thinking…"===e,l="Todos"===e,d="Edit"===e,u=!0===s?.isTasteFile,m=s?.tasteCategory,g=!0===s?.permissionDenied,p=!c&&t&&!u,h=!c&&!l&&!u,{name:f}=detectTerminal(),y="iTerm2"===f?"shift":"ctrl";let w,E;if(r)w="yellow",E="→";else if(o)w="red",E=a.nodejs;else if(c)w=hr,E="✻";else if(l&&n){const e=pn(n),t=e?.every(e=>"completed"===e.status);w=t?"#22C55E":"#D4A017",E=a.nodejs}else w="#22C55E",E=a.nodejs;return U.createElement(q,null,c&&U.createElement(K,{color:w},E),U.createElement(q,{flexDirection:"column",marginLeft:c?1:0},U.createElement(q,null,c?U.createElement(U.Fragment,null,U.createElement(K,{color:hr},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!i&&U.createElement(K,{dimColor:!0},"(",`${y}+o to expand`,")")):u?U.createElement(U.Fragment,null,U.createElement(K,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),U.createElement(K,null," ","Using your taste ",m?"package of ":"packages",m&&U.createElement(K,{bold:!0},m))):U.createElement(K,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),p&&U.createElement(K,null," ",U.createElement(Markdown,null,`(${t})`))),n&&!u&&U.createElement(q,{columnGap:1,marginLeft:h?1:0},h&&U.createElement(K,null,"⎿"," "),l?formatTodosForDisplay(n):c?i?U.createElement(q,{width:"100%",flexDirection:"column"},U.createElement(K,null," "),U.createElement(K,{color:hr,wrap:"wrap",italic:!0},n)):null:d&&s?.oldValue&&s?.newValue?U.createElement(q,{flexDirection:"column"},(()=>{const e=i?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:g,permissionDenied:g,maxLines:e});return U.createElement(U.Fragment,null,n,r&&U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"… (",o-10," more lines) (",`${y}+o to expand`,")")))})(),g&&n&&U.createElement(q,{marginTop:1},U.createElement(K,{color:"red",wrap:"wrap"},n))):U.createElement(q,{width:"100%"},U.createElement(K,{color:o?"red":"",wrap:"wrap"},i?n:U.createElement(U.Fragment,null,truncateToolOutputForDisplay(n),n.includes("\n")&&U.createElement(K,{dimColor:!0}," ","(",`${y}+o to expand`,")"))))),r&&U.createElement(q,{columnGap:1,marginLeft:1},U.createElement(K,null,"⎿"," "),U.createElement(K,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,a;return n?(o="yellow",a="→"):r?(o="red",a="✗"):(o="green",a="✓"),U.createElement(q,null,U.createElement(K,{color:o},a),U.createElement(q,{flexDirection:"column",marginLeft:1},U.createElement(q,null,U.createElement(K,{color:"gray"},"$ "),U.createElement(K,{color:o,bold:!0},e)),U.createElement(q,{columnGap:1,marginLeft:1},U.createElement(K,null,"⎿"," "),U.createElement(K,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}function loadCustomCommands(){const e=[],t=y.join(process.cwd(),".commandcode","commands"),n=y.join(T.homedir(),".commandcode","commands");function loadCommandsFromDirectory(t,n,r=""){if(R.existsSync(t))try{const o=R.readdirSync(t,{withFileTypes:!0});for(const a of o){const o=y.join(t,a.name);if(a.isDirectory())loadCommandsFromDirectory(o,n,r?`${r}/${a.name}`:a.name);else if(a.isFile()&&a.name.endsWith(".md")){const t=y.basename(a.name,".md"),s=R.readFileSync(o,"utf-8").trim();e.push({name:t,source:n,content:s,subdirectory:r})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(n,"user"),loadCommandsFromDirectory(t,"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(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage"),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent");var fr=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.COMPACT="/compact",e.REWIND="/rewind",e))(fr||{}),yr=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"}];function truncateText(e){const{text:t,maxWidth:n}=e;return t.length<=n?t:n<=3?t.substring(0,n):t.substring(0,n-3)+"..."}__name(truncateText,"truncateText");var wr=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=B(0),[a,s]=B(0),{stdout:i}=Y(),c=i?.columns??80,l=Math.max(20,c-12-2-1-2),d=G(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...isInternalFlagPresent()?yr:yr.filter(e=>"/provider"!==e.command)];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),u=G(()=>{const e=a,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,a]);return W(()=>{o(0),s(0)},[n]),J((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<a&&s(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=a+8&&s(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?U.createElement(q,{flexDirection:"column",paddingLeft:2},U.createElement(K,{color:"dim"},"No commands found")):(d.length,U.createElement(q,{flexDirection:"column",paddingLeft:1},U.createElement(q,{columnGap:2},U.createElement(q,{flexDirection:"column",width:12},u.map((e,t)=>{const n=a+t;return U.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),U.createElement(q,{flexDirection:"column"},u.map((e,t)=>{const n=a+t;return U.createElement(K,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateText({text:e.description,maxWidth:l}))})))))},"CommandMenu");function HelpMessage(){const e=yr.filter(e=>"/help"!==e.command&&"/provider"!==e.command),t=Math.max(...e.map(e=>e.command.length))+2;return U.createElement(q,{flexDirection:"column",paddingY:1},U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(q,null,U.createElement(K,{bold:!0},"Command Code"),U.createElement(K,{color:"gray"}," v","0.9.6")),U.createElement(K,{color:"gray"},"Coding agent that continuously learns your taste of writing code.")),U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{bold:!0},"KEYBOARD SHORTCUTS"),U.createElement(q,{flexDirection:"column",paddingLeft:2,marginTop:1},U.createElement(q,null,U.createElement(K,null,"Shift+Tab".padEnd(15)),U.createElement(K,{color:"gray"},"Toggle auto-accept mode")),U.createElement(q,null,U.createElement(K,null,"Ctrl+T".padEnd(15)),U.createElement(K,{color:"gray"},"Toggle learning feed")),U.createElement(q,null,U.createElement(K,null,"Ctrl+O".padEnd(15)),U.createElement(K,{color:"gray"},"Toggle expanded tool output (Shift+O in iTerm2)")),U.createElement(q,null,U.createElement(K,null,"Esc Esc".padEnd(15)),U.createElement(K,{color:"gray"},"Rewind to previous checkpoint")),U.createElement(q,null,U.createElement(K,null,"/".padEnd(15)),U.createElement(K,{color:"gray"},"Open command menu")))),U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{bold:!0},"COMMANDS"),U.createElement(q,{flexDirection:"column",paddingLeft:2,marginTop:1},e.map(e=>U.createElement(q,{key:e.command},U.createElement(K,null,e.command.padEnd(t)),U.createElement(K,{color:"gray"},e.description))))),U.createElement(q,{flexDirection:"column"},U.createElement(K,{bold:!0},"LINKS"),U.createElement(q,{flexDirection:"column",paddingLeft:2,marginTop:1},U.createElement(q,null,U.createElement(K,null,"Documentation".padEnd(25)),U.createElement(K,{color:"cyan"},"https://commandcode.ai/docs")),U.createElement(q,null,U.createElement(K,null,"Discord Community".padEnd(25)),U.createElement(K,{color:"cyan"},"https://commandcode.ai/discord")))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?U.createElement(HelpMessage,null):U.createElement(q,{flexDirection:"column"},U.createElement(K,{wrap:"wrap"},U.createElement(Markdown,null,e)))}function getTerminalWidth(){return process.stdout.columns||80}__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(getTerminalWidth,"getTerminalWidth");var Er=__name(()=>{const e=getTerminalWidth();return e>=70?" \n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":e>=50?"\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n":br},"getResponsiveCommandLogo"),br="⌘ CMD\n";function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return U.createElement(q,null,U.createElement(K,{color:"red"},t?a.pointer:a.warning),U.createElement(q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},U.createElement(Markdown,{color:"red"},e)))}function InfoMessage({content:e}){return U.createElement(q,null,U.createElement(K,{dimColor:!0},a.info),U.createElement(q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},U.createElement(Markdown,{dimColor:!0},e)))}function getModelShortName(e){const t=Object.values(Ne).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet")?"sonnet-4.5":e.includes("opus")?"opus-4.5":"sonnet-4.5"}__name(ErrorMessage,"ErrorMessage"),__name(InfoMessage,"InfoMessage"),__name(getModelShortName,"getModelShortName");var kr=U.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const a=t?["header",...e]:e,s=Er();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~");return U.createElement(V,{items:a,key:n,style:{width:"100%"}},e=>{if("header"===e)return U.createElement(q,{key:"header",marginBottom:1,flexDirection:"column"},U.createElement(pe,{name:"vice"},U.createElement(K,null,s.trimEnd())),U.createElement(q,{flexDirection:"column",marginTop:1},U.createElement(q,null,U.createElement(K,{color:"gray"},"# "),U.createElement(K,{bold:!0},"Command Code"),U.createElement(K,{color:"gray"}," v",i)),U.createElement(K,{color:"gray"},"# models: ",c," · ","taste-1"),U.createElement(K,{color:"gray"},"# ",u)));const t=e,n=(()=>{switch(t.role){case"user":return U.createElement(UserMessage,{content:t.input});case"assistant":return U.createElement(AssistantMessage,{content:t.input});case"tool":return U.createElement(ToolMessage,{name:mn(t.name||""),input:t.input,output:t.output||"",isPending:ln(t),hasError:cn(t),metadata:t.metadata,expandedOutput:r});case"bash":return U.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:ln(t),hasError:cn(t)});case"system":return U.createElement(SystemMessage,{content:t.input});case"info":return U.createElement(InfoMessage,{content:t.input});case"error":return U.createElement(ErrorMessage,{content:t.input});default:return U.createElement(U.Fragment,null)}})();return U.createElement(q,{key:t.id,marginBottom:1,width:"90%"},n)})}),vr=__name(({messages:e})=>0===e.length?null:U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(q,{marginBottom:0},U.createElement(K,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>U.createElement(q,{key:t},U.createElement(K,{dimColor:!0},a.pointerSmall," "),U.createElement(K,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages"),Cr=["·","○","◇","☆","✧","☆","◇","○","⌘"],Tr=[8,5,4,4,4,4,4,5,20],Sr=[5,4,4,4,4,4,5],Pr=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Tr.length;e++)if(n+=Tr[e],t<n)return Cr[e];const r=t-58;n=0;for(let e=0;e<Sr.length;e++)if(n+=Sr[e],r<n)return Cr[7-e];return Cr[0]},"getWaveSymbol"),Ar=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=B(0);W(()=>{const t=setInterval(()=>{n(t=>(t+1)%(e.length+10))},50);return()=>clearInterval(t)},[e.length]);const r=__name(e=>{const n=e-(t-5);return n>=0&&n<Ar.length?Ar[n]:"#B799E6"},"getCharColor");return U.createElement(K,null,e.split("").map((e,t)=>U.createElement(K,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=B(0);return W(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),U.createElement(K,{color:"#E4CCFF",bold:!0},Pr(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var xr=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,a]=B(0),s=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}W(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),o=e>0?t:-t,s=setInterval(()=>{a(e=>{const t=e+o;return o>0&&t>=n||o<0&&t<=n?n:t})},30);return()=>clearInterval(s)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime,"formatTime");const i=s>70,c=s>40&&s<=70;return U.createElement(q,{width:s,height:1,paddingLeft:0,marginLeft:0},U.createElement(CMDIcon,null),U.createElement(q,{marginRight:1},U.createElement(ShimmerText,{text:e})),i?U.createElement(U.Fragment,null,U.createElement(q,{columnGap:1},U.createElement(K,{dimColor:!0},`(${formatTime(t)}`),U.createElement(K,{dimColor:!0},"•"),U.createElement(K,{color:"gray"},o.arrowDown),U.createElement(K,{dimColor:!0},`${formatToken(Math.round(r))}`),U.createElement(K,{dimColor:!0},"•"),U.createElement(q,{columnGap:1},U.createElement(K,{bold:!0,color:"gray"},"esc"),U.createElement(K,{dimColor:!0},"to interrupt)")))):c?U.createElement(q,{columnGap:1},U.createElement(K,{dimColor:!0},`(${formatToken(Math.round(r))})`)):U.createElement(U.Fragment,null))},"Status"),$r=__name(({usage:e})=>{if(!e)return null;const t=__name(e=>e>=1e3?`${Math.round(e/1e3)}K`:e.toString(),"formatNumber"),n=Math.min(e.current/e.limit*100,100),r=__name(e=>e>=90?"red":e>=70?"yellow":"gray","getColor");return U.createElement(q,{paddingRight:1},U.createElement(K,{color:r(n),dimColor:!0},n.toFixed(1),"% context used (",t(e.current),"/",t(e.limit),")"))},"ContextUsage");function loadGitignore(e){const t=we(),n=E(e,".gitignore");if(M(n))try{const e=N(n,"utf8");t.add(e)}catch{}return t.add(".git"),t}__name(loadGitignore,"loadGitignore");var Ir=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=B(process.cwd()),[a,s]=B([]),[i,c]=B(0),[l,d]=B(0),u=n.trim()?15:10,m=H((e,t=process.cwd())=>{if(!e.trim())return[];const n=loadGitignore(t);if(e.endsWith("/")){const r=E(t,e);try{const e=L(r),o=[];return e.forEach(e=>{const a=E(r,e);try{const e=_(a),r=b(t,a);if(n.ignores(r))return;o.push({name:r,path:a,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{}}if(e.includes("/")){const r=e.split("/"),o=r.pop()||"",a=E(t,r.join("/"));try{const e=L(a),r=[],s=o.toLowerCase();return e.forEach(e=>{const i=e.toLowerCase();if(!o||i.includes(s)){const o=E(a,e);try{const e=_(o),a=b(t,o);if(n.ignores(a))return;r.push({name:a,path:o,isDirectory:e.isDirectory()})}catch{}}}),r.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),r.slice(0,50)}catch{}}const r=[],o=e.toLowerCase(),a=__name((e,s=0)=>{if(!(s>8))try{L(e).forEach(i=>{const c=E(e,i);try{const e=_(c),l=b(t,c);if(n.ignores(l))return;const d=l.toLowerCase();(i.toLowerCase().includes(o)||d.includes(o))&&r.push({name:l,path:c,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==i&&a(c,s+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),r.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),a=n===o,s=r===o;if(a&&!s)return-1;if(!a&&s)return 1;const i=n.split("/").pop()||"",c=r.split("/").pop()||"",l=i.includes(o),d=c.includes(o);if(l&&!d)return-1;if(!l&&d)return 1;const u=e.name.split("/").length,m=t.name.split("/").length;return u!==m?u-m:e.name.localeCompare(t.name)}),r.slice(0,50)},[]),g=H(e=>{try{const t=L(e),n=[],r=process.cwd(),o=loadGitignore(r);"/"!==e&&n.push({name:"..",path:w(e),isDirectory:!0}),t.forEach(t=>{const a=E(e,t);try{const e=_(a),s=b(r,a);if(o.ignores(s))return;n.push({name:t,path:a,isDirectory:e.isDirectory()})}catch{}}),n.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s(n),c(0),d(0)}catch{}},[]);W(()=>{if(n.trim()){const e=m(n);s(e),c(0),d(0)}else g(r)},[r,g,n,m]),J((r,s)=>{if(s.escape)t();else if(s.upArrow)c(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t});else if(s.downArrow)c(e=>{const t=Math.min(a.length-1,e+1);return t>=l+u&&d(t-u+1),t});else{if(s.rightArrow){const e=a[i];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(v(e.path)))}if(s.return){const t=a[i];if(!t)return;return void e(t.path)}}});const p=a.slice(l,l+u);return U.createElement(q,{flexDirection:"column",paddingLeft:1},U.createElement(q,{marginBottom:1,flexDirection:"column"},U.createElement(K,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),U.createElement(K,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===p.length?U.createElement(K,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):p.map((e,t)=>{const n=l+t,r=e.name,o=n===i;return U.createElement(K,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),Dr=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=B([]),[o,s]=B(0),[i,c]=B(!0);W(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await Zn.listSessions();r(e.slice(0,30)),c(!1)},"loadSessions");if(J((r,a)=>{a.escape?t():a.upArrow?s(e=>Math.max(0,e-1)):a.downArrow?s(e=>Math.min(n.length-1,e+1)):a.return&&n.length>0&&o<n.length&&e(n[o].id)}),i)return U.createElement(q,{flexDirection:"column",paddingLeft:2},U.createElement(K,{color:"gray"},"Loading sessions..."));if(0===n.length)return U.createElement(q,{flexDirection:"column",paddingLeft:2},U.createElement(K,{color:"gray"},"No previous sessions found"),U.createElement(K,{color:"dim",dimColor:!0},"Press ESC to go back"));const d=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),a=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${a}d ago`},"formatRelativeTime"),u=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return U.createElement(q,{flexDirection:"column",paddingLeft:1,width:"100%"},U.createElement(K,{color:"cyan",bold:!0},"Resume Session"),U.createElement(K,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),U.createElement(q,{marginTop:1}),U.createElement(q,{columnGap:2,marginBottom:1},U.createElement(q,{width:5},U.createElement(K,{color:"gray"}," ")),U.createElement(q,{width:13},U.createElement(K,{color:"gray"},"Modified")),U.createElement(q,{width:20},U.createElement(K,{color:"gray"},"Git Branch")),U.createElement(q,{width:11},U.createElement(K,{color:"gray"},"# Messages")),U.createElement(q,null,U.createElement(K,{color:"gray"},"Summary"))),U.createElement(q,{columnGap:2},U.createElement(q,{flexDirection:"column",width:5},n.map((e,t)=>U.createElement(K,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${a.pointer} ${t+1}.`:` ${t+1}.`))),U.createElement(q,{flexDirection:"column",width:13},n.map((e,t)=>U.createElement(K,{key:`mod-${e.id}`,color:o===t?"white":"gray"},d(e.lastModified)))),U.createElement(q,{flexDirection:"column",width:20},n.map((e,t)=>U.createElement(K,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),U.createElement(q,{flexDirection:"column",width:11},n.map((e,t)=>U.createElement(K,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),U.createElement(q,{flexDirection:"column"},n.map((e,t)=>U.createElement(K,{key:`summary-${e.id}`,color:o===t?"white":"gray"},u(e.firstMessage))))))},"SessionsResumeTable"),Fr=__name(()=>U.createElement(q,{flexDirection:"column",paddingLeft:1},U.createElement(K,{color:"dim",bold:!0},"Available Shortcuts:"),U.createElement(q,{columnGap:4},U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"dim"},"! for bash mode"),U.createElement(K,{color:"dim"},"/ for commands"),U.createElement(K,{color:"dim"},"@ for file paths"),U.createElement(K,{color:"dim"},"shift + tab to toggle auto-accept")),U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"dim"},"double tap esc to clear input"),U.createElement(K,{color:"dim"},"shift + ⏎ for newline"),U.createElement(K,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Rr=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:g=!1,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:y,updateStatus:w,updateFailedInfo:E,currentProvider:k,showProviderInfo:v,isOAuthMode:C=!1,autoAcceptMode:T=!1,onToggleAutoAccept:S,hintMessage:P})=>{const[A,x]=B(0),[$,I]=B(!1),[D,F]=B(!1),[R,M]=B(!1),[N,j]=B(!1),[O,L]=B(""),[_,V]=B(!1),[Y,Z]=B(null),[X,ee]=B([]),[te,ne]=B([]),[re,oe]=B(""),[ae,se]=B(""),ie=z(!1),[ce,le]=B(!1),de=G(()=>{const t=(process.stdout.columns||80)-4,n=(e.match(/\n/g)||[]).length;return Math.ceil(Math.max(1,e.length)/t)+n},[e]),[ue,me]=B(!0),ge=z(de);W(()=>{if(de!==ge.current){me(!1);const e=setTimeout(()=>{me(!0)},0);return ge.current=de,()=>clearTimeout(e)}},[de]);const pe=H(()=>{n(""),F(!1),j(!1),L(""),V(!1),ee([]),ne([]),oe(""),le(!1),x(e=>e+1)},[n]),he=H(e=>{if(0===e.length)return e;let t=e.length;for(;t>0&&/\s/.test(e[t-1]);)t--;for(;t>0&&!/\s/.test(e[t-1]);)t--;return e.slice(0,t)},[]),fe=H(()=>{const t=he(e);n(t),x(e=>e+1)},[e,he,n]);J(async(t,r)=>{if(getIsExpandToolShortcut(r,t))return ie.current=!0,n(e),void x(e=>e+1);if(!r.ctrl&&!r.meta&&!r.shift){if(""===t)return void pe();if(""===t)return void fe()}if(r.meta&&r.delete)return ie.current=!0,void fe();if(r.meta&&r.backspace)pe();else if(r.alt&&r.backspace)fe();else{if(r.ctrl&&"w"===t)return ie.current=!0,void fe();if(r.meta&&"w"===t)return ie.current=!0,void pe();if(r.meta&&"v"===t||r.ctrl&&"v"===t){if(r.ctrl&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();if(r){const e=`[Image#${te.length+1}]`;ne(e=>[...e,r]),n(t+e),x(e=>e+1)}return void(ie.current=!0)}}else{if((r.ctrl||r.meta)&&"u"===t)return ie.current=!0,void pe();if(r.ctrl&&t)switch(t.toLowerCase()){case"k":case"a":return void pe();case"z":return M(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100)}if(r.escape){if(_)return V(!1),n(re),void x(e=>e+1);const e=Date.now(),t=500;return Y&&e-Y<t?(pe(),Z(null)):(Z(e),setTimeout(()=>Z(null),t)),I(!1),void F(!1)}$&&(r.backspace||r.delete)&&0===e.length&&I(!1)}}});const ye=H(async t=>{const r=processBracketedPaste(t);if(r.isPasteStart&&!ce){if(le(!0),se(e),!r.isPasteEnd)return;le(!1);const t=await detectClipboardImage();if(t){const r=`[Image#${te.length+1}]`;ne(e=>[...e,t]),n(e+r),x(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>300){const t=`[Text#${X.length+1}]`;ee(t=>[...t,e]),n(ae+t),x(e=>e+1)}else n(ae+e),x(e=>e+1)}return}if(ce&&!r.isPasteEnd)return;if(ce&&r.isPasteEnd){le(!1);const e=await detectClipboardImage();if(e){const t=`[Image#${te.length+1}]`;ne(t=>[...t,e]),n(r.cleanedContent+t),x(e=>e+1)}else{const e=await detectClipboardText();if(e)if(e.length>300){const t=`[Text#${X.length+1}]`;ee(t=>[...t,e]),n(ae+t),x(e=>e+1)}else n(ae+e),x(e=>e+1)}return}if(r.isPasteEnd&&!r.isPasteStart)return;if(ie.current)return void(ie.current=!1);const o=1===t.length,a=t.slice(-1);if(o){if("?"===a&&!$)return I(!0),n(""),void x(e=>e+1);if("!"===a&&!D)return I(!1),F(!0),n(""),void x(e=>e+1);"/"!==a||N||(j(!0),L(""))}if(N){const e=t.lastIndexOf("/");if(-1!==e){const n=t.substring(e+1);L(n)}}"@"!==a||s||(i(!0),l(""));const c=t.lastIndexOf("@");if(t.length<e.length&&-1!==c&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(c+1);!e.includes(" ")&&(i(!0),l(e))}if(s)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),l("");else{const n=t.substring(e+1);l(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);l(e),i(!1)}else l(n)}}$&&(t!==e||t.length<e.length)&&I(!1),0===t.length&&(F(!1),j(!1),L(""),V(!1),ne([]),ee([]),l(""),oe(""),le(!1)),n(t)},[$,e,n,s,i,D,ce,te]),we=H(async()=>{if($)return void I(!1);let n=e.trim();if(!D&&n.startsWith("/"))return d&&d(n),F(!1),j(!1),L(""),ne([]),void ee([]);let r=[];const o=te.length>0,a=X.length>0;if(!D&&o){const e=[];te.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!D&&a){let e=n;X.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:D?"bash":"user",images:r}),F(!1),j(!1),L(""),ne([]),ee([])},[t,d,$,e,D,te]),Ee=H(t=>{const r=b(process.cwd(),t);let o;if(s&&""!==c){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),i(!1),l(""),x(e=>e+1)},[n,i,e,s,c,l]),be=H(()=>{i(!1),l("")},[i,l]),ke=H(t=>{if("/resume"===t)oe(e),j(!1),L(""),V(!0),n(""),x(e=>e+1);else{const e=Object.values(fr).includes(t);j(!1),L(""),e?(n(""),x(e=>e+1),d&&d(t)):(n(t+" "),x(e=>e+1))}},[d,n,e]),ve=H(()=>{j(!1),L(""),n(""),x(e=>e+1)},[n]),Ce=H(e=>{V(!1),n(""),oe(""),x(e=>e+1),d&&d(`/resume:${e}`)},[d]),Te=H(()=>{V(!1),n(re),x(e=>e+1)},[re]),Se=G(()=>T?!$&&!_:!$&&0===e.length&&!D&&!_,[$,e,D,_,T]),Pe=__name(()=>$||s||N||_||R?0:Se||D?3:4,"getBottomMargin");return U.createElement(q,{width:"100%",flexDirection:"column",marginBottom:Pe()},!_&&U.createElement(q,{borderStyle:ue?"round":void 0,borderRight:!1,borderLeft:!1,borderColor:D?"green":"gray",paddingY:0,width:"100%"},U.createElement(K,{color:D?"green":"dim"},D?"!":a.pointer),U.createElement(q,{flexGrow:1,paddingLeft:1},U.createElement(Q,{key:A,value:e,placeholder:o,onChange:ye,onSubmit:()=>{s||N||_||we()},showCursor:r}))),$&&U.createElement(Fr,null),R&&U.createElement(q,{paddingTop:1},U.createElement(K,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),s&&U.createElement(Ir,{onSelectFile:Ee,onClose:be,searchQuery:c}),N&&U.createElement(wr,{onSelectCommand:ke,onClose:ve,searchQuery:O}),_&&U.createElement(Dr,{onSelectSession:Ce,onClose:Te}),Se&&U.createElement(q,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1},U.createElement(q,null,T?U.createElement(q,{flexDirection:"row"},U.createElement(K,{color:"#E4CCFF"},"» accept edits on "),U.createElement(K,{dimColor:!0},"(shift+tab to toggle)")):U.createElement(K,{color:"dim"},"? for shortcuts")),U.createElement(q,{flexDirection:"row",columnGap:1},w&&U.createElement(q,null,U.createElement(K,null,U.createElement(K,null,a.tick," ","Command Code"," ","updated:"," "),U.createElement(K,{dimColor:!0},"v",w.updatedFrom),U.createElement(K,{dimColor:!0}," ",a.arrowRight," "),U.createElement(K,null,"v",w.updatedTo))),!w&&E&&U.createElement(U.Fragment,null,U.createElement(q,null,U.createElement(K,{color:"yellow",dimColor:!0},a.info," Update available:"," ",E.currentVersion," ",a.arrowRight," ",E.latestVersion)),(k||m||g||u)&&U.createElement(q,{marginLeft:1,marginRight:1},U.createElement(K,{dimColor:!0,color:"gray"},"•"))),v&&k&&U.createElement(U.Fragment,null,U.createElement(q,null,U.createElement(K,{color:"green",dimColor:!0},`${a.bullet} Provider: ${getProviderDisplayName(k)}`)),(u||C)&&U.createElement(q,{marginLeft:1,marginRight:1},U.createElement(K,{dimColor:!0,color:"gray"},"•"))),C&&U.createElement(U.Fragment,null,U.createElement(q,null,U.createElement(K,{color:"yellow",dimColor:!0},"--co")),u&&U.createElement(q,{marginLeft:1,marginRight:1},U.createElement(K,{dimColor:!0,color:"gray"},"•"))),U.createElement($r,{usage:u||null}))),D&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:"green"},"! for bash mode")),h&&p&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:"#E4CCFF"},"SHARED: ",p.url," (copied to clipboard)")),f&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:f.includes("NOT SHARED")?"red":"#E4CCFF"},f)),y&&U.createElement(q,{paddingLeft:1},U.createElement(K,{color:"#E4CCFF"},y)))},"InputBox"),Mr=__name(()=>{const[e,t]=B("continuous learning"),n=z([]),r=z(0),o=z(null),a=z(!1);W(()=>{const e=__name(e=>"analyzing"===e.type?(a.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):a.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(a.current=!1,void(n.current.length>0?(r.current=0,s()):t("continuous learning"))):void 0,"handleNewEvent"),s=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const a="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,s()},a)},"cycleThroughNextEvent");return ir.on("new-event",e),()=>{ir.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const s=9+e.length+19>100;let i=e;if(s){const t=100;e.length>t&&(i=e.substring(0,t-3)+"...")}else{const t=72;e.length>t&&(i=e.substring(0,t-3)+"...")}return U.createElement(q,null,!s&&U.createElement(K,{color:"green"},"● taste: "),U.createElement(K,null,i),!s&&U.createElement(K,{dimColor:!0}," (ctrl+t to expand)"))},"LearningFeedMini"),Nr=U.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:a,onSubmit:s,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:k,currentProvider:v,showProviderInfo:C,isOAuthMode:T,autoAcceptMode:S,onToggleAutoAccept:P,hintMessage:A})=>{const[x,$]=B(0);return W(()=>{if(!t)return void $(0);const e=setInterval(()=>{$(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),U.createElement(q,{flexDirection:"column"},U.createElement(vr,{messages:e}),U.createElement(q,{flexDirection:"row",justifyContent:"space-between"},U.createElement(q,{flexDirection:"column"},(t||n.isExecuting)&&U.createElement(xr,{tokens:m,timeElapsed:x,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),A&&U.createElement(q,{marginLeft:1},U.createElement(K,{dimColor:!0}," ","⎿"," Tip: ",A)))),U.createElement(Rr,{input:o,setInput:a,onSubmit:s,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:k,currentProvider:v,showProviderInfo:C,isOAuthMode:T,autoAcceptMode:S,onToggleAutoAccept:P,hintMessage:A}),p&&!o&&U.createElement(q,{justifyContent:"flex-end",marginTop:-3},U.createElement(Mr,null)))}),jr=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=X(),[r,o]=B([]),[s,i]=B(0),[c,l]=B(!0),[d,u]=B(0),m=30;W(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await Zn.listSessions();o(e),l(!1)},"loadSessions");if(J((t,o)=>{o.upArrow?i(e=>{const t=Math.max(0,e-1);return t<d&&u(t),t}):o.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=d+m&&u(t-m+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),c)return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),a=Math.floor(n/864e5),s=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:a<7?`${a} day${a>1?"s":""} ago`:1===s?"1 week ago":`${s} weeks ago`},"formatRelativeTime"),h=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"gray"},"No sessions available"));const f=r.slice(d,d+m),y=d;return U.createElement(q,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"dim"},"Showing ",d+1,"-",Math.min(d+m,r.length)," ","of ",r.length," sessions",d>0&&" (↑ for more)",d+m<r.length&&" (↓ for more)")),U.createElement(q,{columnGap:2,marginBottom:1},U.createElement(q,{width:7},U.createElement(K,{color:"gray"}," ")),U.createElement(q,{width:13},U.createElement(K,{color:"gray"},"Modified")),U.createElement(q,{width:11},U.createElement(K,{color:"gray"},"# Messages")),U.createElement(q,{width:20},U.createElement(K,{color:"gray"},"Git Branch")),U.createElement(q,null,U.createElement(K,{color:"gray"},"Summary"))),U.createElement(q,{columnGap:2},U.createElement(q,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${a.pointer} ${n+1}.`:` ${n+1}.`)})),U.createElement(q,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`mod-${e.id}`,color:s===n?"white":"gray"},p(e.lastModified))})),U.createElement(q,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),U.createElement(q,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),U.createElement(q,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return U.createElement(K,{key:`summary-${e.id}`,color:s===n?"white":"gray"},h(e.firstMessage))}))))},"SessionTable");function RetryMessage({attempt:e}){const[t,n]=B(0);if(W(()=>{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 U.createElement(q,{marginBottom:1},U.createElement(K,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}__name(RetryMessage,"RetryMessage");var Or=__name(({onTrust:e,onExit:t})=>{const{exit:n}=X(),[r,o]=B(1),s=process.cwd().replace(process.env.HOME||"","~");return J((a,s)=>{s.upArrow||s.downArrow?o(1===r?2:1):s.return?1===r?e():(t(),n()):"1"===a?e():("2"===a||s.escape||s.ctrl&&"c"===a)&&(t(),n())}),U.createElement(q,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1},U.createElement(K,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),U.createElement(q,{marginTop:1},U.createElement(K,{color:"gray"},s)),U.createElement(q,{marginTop:1,flexDirection:"column"},U.createElement(K,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),U.createElement(q,{marginTop:1},U.createElement(K,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),U.createElement(q,{marginTop:1,flexDirection:"column"},U.createElement(q,null,U.createElement(K,{color:1===r?"cyan":"gray"},1===r?a.pointer:" "," 1. Yes, proceed")),U.createElement(q,null,U.createElement(K,{color:2===r?"cyan":"gray"},2===r?a.pointer:" "," 2. No, exit"))))},"TrustPrompt"),Lr=class extends me{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||y.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 P.readFile(this.configPath,"utf-8"),t=JSON.parse(e);t.permissions&&("acceptEdits"===t.permissions.defaultMode&&(this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0),t.permissions.autoApprove&&(void 0!==t.permissions.autoApprove.create&&(this.config.autoApprove.create=t.permissions.autoApprove.create),void 0!==t.permissions.autoApprove.update&&(this.config.autoApprove.edit=t.permissions.autoApprove.update),void 0!==t.permissions.autoApprove.delete&&(this.config.autoApprove.delete=t.permissions.autoApprove.delete)),t.permissions.allow&&t.permissions.allow.forEach(e=>{if(e.startsWith("Bash(")&&e.endsWith(")")){const t=e.slice(5,-1);this.config.trustedCommands.push(t)}}))}catch(e){}}async requestPermission(e){if(!this.config.enabled)return{allowed:!0};const t=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)?{allowed:!0}:this.config.sessionPermissions.has(t)?{allowed:this.config.sessionPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("permission-request",e,n=>{this.handleUserChoice(e,n).then(t)})})}async handleUserChoice(e,t){const n=e.action,r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionPermissions.set(n,!0);break;case"project":await this.createCommandCodeSettings(),this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getFileKey(e){const t=y.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=y.relative(this.projectRoot,e);return this.config.trustedPaths.some(n=>t.startsWith(n)||e.startsWith(n))}async requestShellPermission(e){if(!this.config.enabled)return{allowed:!0};const t=this.getCommandKey(e);return this.config.autoApprove.shellCommands||this.isTrustedCommand(e.command)?{allowed:!0}:this.config.projectShellPermissions.has(t)?{allowed:this.config.projectShellPermissions.get(t)||!1,scope:"project"}:this.config.sessionShellPermissions.has(t)?{allowed:this.config.sessionShellPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("shell-permission-request",e,n=>{this.handleShellUserChoice(e,n).then(t)})})}async handleShellUserChoice(e,t){const n=this.getCommandKey(e),r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionShellPermissions.set(n,!0);break;case"project":await this.addCommandToSettings(e.command),this.config.projectShellPermissions.set(n,!0)}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getCommandKey(e){return`${e.command.split(" ")[0]}:${e.args?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand(e){return!!["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","grep","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))||this.config.trustedCommands.some(t=>{if(t===e)return!0;if(t.endsWith(":*")){const n=t.slice(0,-2);return e===n||e.startsWith(n+" ")}return e.startsWith(t)})}clearSessionPermissions(){this.config.sessionPermissions.clear(),this.config.sessionShellPermissions.clear()}clearProjectPermissions(){this.config.projectPermissions.clear(),this.config.projectShellPermissions.clear()}setAutoApprove(e,t){this.config.autoApprove[e]=t}addTrustedPath(e){this.config.trustedPaths.includes(e)||this.config.trustedPaths.push(e)}removeTrustedPath(e){const t=this.config.trustedPaths.indexOf(e);t>-1&&this.config.trustedPaths.splice(t,1)}addTrustedCommand(e){this.config.trustedCommands.includes(e)||this.config.trustedCommands.push(e)}removeTrustedCommand(e){const t=this.config.trustedCommands.indexOf(e);t>-1&&this.config.trustedCommands.splice(t,1)}setEnabled(e){this.config.enabled=e}getConfig(){return{...this.config}}async createCommandCodeSettings(){const e=y.join(this.projectRoot,".commandcode"),t=y.join(e,"settings.local.json");try{await P.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await P.readFile(t,"utf-8"),r=JSON.parse(e);r.permissions&&r.permissions.allow&&(n.permissions.allow=[...new Set([...r.permissions.allow,...n.permissions.allow])]),r.permissions&&r.permissions.deny&&(n.permissions.deny=r.permissions.deny)}catch(e){}await P.writeFile(t,JSON.stringify(n,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const t=y.join(this.projectRoot,".commandcode"),n=y.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await P.mkdir(t,{recursive:!0});try{const t=await P.readFile(n,"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(r)||e.permissions.allow.push(r),await P.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},_r=__name((e={})=>{const[t,n]=B(null),[r,o]=B(null),[a,s]=B(!1);return W(()=>{const t=e.projectRoot||process.cwd(),r=new Lr(t);return r.on("permission-request",(t,n)=>{o(t),s(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),s(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:H(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:H(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:H(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),s(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),s(!1)}},[t]),clearSessionPermissions:H(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:H(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:H((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:H(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:a,service:t}},"usePermissions"),Ur=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=B(0),o=[{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}],s=__name(e=>{const r=o.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),i=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),c=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const t=y.basename(e.filePath),n=y.relative(process.cwd(),e.filePath);return n&&!n.startsWith("../")&&n.length<50?n:t||e.filePath}catch{return e.filePath}},"getDisplayPath"),l=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return U.createElement(q,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"yellow"},`${l()} ${"edit"===e.action?c():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&U.createElement(q,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c(),marginLeft:0}).diffContent),U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0},"Do you want to ",i()," ",U.createElement(K,{color:"cyan"},c()),"?")),U.createElement(Ee,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>U.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?U.createElement(U.Fragment,null,e.split("(shift+tab)")[0],U.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?U.createElement(U.Fragment,null,e.split("(")[0],U.createElement(K,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),Br=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=B(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:"",n=t?`${e.command} ${t}`:e.command;return n.length>60?n.substring(0,57)+"...":n},"getCommandDisplay");return U.createElement(q,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0,color:"yellow"},"Execute Shell Command")),U.createElement(q,{marginBottom:1},U.createElement(K,{bold:!0},"Command Code needs to execute ",U.createElement(K,{color:"cyan"},i()),".")),e.workingDirectory&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&U.createElement(q,{marginBottom:1},U.createElement(K,{color:"gray",italic:!0},e.description)),U.createElement(Ee,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"cyan"},e?a.pointer:" "),itemComponent:({label:e,isSelected:t})=>U.createElement(K,{color:t?"cyan":"white"},e.includes("(shift+tab)")?U.createElement(U.Fragment,null,e.split("(shift+tab)")[0],U.createElement(K,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt"),Wr=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole"),zr=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=B(!1),[a,s]=B(!0);W(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{s(!1)}},"loadSettings")()},[]),J((t,n)=>{if(!n.return&&" "!==t)return n.escape?(Wr(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return a?U.createElement(q,{key:n,borderStyle:"round",borderColor:"blue",padding:1,flexDirection:"column"},U.createElement(K,{color:"blue",bold:!0},"Taste Settings"),U.createElement(K,{dimColor:!0},"Loading configuration...")):U.createElement(q,{key:n,borderStyle:"round",borderColor:"gray",padding:1,flexDirection:"column"},U.createElement(K,{bold:!0},"Taste Learning"),U.createElement(K,{dimColor:!0},"Configure taste learning preferences for this project"),U.createElement(q,{marginTop:1}),U.createElement(q,{justifyContent:"space-between"},U.createElement(K,null,"Taste learning",U.createElement(K,{dimColor:!0}," - Learn from your interactions")),U.createElement(K,{color:r?"green":"gray"},r?"enabled":"disabled")),U.createElement(q,{marginTop:1}),U.createElement(K,{dimColor:!0},"Taste data stored in .commandcode/taste/"),U.createElement(K,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig"),Gr=__name(({onClose:e,staticKey:t})=>{const[n,r]=B([]),[o,a]=B(!0),[s,i]=B(null),{stdout:c}=Y(),l=c?.columns??80,d=__name((e,t)=>e.length<=t?e:t<=3?e.substring(0,t):e.substring(0,t-3)+"...","truncateText");W(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),n=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];r(n)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{a(!1)}},"loadSkills")()},[]);const u=__name(async t=>{const r=n.find(e=>e.value===t.value);if(r)try{await ne([{file:r.filePath,line:1}]),Wr(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(m()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelect");J((t,n)=>{n.escape&&(Wr(),e())});const m=__name(()=>{const e=process.platform;return"win32"===e?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===e?"~/.zshrc":"~/.bashrc")},"getEditorSetupMessage");return o?U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),U.createElement(K,{dimColor:!0},"Loading skills...")):s?U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(K,{color:"red",bold:!0},"Agent Skills"),U.createElement(K,{dimColor:!0},s),U.createElement(q,{marginTop:1}),U.createElement(K,{dimColor:!0},"Press ",U.createElement(K,{bold:!0},"Esc")," to close")):0===n.length?U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills"),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"No skills found")),U.createElement(K,{dimColor:!0},"Create skills in:"),U.createElement(K,{dimColor:!0}," ~/.commandcode/skills/ (user)"),U.createElement(K,{dimColor:!0}," .commandcode/skills/ (project)"),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press ",U.createElement(K,{bold:!0},"Esc")," to close"))):U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(q,null,U.createElement(K,{color:"#E4CCFF",bold:!0},"Agent Skills")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Select a skill to open in your editor. Skills provide specialized guidance for coding tasks.")),U.createElement(Ee,{items:n,onSelect:u,initialIndex:0,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const r=n.find(e=>e.label===t),o=r?.location?` (${r.location})`:"",a=Math.max(30,l-35),s=r?.description?d(r.description,a):"";return U.createElement(q,null,U.createElement(K,{color:e?"green":"white"},` ${t}`),U.createElement(K,{color:"gray"},o.padEnd(25-t.length)),U.createElement(K,{color:"gray"},s))}}),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press ",U.createElement(K,{bold:!0},"Esc")," to cancel")))},"SkillsConfig"),Hr=__name(({onClose:e})=>{const[t,n]=B(ir.getEvents());J((t,n)=>{n.ctrl&&"t"===t&&(Wr(),e())},{isActive:!0}),W(()=>{const e=__name(()=>{n(ir.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return ir.on("new-event",e),ir.on("cleared",t),()=>{ir.off("new-event",e),ir.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,a=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);a=`confidence: ${parseFloat(e).toString()}%`}const s={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:s,content:o,confidence:a}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),s=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),i=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails");return U.createElement(q,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(pe,{name:"vice"},U.createElement(K,null,Er()))),U.createElement(q,{marginBottom:1,width:"100%",justifyContent:"space-between"},U.createElement(q,null,U.createElement(K,{bold:!0},"Learning Feed"),U.createElement(K,{dimColor:!0}," - Real-time taste learning activity")),U.createElement(K,{dimColor:!0},"Press ctrl+t to close")),U.createElement(q,{flexDirection:"column"},0===t.length?U.createElement(q,null,U.createElement(K,{dimColor:!0},"No learning events yet...")):U.createElement(q,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:a}=o(e.message),c="moved"===t?i(e.details):null,l="upgraded"===t||"downgraded"===t?s(r):null;return U.createElement(q,{key:e.id,marginBottom:1},U.createElement(q,{flexDirection:"column"},U.createElement(q,null,U.createElement(K,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?U.createElement(K,{dimColor:!0}," (",c.fullPath,")"):e.details?U.createElement(K,{dimColor:!0}," (",e.details,")"):null),U.createElement(q,{marginLeft:1},U.createElement(K,{dimColor:!0},"⎿"," "),c?U.createElement(U.Fragment,null,U.createElement(K,null,c.category," package ("),U.createElement(K,{dimColor:!0},c.oldPath),U.createElement(K,null," → ",c.newPath),U.createElement(K,null,")")):l?U.createElement(U.Fragment,null,U.createElement(K,null,l.text," ("),U.createElement(K,{dimColor:!0},"confidence: "),U.createElement(K,{dimColor:!0},l.oldPercent,"%"),U.createElement(K,null," → "),U.createElement(K,{color:l.diff>0?"green":"red"},l.newPercent,"%"),U.createElement(K,null,")")):U.createElement(U.Fragment,null,U.createElement(K,null,r),a&&U.createElement(K,{dimColor:!0}," (",a,")")))))}return U.createElement(q,{key:e.id,marginBottom:1},U.createElement(K,{dimColor:!0},a.pointerSmall," ",e.message))}))))},"LearningFeedFull");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,a="";for(let e=0;e<t.length;e++){const s=t[e];'"'!==s&&"'"!==s||o?s===a&&o?(o=!1,a=""):" "!==s||o?r+=s:(r.trim()&&n.push(r.trim()),r=""):(o=!0,a=s)}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),a=n.substring(r+1).trim();return{commandName:o,rawArguments:a,positionalArgs:parsePositionalArguments({input:a})}}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}}__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate");var Vr=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");J((e,n)=>{n.escape&&t()});const a=n?r.findIndex(e=>e.value===n):0,s=n&&-1===a;return U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(q,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},U.createElement(q,null,U.createElement(K,{bold:!0},"Select AI Provider")),n&&U.createElement(q,{flexDirection:"row"},U.createElement(K,{dimColor:!0},"Current: "),U.createElement(K,{color:"green"},getProviderDisplayName(n)),s&&U.createElement(K,{color:"yellow"}," [OAuth enforced]"))),U.createElement(q,{marginBottom:0},U.createElement(K,{dimColor:!0},"Available Providers:")),U.createElement(Ee,{items:r,onSelect:o,initialIndex:a>=0?a:0,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"cyan":"gray",bold:e},` ${t}`)}),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector");function getModelOptions(){return Object.values(Ne).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}__name(getModelOptions,"getModelOptions");var qr=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");J((e,n)=>{n.escape&&t()});const a=n?r.findIndex(e=>e.value===n):0;return U.createElement(q,{flexDirection:"column",paddingX:0,width:"100%"},U.createElement(q,null,U.createElement(K,{color:"#E4CCFF",bold:!0},"Select model")),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),U.createElement(Ee,{items:r,onSelect:o,initialIndex:a>=0?a:0,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),a=o?.value===n,s=o?.description?`${o.label} (${o.description})`:o?.label||t;return U.createElement(q,null,U.createElement(K,{color:e?"green":"gray"},` ${s.padEnd(24)}`),U.createElement(K,{color:e?"green":"gray"},o?.modelName),a&&U.createElement(K,{color:"green"}," ✓"))}}),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to cancel")))},"ModelSelector"),Kr=__name(({onClose:e})=>{const[t,n]=B([]),[r,o]=B(0),[a,s]=B(!0),[i,c]=B(null);W(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),s(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),s(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(J((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),a)return U.createElement(q,{paddingLeft:1,paddingTop:1},U.createElement(K,{color:"dim"},"Loading memory files..."));if(i)return U.createElement(q,{paddingLeft:1,paddingTop:1},U.createElement(K,{color:"red"},"❌ ",i));const u=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return U.createElement(q,{flexDirection:"column",width:"100%",borderStyle:"round",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},U.createElement(q,null,U.createElement(K,{color:"white",bold:!0},"Select memory to edit:")),U.createElement(q,{columnGap:4,marginTop:1},U.createElement(q,{flexDirection:"column"},u.map((e,t)=>U.createElement(K,{key:t,color:r===t?"white":"dim"},r===t?"> ":" ",e.label))),U.createElement(q,{flexDirection:"column"},u.map((e,t)=>U.createElement(K,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector"),Jr=class{static{__name(this,"TasteManager")}static async initializeProject(){const e=process.cwd(),t=f.join(e,".commandcode","taste");await S.mkdir(t,{recursive:!0});const n=f.join(t,"taste.md");try{await S.access(n);const e=await S.readFile(n,"utf-8"),t=migrateHeader({content:e});t!==e&&await S.writeFile(n,t,"utf-8")}catch{await S.writeFile(n,ft+"\n\n")}}static async isInitialized(){const e=process.cwd(),t=f.join(e,".commandcode","taste");try{return await S.access(t),!0}catch{return!1}}},Yr=__name(({staticKey:e})=>U.createElement(V,{items:[{staticKey:e}],key:e},()=>U.createElement(K,{key:e},"\0")),"Responsive"),Zr=__name(()=>y.join(T.homedir(),".commandcode","agents"),"getRootAgentDir"),Xr=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Qr=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=B("idle"),[a,s]=B(""),i=[...tr.map(e=>e.name),...nr.map(e=>e.name)],c=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void s("Agent configuration is incomplete");o("saving");try{const n="personal"===e.location?Zr():Xr();await P.mkdir(n,{recursive:!0});const r=`${e.agentType}.md`,o=y.join(n,r),a=Array.from(e.selectedTools).map(e=>or[e]||e).join(", "),s=0===e.selectedTools.size?"none":e.selectedTools.size===i.length?'"*"':JSON.stringify(a),c=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${s}\n---\n\n${e.sysPrompt}\n`;await P.writeFile(o,c,"utf-8"),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),s(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");J((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||c()});const l=Array.from(e.selectedTools).map(e=>or[e]||e).join(", "),d="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return U.createElement(q,{flexDirection:"column",gap:1},U.createElement(q,{flexDirection:"column"},U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Name:"),U.createElement(K,{color:"gray"},e.agentType)),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Location:"),U.createElement(K,{color:"gray"},d)),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Tools:"),U.createElement(K,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===i.length?"*":l))),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"Description"),U.createElement(K,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),U.createElement(K,{color:"gray"},e.ccToolDefinition),U.createElement(q,{gap:1},U.createElement(K,{color:"white",bold:!0},"System Prompt:")),U.createElement(K,{color:"gray"},e.sysPrompt),!n&&U.createElement(q,{marginTop:1},"idle"===r&&U.createElement(q,{gap:1},U.createElement(K,{color:"green",dimColor:!0},"Press"),U.createElement(K,{color:"green",bold:!0},"Enter"),U.createElement(K,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===r&&U.createElement(K,{color:"yellow"},"Saving agent..."),"saved"===r&&U.createElement(K,{color:"green"},"✓ ",a),"error"===r&&U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"red"},"✗ Error: ",a),U.createElement(K,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),eo=__name(({agent:e,onBack:t,setRevalidateAgent:n})=>{const[r,o]=B("menu"),a=[...tr.map(e=>e.name),...nr.map(e=>e.name)];let s=new Set;if("*"===e.tools||'"*"'===e.tools)s=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>ar[e]||e);s=new Set(t)}const i={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:s},c=__name(e=>{"back"===e.value?t():"view"===e.value?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(J((e,n)=>{n.escape&&("menu"===r?t():o("menu")),n.return&&"view"===r&&o("menu")}),"view"===r)return U.createElement(q,{flexDirection:"column"},U.createElement(Qr,{config:i,onSaveComplete:()=>o("menu"),viewOnly:!0}),U.createElement(q,{marginTop:1},U.createElement(K,{color:"gray"},"Press Enter to go back")));if("edit"===r)return U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"yellow"},"Edit functionality coming soon..."),U.createElement(K,{color:"gray"},"Press Esc to go back"));if("delete"===r){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],a=__name(async r=>{if("confirm-delete"===r.value)try{await P.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return U.createElement(q,{flexDirection:"column",gap:1},U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"red"},"Delete agent"),U.createElement(K,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),U.createElement(q,null,U.createElement(Ee,{items:r,onSelect:a,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)})))}return U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white",bold:!0},e.name),U.createElement(q,{marginTop:1},U.createElement(Ee,{items:[{label:"1. View agent",value:"view"},{label:"2. Delete agent",value:"delete"},{label:"3. Back",value:"back"}],onSelect:c,indicatorComponent:({isSelected:e})=>U.createElement(K,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)})),U.createElement(q,{marginTop:1},U.createElement(K,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),to=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=B([]),[o,a]=B([]),[s,i]=B(!0),[c,l]=B(!1),[d,u]=B(null),[m,g]=B(!1),p=__name(()=>y.join(T.homedir(),".commandcode","agents"),"getRootAgentDir"),h=__name(()=>y.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),f=__name(async(e,t)=>{try{l(!1);const n=(await P.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=y.join(e,n),o=await P.readFile(r,"utf-8"),{data:a,content:s}=se(o);let i=a.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:a.name||n.replace(".md",""),description:a.description||"",tools:i,sysPrompt:s.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");W(()=>{__name(async()=>{i(!0);const[e,t]=await Promise.all([f(p(),"personal"),f(h(),"project")]);r(e),a(t),i(!1)},"loadAgents")()},[c]);const w=[{label:"Create new agent",value:"create_new_agent"}];n.forEach(e=>{w.push({label:e.name,value:e.filePath})}),o.forEach(e=>{w.push({label:e.name,value:e.filePath})});const E=n.length>0||o.length>0,b=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...n,...o].find(e=>e.filePath===t.value);e&&(u(e),g(!0))}},"handleAgentSelect");if(s)return U.createElement(K,{color:"gray"},"Loading agents...");if(m&&d)return U.createElement(eo,{agent:d,onBack:()=>{g(!1),u(null)},setRevalidateAgent:l});const k=__name(({isSelected:e,label:t})=>{const r=w.find(e=>e.label===t),a=r?.value||"",s=n[0]?.filePath===a,i=o[0]?.filePath===a;return U.createElement(q,{flexDirection:"column"},s&&n.length>0&&U.createElement(q,{marginTop:1,marginLeft:2},U.createElement(K,{color:"white"},"User agents (~/",".commandcode","/","agents",")")),i&&o.length>0&&U.createElement(q,{marginTop:1,marginLeft:2},U.createElement(K,{color:"white"},"Project agents")),U.createElement(q,null,U.createElement(K,{color:"white"},e?">":" "),U.createElement(K,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return U.createElement(q,{flexDirection:"column"},U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{color:"white",bold:!0},"Agents"),E?U.createElement(K,{color:"gray"},n.length+o.length," agents"):U.createElement(K,{color:"gray"},"No agents found")),t&&U.createElement(q,{flexDirection:"column",marginBottom:1},U.createElement(K,{color:"green",dimColor:!0},"Created agent: ",t)),U.createElement(Ee,{items:w,onSelect:b,indicatorComponent:()=>null,itemComponent:k}),!E&&U.createElement(q,{flexDirection:"column",marginTop:1},U.createElement(K,{color:"gray"},"No agents found. Create specialized subagents that Command Code can delegate to."),U.createElement(K,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools."),U.createElement(K,{color:"gray"},"Try creating: Code Reviewer, Code Simplifier, Security Reviewer, Tech Lead, or UX Reviewer.")))},"ManageAgents"),no=__name(({onSelect:e})=>U.createElement(Ee,{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})=>U.createElement(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector"),ro=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:a,onCCToolDefinitionChange:s,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=B(!1),[m,g]=B(!1),p=H(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[d,a]),h=H(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[m,s]);return"agentType"===e?U.createElement(U.Fragment,null,U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(or).some(e=>ue(e)===ue(t))||Object.keys(or).some(e=>ue(e)===ue(t)))&&U.createElement(K,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name.")),U.createElement(Q,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=ue(t);Object.values(or).some(t=>ue(t)===e)||Object.keys(or).some(t=>ue(t)===e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?U.createElement(U.Fragment,null,U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white"},"Enter the system prompt for your agent:"),U.createElement(K,{color:"gray"},"Be comprehensive for best results.")),U.createElement(Q,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?U.createElement(U.Fragment,null,U.createElement(K,{color:"white"},"When should ","Command Code"," use this agent?"),U.createElement(Q,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow"),oo=__name(({onSelect:e})=>U.createElement(Ee,{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})=>U.createElement(K,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>U.createElement(K,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector"),ao=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=B(!1),[c,l]=B(0),d=H(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 U.createElement(q,{flexDirection:"column"},r?U.createElement(q,null,U.createElement(CMDIcon,null),U.createElement(K,{color:"white"},"Generating agent from description...")):U.createElement(Q,{key:c,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:d,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&U.createElement(q,{marginTop:1},U.createElement(K,{color:"red"},`${a.warning} ${o}`)))},"RecommendedFlow"),so=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,a]=B(!1),[s,i]=B(0),c=G(()=>[...tr.map(e=>e.name),...nr.map(e=>e.name)],[]),l=G(()=>[{name:"All tools",tools:c},{name:"Read-only tools",tools:c.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:c.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:c.filter(e=>"shell_command"===e)},{name:"Search tools",tools:c.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:c.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[c]),d=G(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),c.forEach(t=>{e.push({type:"tool",value:t})})):(l.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,l,e,c]),u=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=l.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${or[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),m=u.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return J((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[s];if(e){const s=d[e.value];if(!s)return;"continue"===s.type?r():"toggle"===s.type?(a(!o),i(0)):"category"===s.type?n(s.value):"tool"===s.type&&t(s.value)}}}),U.createElement(q,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===s;if("divider"===e.type)return U.createElement(q,{key:`divider-${t}`},U.createElement(K,{color:"gray"}," ",e.label));if("spacer"===e.type)return U.createElement(q,{key:`spacer-${t}`,height:1});if("label"===e.type)return U.createElement(q,{key:`label-${t}`},U.createElement(K,{color:"gray"}," ",e.label));const o="continue"===e.type;return U.createElement(q,{key:`item-${t}`},U.createElement(K,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),U.createElement(q,{marginTop:1},e.size===c.length&&U.createElement(K,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&U.createElement(K,{color:"gray"},e.size," tools selected"),0===e.size&&U.createElement(K,{color:"gray"},"No tools selected")))},"ToolsSelector"),io=__name(({onComplete:e})=>{const[t,n]=B("location"),[r,o]=B(!1),[a,s]=B(null),[i,c]=B("agentType"),l=G(()=>[...tr.map(e=>e.name),...nr.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=B(d()),g=__name(t=>{n("location"),c("agentType"),m(d()),e(t)},"resetToDefaults"),p=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===u.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===i)return"Agent type (identifier)";if("sysPrompt"===i)return"System prompt";if("ccToolDefinition"===i)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),h=__name(e=>{m({...u,location:e}),n("method")},"handleLocationSelect"),f=__name(e=>{m({...u,method:e}),n("configuration")},"handleMethodSelect"),y=__name(async()=>{try{s(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===Me&&(r=await _e.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const a={[Ae]:t.toString()};r&&(a[xe]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new pt({baseUrl:i}),l=await c.post({headers:a,endpoint:De.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:ue(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof st&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?s(Ue):s("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),w=__name(()=>{m({...u,agentType:ue(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),b=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),v=__name(e=>{const t=new Set(u.selectedTools);t.has(e)?t.delete(e):t.add(e),m({...u,selectedTools:t})},"handleToggleTool"),C=__name(e=>{const t=[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(u.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),m({...u,selectedTools:n})},"handleToggleCategory");return U.createElement(q,{flexDirection:"column",gap:1},U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:"white",bold:!0},"Create new agent"),U.createElement(K,{color:"gray"},p())),U.createElement(q,null,"location"===t&&U.createElement(no,{onSelect:h}),"method"===t&&U.createElement(oo,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&U.createElement(ao,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:a,onSubmit:y}),"configuration"===t&&"manual"===u.method&&U.createElement(q,{flexDirection:"column",gap:1},U.createElement(ro,{step:i,agentType:u.agentType,sysPrompt:u.sysPrompt,ccToolDefinition:u.ccToolDefinition,onAgentTypeChange:e=>m({...u,agentType:e}),onSysPromptChange:e=>m({...u,sysPrompt:e}),onCCToolDefinitionChange:e=>m({...u,ccToolDefinition:e}),onAgentTypeSubmit:w,onSysPromptSubmit:E,onCCToolDefinitionSubmit:b})),"tools"===t&&U.createElement(so,{selectedTools:u.selectedTools,onToggleTool:v,onToggleCategory:C,onComplete:k}),"summary"===t&&U.createElement(Qr,{config:u,onSaveComplete:g})))},"AgentNew"),co=__name(({onCancel:e})=>{const[t,n]=B(null),[r,o]=B(null),a=__name(e=>{n(e.value),o(null)},"handleSelect");return J((t,n)=>{n.escape&&e()}),U.createElement(q,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"round",flexDirection:"column"},null===t&&U.createElement(to,{handleSelect:a,createdAgentName:r}),"create_new_agent"===t&&U.createElement(io,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r=["create","edit","delete","execute","shellCommands"];for(const e of r)n.setAutoApprove(e,t)}__name(applyAutoAcceptMode,"applyAutoAcceptMode");var lo=[{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"}],uo=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const[r,o]=B(0),[a,s]=B(0),[i,c]=B("checkpoint"),[l,d]=B(null),[u,m]=B(0),g=G(()=>[...e].sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime()),[e]),p=G(()=>{if(!l)return!0;const e=g.findIndex(e=>e.messageId===l.messageId);if(-1===e)return!0;for(let t=0;t<=e;t++)if(g[t].filesModified.length>0)return!0;return!1},[l,g]),h=G(()=>p?lo:lo.filter(e=>"conversation"===e.mode),[p]);if(J((e,p)=>{p.escape?"mode"===i?(c("checkpoint"),d(null),m(0)):n():"checkpoint"===i?p.upArrow?o(e=>{const t=Math.max(0,e-1);return t<a&&s(t),t}):p.downArrow?o(e=>{const t=Math.min(g.length-1,e+1);return t>=a+8&&s(t-8+1),t}):p.return&&g.length>0&&(d(g[r]),c("mode"),m(0)):"mode"===i&&(p.upArrow?m(e=>Math.max(0,e-1)):p.downArrow?m(e=>Math.min(h.length-1,e+1)):p.return&&l&&h[u]&&t({messageId:l.messageId,mode:h[u].mode}))}),0===g.length)return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),U.createElement(K,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to close")));if("mode"===i&&l)return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Restore to: "),U.createElement(K,{color:"white"},truncateString({text:l.userPrompt||"checkpoint",maxLength:50}))),U.createElement(q,{flexDirection:"column"},h.map((e,t)=>{const n=u===t,r=t===h.length-1;return U.createElement(q,{key:e.mode,flexDirection:"column"},U.createElement(q,{flexDirection:"row"},U.createElement(K,{color:n?"#E4CCFF":void 0},n?"> ":" "),U.createElement(q,{flexDirection:"column"},U.createElement(K,{color:n?"#E4CCFF":"white"},e.label),U.createElement(K,{dimColor:!0},e.description))),!r&&U.createElement(K,null," "))})),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Enter"),U.createElement(K,{dimColor:!0}," to confirm, "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to go back")));const f=g.slice(a,a+8);return U.createElement(q,{flexDirection:"column",paddingLeft:2,paddingTop:1},U.createElement(K,{color:"#E4CCFF",bold:!0},"Rewind"),U.createElement(K,{dimColor:!0},"Select a checkpoint to restore your session"),g.length>8&&U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,g.length)," ","of ",g.length)),U.createElement(q,{marginTop:1}),U.createElement(q,{flexDirection:"column"},f.map((e,t)=>{const n=r===a+t,o=e.filesModified.length,s=t===f.length-1;return U.createElement(q,{key:e.messageId,flexDirection:"column"},U.createElement(q,{flexDirection:"row"},U.createElement(K,{color:n?"#E4CCFF":void 0},n?"> ":" "),U.createElement(q,{flexDirection:"column"},U.createElement(q,null,U.createElement(K,{color:n?"#E4CCFF":"white"},truncateString({text:e.userPrompt||"(no prompt)",maxLength:60})),U.createElement(K,{dimColor:!0}," • "),U.createElement(K,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}))),U.createElement(K,{dimColor:!0},o>0?`${o} file${o>1?"s":""} changed`:"No code changes"))),!s&&U.createElement(K,null," "))})),U.createElement(q,{marginTop:1},U.createElement(K,{dimColor:!0},"Press "),U.createElement(K,{dimColor:!0,bold:!0},"Enter"),U.createElement(K,{dimColor:!0}," to select, "),U.createElement(K,{dimColor:!0,bold:!0},"Esc"),U.createElement(K,{dimColor:!0}," to cancel")))},"RewindSelector"),{setText:mo}=ge,go=__name(({resume:e=!1,continue:t=!1,trust:n=!1,updateStatus:r,updateFailedInfo:o,initialMessage:a})=>{const{exit:s}=X(),[i,c]=B(""),[l,d]=B("Ready..."),[u,m]=B(null),[g,p]=B(r);W(()=>{if(g){const e=setTimeout(()=>{p(null)},3e4);return()=>clearTimeout(e)}},[g]);const{stdout:h}=Y(),[f,y]=B(!1),[w,E]=B(!1),[b,k]=B(!1),[v,C]=B(!1),[T,S]=B(!1),[P,A]=B(!1),[x,$]=B(!1),[I,D]=B(!1),[F,R]=B(null),[M,N]=B(null),[j,O]=B(getConfiguredModel()),[L,_]=B(!1),[G,H]=B(!1),[V,Z]=B(!1),Q=z(null),ee=z(null),[te,ne]=B(0),[re,oe]=B(!1),{executeBash:ae,executionState:se}=hn(),[ie,ce]=B(""),[le,de]=B([]),[ue,me]=B(!1),[ge,pe]=B([]),[he,fe]=B(crypto.randomUUID()),[ye,we]=B(!1),[Ee,be]=B(!1),[ke,ve]=B(!1),[Ce,Te]=B(!1),[Se,Pe]=B(!0),[Ae,xe]=B(!1),[$e,Ie]=B(0),[Fe,Re]=B(null),[Me,je]=B(null),[Oe,Le]=B(null),Ue=z(!1),Be=z(!1),We=z(Oe);W(()=>{We.current=Oe},[Oe]);const[ze,Ge]=B(!1),[He,Ve]=B(""),[qe,Ke]=B(!1),[Je,Ye]=B(!1),[Ze,Xe]=B(""),Qe=z(null),[et,tt]=B(!1),[nt,rt]=B(0),ot=__name(async()=>{try{const e=await isTasteLearningEnabled();Ke(e),e&&await Jr.initializeProject()}catch(e){}},"loadTasteStatus"),at=__name(async()=>{const e=await getConfiguredProvider();N(e);const t=await isOAuthEnforced();_(t)},"loadCurrentProvider"),st=z([]),it=z(null),[ct,lt]=B(null),{requestShellPermission:dt,service:ut,respondToPrompt:mt,clearSessionPermissions:gt,setEnabled:ht}=_r({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{lt({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),it.current&&d("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{lt({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),it.current&&d("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?d("Permission granted"):d("Permission denied")},"onPermissionResponse")}),ft=__name(e=>{Qe.current&&clearTimeout(Qe.current),Xe(e),Qe.current=setTimeout(()=>{Xe(""),Qe.current=null},5e3)},"showHintMessage");W(()=>()=>{Qe.current&&clearTimeout(Qe.current)},[]),W(()=>{ut&&applyAutoAcceptMode({enabled:Je,service:ut})},[Je,ut]),W(()=>{(async()=>{if(await Zn.isProjectInitialized())if(Te(!0),Pe(!1),ot(),at(),t){const e=await Zn.listSessions();if(e.length>0){const t=e[0];It(t.id)}}else e&&we(!0);else if(n)if(await Zn.initializeProject(),Te(!0),Pe(!1),ot(),at(),t){const e=await Zn.listSessions();if(e.length>0){const t=e[0];It(t.id)}}else e&&we(!0);else ve(!0),Pe(!1)})()},[e,t,n,s]),W(()=>{st.current=ge},[ge]),W(()=>{(async()=>{if(M&&"anthropic"===M&&L)try{await _e.getValidAccessToken()||d("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){d("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[M,L]),W(()=>{if(!ue)return;const e=setInterval(()=>{d(un())},7e3);return()=>clearInterval(e)},[ue]),W(()=>()=>{Q.current&&clearTimeout(Q.current),ee.current&&clearTimeout(ee.current)},[]);const yt=__name(()=>{Ye(e=>{const t=!e;return t&&ct&&(mt({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),ct.resolve(!0),lt(null)),t})},"handleToggleAutoAccept");async function getBillingLink(){if(Me)return Me;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return je(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return je(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}J((e,t)=>{if(t.shift&&t.tab||""===e)yt();else if(!(b||v||T||P||x||F||I||et)){if(t.ctrl&&"c"===e&&s(),t.ctrl&&"t"===e)return Wr(),D(e=>!e),void ne(e=>e+1);if(getIsExpandToolShortcut(t,e))return Wr(),oe(e=>!e),void ne(e=>e+1);if(t.escape){const e=Date.now(),t=e-nt;if(rt(e),t<500&&!ue&&!ct&&it.current?.hasCheckpoints())return void tt(!0);if(ct)mt({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),ct.resolve(!1),lt(null),d("Permission denied");else if(ue&&it.current){it.current.interrupt(!0),me(!1),d("Interrupted by user");const e=on("Interrupted by user");de(t=>[...t,e])}}t.meta||t.ctrl}}),W(()=>{const e=__name(()=>{Wr(),ne(e=>e+1)},"handleResize");if(h)return h.on("resize",e),()=>{h.off("resize",e)}},[h]),W(()=>{it.current||!Ce||ye||Ee||(it.current=new mr({onFeedUpdate:__name(e=>{de(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...st.current];return st.current=[],pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ie(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Re(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{m(e)},"onRetryUpdate"),onProviderChange:__name(e=>{N(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&ut){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return ut.requestShellPermission(n).then(e=>e.allowed)}if(ut){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return ut.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=We.current;return e?{sessionId:he,secret:e.secret}:null},"getShareInfo")},he),(async()=>{await Pt()})())},[he,ye,Ee,Ce]),W(()=>{a&&Ce&&!Se&&it.current&&!ye&&!Be.current&&(Be.current=!0,wt({role:"user",input:a}))},[a,Ce,Se,ye]),__name(getBillingLink,"getBillingLink");const wt=__name(async({role:e,input:t,images:n})=>{if(t.length)if(g&&p(null),Ie(0),"bash"===e){if(Ue.current)return;Ue.current=!0;const e=nn(t);de([...le,e]),c(""),await ae(t,e=>{de(e)},()=>{Wr(),ne(e=>e+1)}),Ue.current=!1}else{if(ue)return pe(e=>[...e,t]),void c("");if(Ue.current)return;Ue.current=!0,me(!0),d(un()),c("");try{it.current&&await it.current.sendMessage(t,n)}catch(e){if("Interrupted by user"===e?.message||e?.message?.toLowerCase().includes("interrupt")||e?.message?.toLowerCase().includes("abort")||"InterruptedError"===e?.name||"AbortError"===e?.name||"ECONNABORTED"===e?.code);else if("Insufficient credits"===e.message){d("Insufficient credits");const e=await getBillingLink(),t=on(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);de(e=>[...e,t])}else if(e.message.startsWith("Error:")){d("Error");const t=on(e.message);de(e=>[...e,t])}else{d("Error");const t=e.message||"An unexpected error occurred",n=on(t);de(e=>[...e,n])}}finally{me(!1),"Interrupted by user"!==l&&"Permission denied"!==l&&"Insufficient credits"!==l&&d("Ready..."),Ue.current=!1}}},"handleSubmit"),Et=__name(()=>{de(e=>[...e,rn("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),bt=__name(async()=>{if(de([]),Wr(),Ye(!1),Le(null),Ge(!1),Ve(""),it.current){const e=it.current.getSessionManager();e&&await e.deleteShareInfo(),it.current=null;const t=crypto.randomUUID();fe(t),gt(),it.current=new mr({onFeedUpdate:__name(e=>{de(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...st.current];return st.current=[],pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ie(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Re(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{m(e)},"onRetryUpdate"),onProviderChange:__name(e=>{N(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&ut){const e=Array.isArray(t.args)?t.args.join(" "):"string"==typeof t.args?t.args:"",n={command:t.command||"",args:t.args,workingDirectory:t.directory,description:`Execute shell command: ${t.command} ${e}`};return ut.requestShellPermission(n).then(e=>e.allowed)}if(ut){const n={action:e.includes("edit")?"edit":e.includes("write")?"create":e.includes("delete")?"delete":"edit",filePath:t.filePath||t.file_path||t.path||t.absolutePath||"unknown",description:t.description||`${e} operation`,oldContent:"edit_file"===e?t.oldValue:void 0,newContent:"edit_file"===e?t.newValue:void 0};return ut.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),getShareInfo:__name(()=>{const e=We.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}ne(e=>e+1),Re(null),Ie(0)},"handleClearCommand"),kt=__name(()=>{it.current?it.current.hasCheckpoints()?tt(!0):de(e=>[...e,Qt("No checkpoints available. Start sending messages to create checkpoints.")]):de(e=>[...e,Qt("No active conversation to rewind.")])},"handleRewindCommand"),vt=__name(async e=>{const{messageId:t,mode:n}=e;if(tt(!1),it.current)try{d("Restoring checkpoint...");const e=await it.current.restoreToCheckpoint({messageId:t,mode:n});if(e.success){const t=it.current.getSessionManager(),n=it.current.getMessages(),r=t.reconstructFeedFromMessages(n);de(r),Wr(),ne(e=>e+1);const o=[];e.filesRestored>0&&o.push(`${e.filesRestored} file${e.filesRestored>1?"s":""} restored`),e.filesDeleted>0&&o.push(`${e.filesDeleted} file${e.filesDeleted>1?"s":""} deleted`),e.messagesRemoved>0&&o.push(`${e.messagesRemoved} message${e.messagesRemoved>1?"s":""} removed`);const a=o.length>0?`Restored to checkpoint: ${o.join(", ")}.`:"Restored to checkpoint.";de(e=>[...e,Qt(a)]),d("Ready...")}else de(t=>[...t,on(`Failed to restore: ${e.error}`)]),d("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;de(e=>[...e,on(t)]),d("Ready...")}},"handleRewindSelect"),Ct=__name(()=>{tt(!1)},"handleRewindCancel"),Tt=__name(async()=>{if(it.current)if(it.current.isRequestInProgress())de(e=>[...e,Qt("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{d("Compacting conversation...");const e=await it.current.compactConversation();Wr(),ne(e=>e+1);const t=e.messagesRemoved>0?`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`:"Conversation is already compact.";de(e=>[...e,Qt(t)]),d("Ready..."),Re({current:it.current.getContextTokensUsed()||0,limit:Yn})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;de(e=>[...e,on(t)]),d("Ready...")}else de(e=>[...e,Qt("No active conversation to compact.")])},"handleCompactCommand"),St=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await It(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void s();case"/clear":return void await bt();case"/help":return void Et();case"/share":return void At();case"/unshare":return void $t();case"/taste":return void k(!0);case"/skills":return void C(!0);case"/provider":return void(isInternalFlagPresent()?S(!0):d("Provider selection not available"));case"/model":return void A(!0);case"/memory":return void $(!0);case"/init":return void xt();case"/agents":return void E(!0);case"/compact":return void await Tt();case"/rewind":return void kt()}const a=getCustomCommandContent(n);if(a){const e=processCommandTemplate({template:a,rawArguments:r,positionalArgs:o});await wt({input:e.content,role:"user"})}},"handleCommand"),Pt=__name(async()=>{const e=it.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&Le({url:t.url,secret:t.secret})}},"loadShareInfo"),At=__name(async()=>{if(he){if(Oe)return await mo(Oe.url),d(""),Ge(!0),void setTimeout(()=>{Ge(!1)},3e3);try{d("Creating share link...");const e=it.current?.getMessages()||[],t=sr.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new pt({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:De.ALPHA.SHARE.CREATE,body:{sessionId:he,messages:t}}),o={url:r.url,secret:r.secret};Le(o);const a=it.current?.getSessionManager();a&&await a.saveShareInfo({url:r.url,secret:r.secret}),await mo(r.url),d(""),Ge(!0),setTimeout(()=>{Ge(!1)},5e3)}catch(e){d(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else d("No active session to share")},"handleShareCommand"),xt=__name(async()=>{try{const e=process.cwd(),t=`Created AGENTS.md at ${await initProjectMemory(e)}. You can now edit it with /memory or open it in your editor.`;de(e=>[...e,Qt(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;de(e=>[...e,Qt(t)])}},"handleInitCommand"),$t=__name(async()=>{if(he){if(!Oe)return Ve("NOT SHARED: Session is not currently shared"),void setTimeout(()=>Ve(""),5e3);try{d("Removing share link...");const e=new pt({baseUrl:getApiBaseUrl()});await e.delete({endpoint:De.ALPHA.SHARE.DELETE,body:{sessionId:he,secret:Oe.secret}});const t=it.current?.getSessionManager();t&&await t.deleteShareInfo(),Ve("UNSHARED: Sharing has stopped"),d(""),Le(null),setTimeout(()=>{Ve("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;d(t),setTimeout(()=>d(""),5e3)}}else d("No active session to unshare")},"handleUnshareCommand"),It=__name(async e=>{try{de([]),it.current=null,Ye(!1),fe(e),we(!1),be(!0),await new Promise(e=>setTimeout(e,100)),it.current=new mr({onFeedUpdate:__name(e=>{de(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...st.current];return st.current=[],pe([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ie(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Re(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{m(e)},"onRetryUpdate"),onProviderChange:__name(e=>{N(e)},"onProviderChange"),getShareInfo:__name(()=>{const t=We.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const t=await it.current.loadSession(e);await Pt(),de(t),Wr(),ne(e=>e+1)}catch(e){console.error("Failed to load session:",e),we(!0),fe(crypto.randomUUID())}},"handleSelectSession"),Dt=__name(async()=>{de([]),it.current=null,Ye(!1),fe(crypto.randomUUID()),we(!1),be(!1)},"handleNewSession"),Ft=__name(async()=>{try{await Zn.initializeProject(),ve(!1),e?(console.log("No conversations found to resume."),xe(!0),s()):(Te(!0),ot(),at())}catch(e){console.error("Failed to initialize project:",e),ve(!1),xe(!0),s()}},"handleTrust"),Rt=__name(()=>{s()},"handleNoTrust"),Mt=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void R({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),N(e),S(!1);const n=getProviderDisplayName(e);d(`Provider set to ${n}`),Q.current&&clearTimeout(Q.current),H(!0),Q.current=setTimeout(()=>{H(!1),Q.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),d("Failed to set provider"),S(!1)}},"handleProviderSelect"),Nt=__name(()=>{S(!1)},"handleProviderCancel"),jt=__name(e=>{const t=Object.values(Ne).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),Ot=__name(async e=>{try{await setSelectedModel({model:e}),O(e),A(!1);const t=jt(e);d(`Model set to ${t}`),ee.current&&clearTimeout(ee.current),Z(!0),ee.current=setTimeout(()=>{Z(!1),ee.current=null},5e3)}catch(e){console.error("Failed to set model:",e),d("Failed to set model"),A(!1)}},"handleModelSelect"),Lt=__name(()=>{A(!1)},"handleModelCancel"),_t=__name(()=>{if(F){R(null),S(!1),N(F.provider);const e=getProviderDisplayName(F.provider);d(`${e} authentication successful`),Q.current&&clearTimeout(Q.current),H(!0),Q.current=setTimeout(()=>{H(!1),Q.current=null},5e3)}},"handleAuthSuccess"),Ut=__name(()=>{R(null)},"handleAuthCancel");if(Ae)return null;if(ke)return U.createElement(U.Fragment,null,U.createElement(Yr,{staticKey:te}),U.createElement(Or,{onTrust:Ft,onExit:Rt}));if(Se)return null;if(ye)return U.createElement(jr,{onSelectSession:It,onNewSession:Dt});if(!Ce)return null;if(ct){if("shell_command"===ct.toolName){const e=ct.params;return U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(kr,{staticKey:te,feed:le,showHeader:!0,expandedToolOutput:re,currentModel:j}),U.createElement(q,{marginY:1},U.createElement(Br,{request:e,onResponse:e=>{mt(e);const t="no"!==e.value;ct.resolve(t),lt(null),t?(d("Shell command allowed"),Je||ft("Use shift+tab to enable auto-accept")):d("Shell command denied")},onToggleAutoAccept:yt})))}{const e={action:ct.toolName.includes("edit")?"edit":ct.toolName.includes("write")?"create":ct.toolName.includes("delete")?"delete":"edit",filePath:ct.params.filePath||ct.params.file_path||ct.params.path||ct.params.absolutePath||ct.params.notebook_path||"unknown",description:`Allow ${ct.toolName} operation`,oldContent:"edit_file"===ct.toolName?ct.params.oldContent:void 0,newContent:"edit_file"===ct.toolName?ct.params.newContent:void 0};return U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(kr,{staticKey:te,feed:le,showHeader:!0,expandedToolOutput:re,currentModel:j}),U.createElement(q,{marginY:1},U.createElement(Ur,{request:e,onResponse:e=>{mt(e);const t="no"!==e.value;ct.resolve(t),lt(null),t?(d("File operation allowed"),Je||ft("Use shift+tab to enable auto-accept")):d("File operation denied")},onToggleAutoAccept:yt})))}}return I?U.createElement(Hr,{onClose:()=>{D(!1),ne(e=>e+1)}}):b?U.createElement(U.Fragment,null,U.createElement(Yr,{staticKey:te}),U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),U.createElement(zr,{onClose:()=>k(!1),onSettingsChange:ot,staticKey:te}))):v?U.createElement(U.Fragment,null,U.createElement(Yr,{staticKey:te}),U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(q,{marginBottom:1},U.createElement(K,{dimColor:!0},"Press Esc to return to conversation")),U.createElement(Gr,{onClose:()=>C(!1),staticKey:te}))):U.createElement(q,{flexDirection:"column",width:"100%"},U.createElement(kr,{staticKey:te,feed:le,showHeader:!0,expandedToolOutput:re,currentModel:j}),U.createElement(RetryMessage,{attempt:u}),!T&&!P&&!F&&!x&&!w&&!et&&U.createElement(Nr,{queuedMessages:ge,isProcessing:ue,executionState:se,status:l,input:i,setInput:c,onSubmit:wt,showFileList:f,setShowFileList:y,fileSearchQuery:ie,setFileSearchQuery:ce,onCommand:St,outputTokens:$e,contextUsage:Fe,tasteLearning:qe,shareInfo:Oe,showShareNotification:ze,unshareNotificationMessage:He,updateStatus:g,updateFailedInfo:o,currentProvider:M,showProviderInfo:G,isOAuthMode:L,autoAcceptMode:Je,onToggleAutoAccept:yt,hintMessage:Ze}),T&&U.createElement(q,{marginY:1},U.createElement(Vr,{onSelect:Mt,onCancel:Nt,currentProvider:M})),P&&U.createElement(q,{marginY:1},U.createElement(qr,{onSelect:Ot,onCancel:Lt,currentModel:j})),w&&U.createElement(q,{marginY:1},U.createElement(co,{onCancel:()=>E(!1)})),x&&U.createElement(q,{marginY:1},U.createElement(Kr,{onClose:()=>$(!1)})),et&&it.current&&U.createElement(q,{marginY:1},U.createElement(uo,{checkpoints:it.current.listCheckpoints(),onSelect:vt,onCancel:Ct})),F&&U.createElement(q,{marginY:1},U.createElement(F.Component,{onSuccess:_t,onCancel:Ut})))},"InteractiveCLI"),po=__name(async(e={})=>{process.stdin.isTTY||(console.error("Error: Interactive mode requires a TTY terminal."),console.error("Please run this command directly in your terminal, not through a pipe or redirect."),process.exit(1));const t=getUpdateStatus(),n=getFailedUpdateInfo();enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()}),(e.resume||e.continue)&&await Zn.isProjectInitialized()&&0===(await Zn.listSessions()).length&&(console.log("No conversations found to resume."),process.exit(0)),Z(U.createElement(go,{resume:e.resume,continue:e.continue,trust:e.trust,updateStatus:t,updateFailedInfo:n,initialMessage:e.initialMessage}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})},"interactive"),{red:ho,yellow:fo}=te,yo=__name((e="ERROR: ",t,n=!0,r=!0)=>{if(t){if(console.log(),n?(console.log(`${ke.error} ${ho(e)}`),console.log(`${ke.error} ${ho("ERROR →")} ${t.name}`),console.log(`${ke.info} ${ho("REASON →")} ${t.message}`),console.log(`${ke.info} ${ho("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${ke.warning} ${fo(e)}\n`),!r)return!1;process.exit(0)}},"handleError"),wo=__name(()=>{process.on("unhandledRejection",e=>{yo(be`CRITICAL: Unhandled Promise Rejection!
3
+ This is an unexpected error. Please file a bug report at https://github.com/LangbaseInc/command-code/issues/new`,e)})},"handleUnhandledErrors");async function checkAuthAndPromptLogin(){try{const e=await getAuthKey(),t="win32"===process.platform,r=Ge();if(!e){const e=Er();console.log(te.white(e)),r&&console.log(te.dim(`env: (${r.replace("--","")})`)),console.log(""),console.log(`${o.warning} Authentication required to use Command Code.`),console.log("");const a=ve.createInterface({input:process.stdin,output:process.stdout});try{const e=await a.question(`Would you like to sign in now? ${te.dim("(y/n)")}: `);a.close();const s=e.trim().toLowerCase();if(""!==s&&"y"!==s&&"yes"!==s)return console.log(""),console.log(`${o.info} You can authenticate later by running: ${t?"command-code":"cmd"} login`),!1;console.log(""),console.log(`${o.arrowUp} Running: ${t?"command-code":"cmd"} login`),console.log("");try{return n(`${t?"command-code":"cmd"} login ${r}`,{stdio:"inherit",cwd:process.cwd()}),await getAuthKey()?(console.log(""),console.log(`${o.tick} Authentication successful! Starting Command Code...`),console.log(""),!0):(console.log(""),console.log(`${o.cross} Authentication failed. Please try again with: ${t?"command-code":"cmd"} login`),!1)}catch(e){return console.log(""),console.log(`${o.cross} Login command failed. Please run: ${t?"command-code":"cmd"} login`),!1}}catch(e){return a.close(),console.log(""),console.log(`${o.info} Authentication cancelled. You can authenticate later with: ${t?"command-code":"cmd"} login`),!1}}return!0}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var Eo=__name(()=>{const e=[];for(const t of process.argv)"-v"===t?e.push("--version"):"-CRUD"===t?e.push("--crud"):"-CRU"===t?e.push("--cru"):"-C"===t?e.push("--create"):"-R"===t?e.push("--read"):"-U"===t?e.push("--update"):"-D"===t?e.push("--delete"):"-T"===t?e.push("--trust"):e.push(t);process.argv=e},"preprocessCustomFlags");async function updateProjectPermissions(e){const t=process.cwd(),n=f.join(t,".commandcode"),r=f.join(n,"settings.local.json");try{await S.mkdir(n,{recursive:!0});const t=await loadOrCreateSettings(r);updatePermissionsInSettings({settings:t,permissions:e}),await saveSettings({settingsPath:r,settings:t})}catch(e){throw new Error(`Failed to update project permissions: ${e instanceof Error?e.message:String(e)}`)}}async function loadOrCreateSettings(e){try{const t=parseJSON(await S.readFile(e,"utf-8"))||{permissions:{allow:[],deny:[],autoApprove:{}}};return t.permissions||(t.permissions={allow:[],deny:[]}),t.permissions.autoApprove||(t.permissions.autoApprove={}),t}catch{return{permissions:{allow:[],deny:[],autoApprove:{}}}}}function updatePermissionsInSettings(e){const{settings:t,permissions:n}=e;void 0!==n.create&&(t.permissions.autoApprove.create=n.create),void 0!==n.read&&(t.permissions.autoApprove.read=n.read),void 0!==n.update&&(t.permissions.autoApprove.update=n.update),void 0!==n.delete&&(t.permissions.autoApprove.delete=n.delete)}async function saveSettings(e){const{settingsPath:t,settings:n}=e;await S.writeFile(t,JSON.stringify(n,null,2),"utf-8")}async function handleCrudFlags(e){if(!(e.crud||e.cru||e.create||e.read||e.update||e.delete))return;await Zn.initializeProject();const t={};e.crud&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!0),e.cru&&(t.create=!0,t.read=!0,t.update=!0,t.delete=!1),e.create&&(t.create=!0),e.read&&(t.read=!0),e.update&&(t.update=!0),e.delete&&(t.delete=!0),await updateProjectPermissions(t)}async function migrateUserDirectory(){const e=T.homedir(),t=y.join(e,".command-code"),n=y.join(e,".commandcode");if(!R.existsSync(t))return{success:!0,message:"User directory migration not needed (old directory does not exist)",skipped:!0};if(R.existsSync(n))return console.warn("Both ~/.command-code and ~/.commandcode exist. Manual intervention required."),console.warn("Please manually merge or remove ~/.command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{R.renameSync(t,n);const e=y.join(n,"config.json");if(R.existsSync(e)){const t=R.readFileSync(e,"utf-8"),n=JSON.parse(t);delete n.tasteUsage,R.writeFileSync(e,JSON.stringify(n,null,2))}return{success:!0,message:"User directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("User directory migration failed:",t),console.error("Please manually rename ~/.command-code to ~/.commandcode"),{success:!1,message:`User directory migration failed: ${t}`}}}async function migrateProjectDirectory(e){const{projectRoot:t}=e,n=y.join(t,".command-code"),r=y.join(t,".commandcode");if(!R.existsSync(n))return{success:!0,message:"Project directory migration not needed (old directory does not exist)",skipped:!0};if(R.existsSync(r))return console.warn(`Both .command-code and .commandcode exist in ${t}`),console.warn("Manual intervention required. Please manually merge or remove .command-code/"),{success:!1,message:"Both old and new directories exist. Manual intervention required."};try{return R.renameSync(n,r),{success:!0,message:"Project directory migrated successfully"}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("Project directory migration failed:",t),console.error("Please manually rename .command-code to .commandcode"),{success:!1,message:`Project directory migration failed: ${t}`}}}async function migrateDirectories(e){const{projectRoot:t}=e,n=await migrateUserDirectory(),r=await migrateProjectDirectory({projectRoot:t}),o=n.skipped,a=r.skipped;return o&&a||n.success&&r.success||console.warn("\n⚠️ Some migrations failed. See messages above."),{userResult:n,projectResult:r}}__name(updateProjectPermissions,"updateProjectPermissions"),__name(loadOrCreateSettings,"loadOrCreateSettings"),__name(function createDefaultPermissionsStructure(){return{allow:[],deny:[]}},"createDefaultPermissionsStructure"),__name(updatePermissionsInSettings,"updatePermissionsInSettings"),__name(saveSettings,"saveSettings"),__name(handleCrudFlags,"handleCrudFlags"),__name(migrateUserDirectory,"migrateUserDirectory"),__name(migrateProjectDirectory,"migrateProjectDirectory"),__name(migrateDirectories,"migrateDirectories");var bo=getPackageJson(),ko=process.cwd();global.COMMAND_CODE_CWD=ko;var vo=new Te("CommandCode");wo();var Co=__name(()=>{const e=process.argv.slice(2);return!e.includes("--skip-update-check")&&0===e.length},"shouldAutoUpdate");(async()=>{if(Eo(),await migrateDirectories({projectRoot:ko}),Co()&&(process.env.NODE_NO_WARNINGS="1",(await performAutoUpdate({onProgress:__name(e=>{process.stdout.write("\r"+e)},"onProgress")})).success)){process.stdout.write("\r");const e=process.argv[1]?.includes("command-code")?"command-code":"cmd",t=r(e,["--skip-update-check"],{stdio:"inherit",detached:!1,shell:!0,env:{...process.env,NODE_NO_WARNINGS:"1"}});await new Promise(()=>{t.on("exit",e=>{process.exit(e||0)})})}const n=new e;async function commanderAction(e,t){const n=e.findIndex(e=>!e.startsWith("-")),r=[];if(n>=0)for(let t=n;t<e.length&&!e[t].startsWith("-");t++)r.push(e[t]);const o=r.length>0?r.join(" "):void 0;await checkAuthAndPromptLogin()||process.exit(1),await handleCrudFlags({crud:t.crud,cru:t.cru,create:t.create,read:t.read,update:t.update,delete:t.delete});const a={};switch(t.trust&&(a.trust=!0),!0){case t.resume:po({resume:!0,...a});break;case t.continue:po({continue:!0,...a});break;default:po({...a,initialMessage:o})}}__name(commanderAction,"commanderAction"),n.name(bo.name).description(bo.description||"Command Code — Coding Agent with taste by Langbase").version(bo.version,"-v, --version","output the version number").argument("[message...]","Initial message to send").option("-r, --resume","Resume a conversation").option("-c, --continue","Continue the last conversation").option("-T, --trust","Auto-trust project (skip initial permission prompt)").option("--crud","Enable all CRUD permissions (shortcut: -CRUD)").option("--cru","Enable Create, Read, Update (no Delete) (shortcut: -CRU)").option("--create","Enable Create permission (shortcut: -C)").option("--read","Enable Read permission (shortcut: -R)").option("--update","Enable Update permission (shortcut: -U)").option("--delete","Enable Delete permission (shortcut: -D)").addOption(new t(Se).hideHelp()).addOption(new t(Pe).hideHelp()).action(commanderAction).allowUnknownOption(),n.addCommand(rt),n.addCommand(tt),n.addCommand(ht),n.addCommand(At),n.addCommand(createTasteCommand()),n.addCommand(Ye),n.addCommand(Ze),n.addCommand(Xe),n.hook("preAction",()=>{vo.debug("Command starting...")}),n.hook("postAction",()=>{vo.debug("Command completed.")}),n.parse()})();