command-code 0.10.10 → 0.10.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import"dotenv/config";import e from"dedent";import t from"chalk";import n from"log-symbols";import r,{mainSymbols as o}from"figures";import s from"readline/promises";import a,{z as i}from"zod";import{Command as c,Option as l}from"commander";import*as d from"@clack/prompts";import{cancel as u,select as m,isCancel as g,note as p,confirm as h,password as f}from"@clack/prompts";import{Box as y,Text as w,Static as E,render as b,useInput as k,useApp as S,useStdout as C}from"ink";import v from"ink-spinner";import T from"picocolors";import A,{useState as P,useRef as x,useEffect as I,useCallback as $,useMemo as D}from"react";import*as F from"crypto";import R from"crypto";import*as M from"fs/promises";import L,{mkdir as O,writeFile as N}from"fs/promises";import U from"open";import*as j from"http";import*as _ from"net";import*as B from"path";import W,{relative as H,dirname as z,join as G,isAbsolute as q,resolve as V}from"path";import*as K from"os";import J from"os";import Y from"strip-ansi";import*as Q from"fs";import Z,{existsSync as X,readFileSync as ee,promises as te,constants as ne,readdirSync as re,statSync as oe,createReadStream as se}from"fs";import ae from"sharp";import{execSync as ie,exec as ce,spawn as le}from"child_process";import de from"ora";import ue from"@crosscopy/clipboard";import me from"gray-matter";import{minimatch as ge}from"minimatch";import{glob as pe}from"glob";import{quote as he}from"shell-quote";import{MessageStream as fe}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import ye from"@sindresorhus/slugify";import{EventEmitter as we}from"events";import{fileURLToPath as Ee,pathToFileURL as be}from"url";import ke from"strip-json-comments";import*as Se from"readline";import Ce from"ink-select-input";import ve from"ignore";import Te from"ink-gradient";import{Marked as Ae}from"marked";import Pe from"marked-terminal";import*as xe from"diff";import{promisify as Ie}from"util";import $e from"semver";import De from"open-editor";import Fe from"ink-text-input";import*as Re from"process";var Me=Object.defineProperty,__name=(e,t)=>Me(e,"name",{value:t,configurable:!0}),Le=process.argv.includes("-d")||process.argv.includes("--debug");Le&&(process.env.DEBUG="true"),Le||(process.removeAllListeners("warning"),process.on("warning",()=>{}));var{red:Oe,yellow:Ne}=t,Ue=__name((e="ERROR: ",t,r=!0,o=!0)=>{if(t){if(console.log(),r?(console.log(`${n.error} ${Oe(e)}`),console.log(`${n.error} ${Oe("ERROR →")} ${t.name}`),console.log(`${n.info} ${Oe("REASON →")} ${t.message}`),console.log(`${n.info} ${Oe("ERROR STACK ↓ \n")} ${t.stack}\n`)):console.log(`${n.warning} ${Ne(e)}\n`),!o)return!1;process.exit(0)}},"handleError");function handleUnhandledErrors(){process.on("unhandledRejection",t=>{Ue(e`CRITICAL: Unhandled Promise Rejection!
3
- This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,t)})}__name(handleUnhandledErrors,"handleUnhandledErrors");var je="--co",_e="--xco",Be=`x-${je.replace("--","")}-flag`,We="x-oauth-token",He="x-project-slug",ze="x-taste-learning",Ge={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"}}}},qe={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(qe.ALPHA.TASTE),Object.values(qe.BETA.TASTE_PACKAGES),Ge.ALPHA.GENERATE,Ge.ALPHA.AGENT.GENERATE,Ge.ALPHA.WHOAMI,Ge.ALPHA.NAMESPACES,Ge.ALPHA.SHARE.CREATE,Ge.ALPHA.SHARE.DELETE,Ge.ALPHA.SHARE.APPEND,Ge.ALPHA.DEVREL_THREAD.CREATE,Ge.ALPHA.DEVREL_THREAD.DELETE,Ge.ALPHA.DEVREL_THREAD.UPDATE,Ge.ALPHA.TASTE.LEARN,Ge.ALPHA.TASTE.DELETE,Ge.ALPHA.TASTE.GET,Ge.ALPHA.TASTE.UPDATE,Object.values(Ge.BETA.TASTE.PACKAGES),Object.values(qe.INTERNAL.ORGS),Object.values(qe.INTERNAL.USER),Object.values(qe.INTERNAL.TASTE.PACKAGES);var Ve={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"local"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}Object.values(Ve.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl");var Ke="anthropic";a.enum(["owner","admin","member"]);var Je="learn-taste",Ye={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:""}},Qe=Ye.SONNET_4_5.id;new Set([].map(e=>e.toLowerCase()));var Ze=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findAvailablePort(e=5959,t=10){for(let n=0;n<t;n++){const t=e+n;if(await checkPortAvailable(t))return t}throw new Error(`No available port found after ${t} attempts starting from port ${e}`)}async function checkPortAvailable(e){return new Promise(t=>{const n=_.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var Xe=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}};function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=j.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",c=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",c),o.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type"),o.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return o.writeHead(204),void o.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return o.writeHead(404),void o.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return o.writeHead(405),void o.end(JSON.stringify(e))}let l="";e.on("data",t=>{l+=t.toString(),l.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(l);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new Xe(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const a=e;if(!(a.apiKey&&a.state&&a.userId&&a.userName&&a.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(a.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const i={success:!0};o.writeHead(200),o.end(JSON.stringify(i)),n(a),s.close()}catch{const e={success:!1,error:"Invalid JSON"};o.writeHead(400),o.end(JSON.stringify(e))}}),e.on("error",()=>{o.writeHead(500),o.end(JSON.stringify({success:!1,error:"Request error"}))})});return s.on("error",e=>{r(e)}),s.listen(e,"127.0.0.1"),{server:s,waitForCallback:o}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer");var et=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),tt=__name(()=>{const e=et();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag");function getAuthDir(){return W.join(J.homedir(),".commandcode")}function getAuthFile(e){const t=e??et(),n="local"===t?"auth.local.json":"staging"===t?"auth.staging.json":"auth.json";return W.join(getAuthDir(),n)}function getConfigFile(e){const t=e??et(),n="local"===t?"config.local.json":"staging"===t?"config.staging.json":"config.json";return W.join(getAuthDir(),n)}function generateStateToken(){return F.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await U(e),!0}catch(e){return console.error("[CLI Auth] Failed to open browser:",e instanceof Error?e.message:"Unknown error"),!1}}function getStudioBaseUrl(){switch(et()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}__name(getAuthDir,"getAuthDir"),__name(getAuthFile,"getAuthFile"),__name(getConfigFile,"getConfigFile"),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var nt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}};async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await M.mkdir(t,{recursive:!0,mode:448});const r=JSON.stringify({apiKey:e.apiKey,userId:e.userId,userName:e.userName,keyName:e.keyName,authenticatedAt:e.authenticatedAt},null,2);await M.writeFile(n,r,{mode:384}),await M.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await M.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}function getApiBaseUrl(){const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials"),__name(getApiBaseUrl,"getApiBaseUrl");var rt=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${Ge.ALPHA.WHOAMI}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});return 401===n.status?{valid:!1,error:"invalid_key"}:n.ok?{valid:!0,user:await n.json()}:(process.env.DEBUG&&console.error(`API key validation failed with status ${n.status}`),{valid:!1,error:"server_error"})}catch(e){return process.env.DEBUG&&console.error("API key validation network error:",e),{valid:!1,error:"network_error"}}}function sanitizeApiKey(e){const t=String.fromCharCode(27),n=e.replaceAll(t+"[200~","").replaceAll(t+"[201~","").replaceAll("[200~","").replaceAll("[201~","");return Array.from(n).filter(e=>{const t=e.charCodeAt(0);return t>31&&127!==t}).join("").trim()}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=rt}=e,[s,a]=P("initializing"),[i,c]=P("Starting authentication..."),[l,d]=P(""),[u,m]=P(null),g=x(null),p=x(!1),h=x(!1),f=x(null),y=x(t),w=x(n),E=x(r);I(()=>{y.current=t,w.current=n,E.current=r});const b=$(()=>{f.current&&(clearTimeout(f.current),f.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),k=$(()=>{h.current||(h.current=!0,p.current=!0,b(),E.current())},[b]),S=$((e,t)=>{h.current||(h.current=!0,b(),y.current(e,t))},[b]),C=$((e,t)=>{h.current||(h.current=!0,b(),w.current(e,t))},[b]),v=$(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),c("Validating API key...");const n=await validateApiKey(t);if(p.current)return;if(h.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),c(e),void(f.current=setTimeout(()=>{p.current||h.current||(a("manual_entry"),c("Paste a valid API key below.")),f.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(h.current)return;await storeCredentials(e),a("success"),S(e,"manual")}catch(e){process.env.DEBUG&&console.error("Failed to store credentials:",e),c("Failed to save API key. Please try again."),a("manual_entry")}},[S]);return I(()=>{let e=!0;return __name(async()=>{if(!p.current)try{const t=await findAvailablePort(5959,10);if(!e||p.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);m(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(g.current=s,!e||p.current)return void await stopServer(s);a("waiting_browser"),c("Opening browser for authentication...");const l=await openBrowser(r);if(!e||p.current)return;if(!l)return b(),c("Could not open browser. Paste your API key below."),void a("manual_entry");c("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new nt("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||p.current)return;if(h.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(h.current)return;if(await storeCredentials(n),!e||p.current||h.current)return;a("browser_success"),S(n,"browser")}catch(t){if(h.current)return;if(!e||p.current)return;if(t instanceof Xe)return a("denied"),void C("denied","Authorization denied by user.");b(),t instanceof nt&&"TIMEOUT"===t.code?c("Browser auth timed out. Paste your API key below."):c("Browser auth failed. Paste your API key below."),a("manual_entry")}}catch(t){if(h.current)return;if(!e||p.current)return;process.env.DEBUG&&console.error("Browser auth startup failed:",t),b(),a("manual_entry"),c("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,b()}},[o,S,C,b]),{authState:s,statusMessage:i,browserUrl:u,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:v,cancel:k,hasCompleted:h.current}}__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow");var ot=/\s|[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWordBoundary(e){return!e||0===e.length||ot.test(e)}function findPreviousWordBoundary(e,t){if(!e||t<=0)return 0;let n=Math.min(t,e.length);for(;n>0&&isWordBoundary(e[n-1]||"");)n--;for(;n>0&&!isWordBoundary(e[n-1]||"");)n--;return n}function findNextWordBoundary(e,t){if(!e)return 0;if(t>=e.length)return e.length;let n=Math.max(0,t);for(;n<e.length&&isWordBoundary(e[n]||"");)n++;for(;n<e.length&&!isWordBoundary(e[n]||"");)n++;return n}function deleteWordBackwards(e,t){if(!e||t<=0)return{text:e||"",cursor:0};const n=findPreviousWordBoundary(e,t);return{text:e.slice(0,n)+e.slice(t),cursor:n}}function clampCursor(e,t){return Math.max(0,Math.min(e,t))}function findLineStart(e,t){if(!e||t<=0)return 0;for(let n=Math.min(t,e.length)-1;n>=0;n--)if("\n"===e[n])return n+1;return 0}function findLineEnd(e,t){if(!e)return 0;if(t>=e.length)return e.length;for(let n=Math.max(0,t);n<e.length;n++)if("\n"===e[n])return n;return e.length}function moveCursorUp(e,t){if(!e)return 0;const n=findLineStart(e,t);if(0===n)return t;const r=t-n,o=n-1,s=findLineStart(e,o),a=o-s;return s+Math.min(r,a)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const o=t-n,s=r+1,a=findLineEnd(e,s)-s;return s+Math.min(o,a)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}__name(isWordBoundary,"isWordBoundary"),__name(findPreviousWordBoundary,"findPreviousWordBoundary"),__name(findNextWordBoundary,"findNextWordBoundary"),__name(deleteWordBackwards,"deleteWordBackwards"),__name(clampCursor,"clampCursor"),__name(findLineStart,"findLineStart"),__name(findLineEnd,"findLineEnd"),__name(moveCursorUp,"moveCursorUp"),__name(moveCursorDown,"moveCursorDown"),__name(insertTextAt,"insertTextAt"),__name(deleteCharBefore,"deleteCharBefore"),__name(deleteCharAt,"deleteCharAt");var st=new Set(["","b","","",""]),at=new Set(["","f","","",""]),it=new Set(["","[1~","[7~","OH"]),ct=new Set(["","[4~","[8~","OF"]),lt=new Set(["[3~"]),dt=new Set(["",""]),ut=/^\x1b\[1;[359]D$/,mt=/^\x1b\[1;[359]C$/;function isWordLeftSequence(e){return!!st.has(e)||!!ut.test(e)}function isWordRightSequence(e){return!!at.has(e)||!!mt.test(e)}function isHomeSequence(e){return it.has(e)}function isEndSequence(e){return ct.has(e)}function isForwardDeleteSequence(e){return lt.has(e)}function isDeleteWordSequence(e){return dt.has(e)}function isCtrlA(e){return 1===e.length&&1===e.charCodeAt(0)}function isCtrlE(e){return 1===e.length&&5===e.charCodeAt(0)}function isCtrlK(e){return 1===e.length&&11===e.charCodeAt(0)}function isCtrlU(e){return 1===e.length&&21===e.charCodeAt(0)}function processWordLeft(e,t){return{value:e,cursor:findPreviousWordBoundary(e,t),handled:!0}}function processWordRight(e,t){return{value:e,cursor:findNextWordBoundary(e,t),handled:!0}}function processLineStart(e,t){return{value:e,cursor:findLineStart(e,t),handled:!0}}function processLineEnd(e,t){return{value:e,cursor:findLineEnd(e,t),handled:!0}}function processDeleteWord(e,t){const n=deleteWordBackwards(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processDeleteToEnd(e,t){const n=findLineEnd(e,t);return{value:e.slice(0,t)+e.slice(n),cursor:t,handled:!0}}function processDeleteToStart(e,t){const n=findLineStart(e,t);return{value:e.slice(0,n)+e.slice(t),cursor:n,handled:!0}}function processForwardDelete(e,t){const n=deleteCharAt(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processBackspace(e,t){const n=deleteCharBefore(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processCursorLeft(e,t,n){return n?t<=0?{value:e,cursor:t,handled:!0}:{value:e,cursor:t-1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorRight(e,t,n){return n?t>=e.length?{value:e,cursor:t,handled:!0}:{value:e,cursor:t+1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorUp(e,t,n){return n?{value:e,cursor:moveCursorUp(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorDown(e,t,n){return n?{value:e,cursor:moveCursorDown(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCharacterInput(e,t,n){const r=n.replace(/[\x00-\x1F\x7F]|\x1b.*/g,"");if(0===r.length)return{value:e,cursor:t,handled:!1};const o=insertTextAt(e,t,r);return{value:o.text,cursor:o.cursor,handled:!0}}function processRawInput(e,t,n){return isWordLeftSequence(e)?processWordLeft(t,n):isWordRightSequence(e)?processWordRight(t,n):isHomeSequence(e)?processLineStart(t,n):isEndSequence(e)?processLineEnd(t,n):isCtrlA(e)?processLineStart(t,n):isCtrlE(e)?processLineEnd(t,n):isDeleteWordSequence(e)?processDeleteWord(t,n):isCtrlK(e)?processDeleteToEnd(t,n):isCtrlU(e)?processDeleteToStart(t,n):isForwardDeleteSequence(e)?processForwardDelete(t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(processWordLeft,"processWordLeft"),__name(processWordRight,"processWordRight"),__name(processLineStart,"processLineStart"),__name(processLineEnd,"processLineEnd"),__name(processDeleteWord,"processDeleteWord"),__name(processDeleteToEnd,"processDeleteToEnd"),__name(processDeleteToStart,"processDeleteToStart"),__name(processForwardDelete,"processForwardDelete"),__name(processBackspace,"processBackspace"),__name(processCursorLeft,"processCursorLeft"),__name(processCursorRight,"processCursorRight"),__name(processCursorUp,"processCursorUp"),__name(processCursorDown,"processCursorDown"),__name(processCharacterInput,"processCharacterInput"),__name(processRawInput,"processRawInput"),__name(isIgnoredKey,"isIgnoredKey"),__name(processInkInput,"processInkInput");var gt=!1,pt=[],ht=null;function startEarlyInputCapture(){gt||(gt=!0,pt=[],ht=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&pt.push(t)},"earlyInputHandler"),process.stdin.on("data",ht))}function stopEarlyInputCapture(){gt&&ht&&(process.stdin.off("data",ht),ht=null,gt=!1)}function consumeBufferedInput(){const e=pt.join("");return pt=[],e}function hasBufferedInput(){return pt.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}function useCursorState({value:e,focus:t,showCursor:n}){const[r,o]=P((e||"").length),s=x(r);I(()=>{s.current=r},[r]),I(()=>{if(!t)return;if(!n)return;const s=(e||"").length;r>s&&o(s)},[e,t,n,r]);const a=$(e=>{o(e),s.current=e},[]);return{cursor:r,setCursor:a,cursorRef:s}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o}){const s=x(!1);I(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{const s=processRawInput(e.toString(),t.current,n.current);if(!s.handled)return;o(!0);const a=clampCursor(s.cursor,s.value.length);r(s.value,a),setTimeout(()=>o(!1),0)},"handleRawInput");if(a.on("data",i),!s.current&&hasBufferedInput()){s.current=!0;const e=consumeBufferedInput();e&&i(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",i)}},[e,t,n,r,o])}function useInkInputHandler({focus:e,showCursor:t,value:n,cursor:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){k((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n);const c=processInkInput(e,i,n,r,t);if(!c.handled)return;const l=clampCursor(c.cursor,c.value.length);s(c.value,l)},{isActive:e})}function useSyncedRef(e){const t=x(e);return I(()=>{t.current=e},[e]),t}function renderPlaceholder(e,n){return n?0===e.length?t.inverse(" "):t.inverse(e[0])+t.grey(e.slice(1)):t.grey(e)}function renderValue(e,n,r){if(!r)return e;if(0===e.length)return t.inverse(" ");let o="";for(let r=0;r<e.length;r++)r===n?"\n"===e[r]?o+=t.inverse(" ")+"\n":o+=t.inverse(e[r]):o+=e[r];return n===e.length&&(o+=t.inverse(" ")),o}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(Y(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",c=0,l=!0;for(const e of a){const t=Y(e).length;c+t>(l?s:o)&&c>0&&(i+="\n"+r,c=n,l=!1),i+=e,c+=t}return i}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}function createStdinUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t&&n(r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:a,onCursorChange:i,prefix:c="",prefixColor:l}){const d=x(!1),u=useSyncedRef(e),m=useSyncedRef(s),{cursor:g,setCursor:p,cursorRef:h}=useCursorState({value:e,focus:n,showCursor:o});A.useEffect(()=>{i?.(g)},[g,i]);const f=$(createStdinUpdateHandler(p,u,m),[p,u,m]),y=$(()=>createInkUpdateHandler(p,e,s),[p,e,s])(),E=$(e=>{d.current=e},[]),b=$(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:u,cursorRef:h,onUpdate:f,setHandled:E}),useInkInputHandler({focus:n,showCursor:o,value:e,cursor:g,isHandledByStdin:b,onUpdate:y,onSubmit:a});const{stdout:k}=C(),S=k?.columns??80,v=getMaskedValue(e,r),P=wrapWithIndent(__name(()=>{if(!c)return"";if(!l)return c;const e={white:T.white,green:T.green,red:T.red,blue:T.blue,yellow:T.yellow,cyan:T.cyan,magenta:T.magenta,gray:T.gray,grey:T.gray}[l];return e?e(c):c},"getColoredPrefix")()+getDisplayValue(v,t,g,o,n),S,c?.length??0);return A.createElement(w,{wrap:"wrap"},P)}function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){switch(e){case"waiting_browser":return"Authorize in browser, or paste API key here";case"invalid_key":return"That key was invalid. Try again.";default:return"Paste your API key and press Enter"}}function getAuthUrlLabel(e){return"waiting_browser"===e?"Authenticating via:":"Get your API key from:"}__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip"),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue"),__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput"),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var ft,yt,wt=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})=>{const i=__name(()=>{switch(e){case"initializing":case"waiting_browser":case"validating":default:return A.createElement(v,{type:"dots"});case"browser_success":case"success":return A.createElement(w,{color:"green"},r.tick);case"denied":case"invalid_key":return A.createElement(w,{color:"red"},r.cross);case"manual_entry":return A.createElement(w,{color:"yellow"},r.arrowDown);case"error":return A.createElement(w,{color:"red"},r.warning)}},"getStatusIcon"),c=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const l="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,d=n&&("waiting_browser"===e||"manual_entry"===e);return A.createElement(y,{flexDirection:"column",paddingY:1},A.createElement(y,{marginBottom:1},A.createElement(y,{marginRight:1},i()),A.createElement(w,{color:c()},t)),l&&A.createElement(y,{flexDirection:"column"},A.createElement(y,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},A.createElement(w,{dimColor:!0},"API Key: "),A.createElement(y,{flexGrow:1},A.createElement(TextInput,{value:o,onChange:s,onSubmit:a,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},getAuthHelpText(e))),d&&A.createElement(y,{marginTop:1,flexDirection:"column"},A.createElement(w,{dimColor:!0},getAuthUrlLabel(e)),A.createElement(w,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(et())))),"validating"===e&&A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),Et=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a,cancel:i}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return k((e,t)=>{t.ctrl&&"c"===e&&i()}),A.createElement(wt,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey"),bt="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing";function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${T.bgGreen(T.black(` ${e} `))}${o}`:n?`${T.bgBlack(T.white(` ${e} `))}${o}`:`${T.bold(T.bgCyan(T.black(` ${e} `)))}${o}`}async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=ae(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=1200;let i,c,{width:l,height:d}=s;(l>a||d>a)&&(l>d?(d=Math.round(d*a/l),l=a):(l=Math.round(l*a/d),d=a)),t.includes("png")&&s.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:u,compressionRatio:r/u}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}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,o,s=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");if(s=s.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){r=e.slice(0,t.index);const s=e.slice(t.index+t[0].length);if(n){const e=s.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=s.slice(0,e.index))}else o=s}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:s,textBeforePaste:r,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}__name(heading,"heading"),(e=>{e.OAuth=i.object({type:i.literal("oauth"),refresh:i.string(),access:i.string(),expires:i.number()}),e.ApiKey=i.object({type:i.literal("api"),key:i.string()}),e.Info=i.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>W.join(J.homedir(),".commandcode"),"getAuthDir"),n=__name(()=>{const e=et(),n="local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json";return W.join(t(),n)},"getAuthFile");async function get(e){try{const t=await L.readFile(n(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,r){const o=t(),s=n();await L.mkdir(o,{recursive:!0});let a={};try{const e=await L.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=r,await L.writeFile(s,JSON.stringify(a,null,2)),await L.chmod(s,384)}async function remove(e){const t=n();try{const n=await L.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await L.unlink(t):(await L.writeFile(t,JSON.stringify(r,null,2)),await L.chmod(t,384))}catch{}}async function list2(){try{const e=await L.readFile(n(),"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")})(ft||(ft={})),(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 R.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return R.createHash("sha256").update(e).digest("base64url")}function generateState(){return R.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,s){const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!a.ok){const e=await a.text();throw new Error(`Token exchange failed: ${e}`)}const i=await a.json();await ft.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 ft.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 ft.remove("anthropic");const o=await r.json();return await ft.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 ft.remove("anthropic")}}}async function getValidAccessToken(){const e=await ft.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")})(yt||(yt={})),__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var kt=B.join(K.homedir(),".commandcode","logs"),St=B.join(kt,"command.log"),Ct={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",default:"-"};function getIcon(e){if(Ct[e])return Ct[e];const t=e.split(":")[0];return Ct[t]?Ct[t]:Ct.default}function formatTime(e){return`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`}function parseMessage(e){const t=e.match(/^\[([^\]]+)\]\s*(.*)/);return t?{category:t[1],text:t[2]}:{category:"",text:e}}__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage");var vt=!1;function showStartup(){if(!vt){vt=!0;try{Q.mkdirSync(kt,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${St}\n════════════════════════════════════════════════════════════════\n\n`;Q.appendFileSync(St,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${Ct.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",Q.appendFileSync(St,s,"utf-8")}catch{}}}function dlogSection(e){if("true"===process.env.DEBUG){showStartup();try{const t=`\n──── ${e} ${"─".repeat(Math.max(0,50-e.length))}\n`;Q.appendFileSync(St,t,"utf-8")}catch{}}}function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${J.platform()}-${J.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 Z.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 ie("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return ie("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim()}catch{return""}}function getMainBranch(){try{const e=ie("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=ie("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory()}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),n=t.filter(e=>e.startsWith(" M")).length,r=t.filter(e=>e.startsWith("A ")).length,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,a=[];return n>0&&a.push(`M ${n}`),r>0&&a.push(`A ${r}`),o>0&&a.push(`D ${o}`),s>0&&a.push(`?? ${s}`),a.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=ie("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("ghostty"===t)return{name:"Ghostty",type:"ghostty",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}function isInternalTeamDisableOAuthFlagPresent(){return process.argv.includes(_e)}function formatDate(e=new Date){return e.toISOString().split("T")[0]}function parseJSON(e){try{return JSON.parse(e)}catch{return null}}async function getConfiguredProvider(){try{const e=getConfigFile(),t=await L.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):s||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!e.ctrl||"o"!==t)}function formatTime2(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function formatTokens(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}async function loadUserConfig(){try{const e=getConfigFile();return parseJSON(await M.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();Q.writeFileSync(t,JSON.stringify(e,null,2)),Q.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})}__name(showStartup,"showStartup"),"true"===process.env.DEBUG&&showStartup(),__name(dlog,"dlog"),__name(dlogSection,"dlogSection"),__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(isInternalTeamDisableOAuthFlagPresent,"isInternalTeamDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut"),__name(formatTime2,"formatTime"),__name(formatTokens,"formatTokens"),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning");var Tt=null;async function isOAuthEnforced(){if(null!==Tt)return Tt;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),Tt=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),Tt=!0,!0;const e=await loadUserConfig();return(Tt=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),Tt}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=getConfigFile();return(parseJSON(Q.readFileSync(e,"utf-8"))||{}).model??Qe}catch{return Qe}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel");var At=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=P(""),[s,a]=P(null),[i,c]=P(!1),[l,d]=P(null),[u,m]=P(!0),[g,p]=P(!1),[h,f]=P(!1);I(()=>{const{url:e,verifier:t,state:n}=yt.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const E=$(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||h){if(!h||t.isPasteEnd){if(h&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}},[h]);k((e,n)=>{if(n.escape&&t(),u&&!g)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;U(s.url).then(()=>{p(!0),m(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),p(!0),m(!1)})}});const b=__name(async()=>{if(r.trim()&&s&&!i){c(!0),d(null);try{const t=r.split("#")[0].trim();await yt.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),c(!1),n&&n(t)}}},"handleSubmit");return u&&!g?A.createElement(y,{flexDirection:"column"},A.createElement(y,{marginBottom:1},A.createElement(w,{bold:!0,color:"cyan"},"Anthropic Authentication")),A.createElement(y,{marginBottom:1},A.createElement(w,null,"Open the Anthropic auth page?",A.createElement(w,{dimColor:!0}," (Y/n)")))):A.createElement(y,{flexDirection:"column"},A.createElement(y,{marginBottom:1},A.createElement(w,{bold:!0,color:"cyan"},"Anthropic Authentication")),A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"After authorizing, copy the code and paste it below:")),l&&A.createElement(y,{marginBottom:1},A.createElement(w,{color:"red"},"Error: ",l)),A.createElement(y,null,A.createElement(w,null,"Authorization code: "),A.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:E,onSubmit:b,placeholder:"Paste code here..."})),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth"),Pt={"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:At,checkAuth:__name(async()=>!!await yt.getValidAccessToken(),"checkAuth")}};function getProviderDisplayName(e){if(!e)return"None";const t=Pt[e];return t?.displayName||e}function getProviderConfig(e){return Pt[e]}function isInternalTeamFlagPresent(){return process.argv.includes(je)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(_e)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(Q.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(Pt).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=yt.createAuthorizationUrl(),r=await h({message:"Open the Anthropic auth page?"});if(g(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await U(e),console.log(),console.log(T.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(T.dim(" Open this URL in your browser:")),console.log(),console.log(T.cyan(` ${e}`)),console.log(),console.log(T.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await f({message:"Paste your authorization code:",mask:"*"});if(g(o))return{success:!1,error:"No API key provided"};if(!o.trim())return{success:!1,error:"No authorization code provided"};const s=o.split("#")[0].trim();return await yt.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalTeamFlagPresent,"isInternalTeamFlagPresent"),__name(isInternalTeamDisableFlagPresent,"isInternalTeamDisableFlagPresent"),__name(isInternalTeamFlagEnforced,"isInternalTeamFlagEnforced"),__name(getProviderOptions,"getProviderOptions"),__name(performAnthropicAuth,"performAnthropicAuth");var xt=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},It=class extends Error{static{__name(this,"AuthorizationDeniedError")}constructor(e){super(e),this.name="AuthorizationDeniedError"}};async function readAuthFile(e){try{const t=getAuthFile(e),n=await L.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async function getAuthKey(e){const t=await readAuthFile(e);return t&&t.apiKey||null}async function checkAuthStatus(e){const t=await readAuthFile(e);return t&&t.apiKey?{authenticated:!0,apiKey:t.apiKey,userName:t.userName}:{authenticated:!1,apiKey:null}}async function statusAction(){const e=de("Checking authentication status...").start();try{const t=et(),n=await checkAuthStatus(t);n.error&&(e.fail(T.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(T.red("Not authenticated")),console.log(""),console.log(`${T.dim("Run")} ${T.cyan("cmd auth login")} ${T.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${T.green(r.tick)} ${T.bold("Authenticated")} with ${T.cyan("Command Code")}`),n.userName&&console.log(`${T.dim("Logged in as")} ${T.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(T.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var $t=new c("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),Dt=__name(({message:e})=>A.createElement(A.Fragment,null,A.createElement(w,{color:"cyan"},A.createElement(v,{type:"dots"})),A.createElement(w,null," ",e)),"LoadingIndicator"),Ft=__name(({message:e})=>A.createElement(A.Fragment,null,A.createElement(w,{color:"green"},r.tick),A.createElement(w,null," ",e)),"SuccessIndicator"),Rt=__name(({children:e})=>A.createElement(y,{flexDirection:"column"},A.createElement(w,null," "),A.createElement(y,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=P("loading"),[i,c]=P(null);return I(()=>{n().then(e=>{c(e),a(o?"success":"done")})},[n,o]),I(()=>{if("done"===s&&null!==i&&r(i),"success"===s&&null!==i){const e=setTimeout(()=>r(i),100);return()=>clearTimeout(e)}},[s,i,r]),"done"===s?null:A.createElement(Rt,null,"loading"===s?A.createElement(Dt,{message:e}):A.createElement(Ft,{message:t}))}async function checkExistingAuth(e){const t=await checkAuthStatus(e);return t.authenticated?{isAuthenticated:!0,userName:t.userName}:{isAuthenticated:!1}}function getAuthFileName(e){return"local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json"}function isGenericUserName(e){return!e||"API Key"===e}function isGenericUserNameForOutro(e){return isGenericUserName(e)||"Manual API Key"===e}function formatUserDisplay(e,t=!1){return(t?isGenericUserNameForOutro(e):isGenericUserName(e))?t?" successfully":"":` as ${T.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${T.green(r.tick)} ${T.bold("Already logged in")}${t}`,"",`${T.dim("Run")} ${T.cyan("cmd")} ${T.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${T.green(r.tick)} ${T.bold("Logged in")}${n}`,"",`${T.dim("API key stored in")} ${T.cyan(`~/.commandcode/${t}`)}`,`${T.dim("Run")} ${T.cyan("cmd")} ${T.dim("to get started.")}`].join("\n")}function isLoginSuccess(e){return e.success}function isLoginDenied(e){return"denied"===e.reason}function isLoginCancelled(e){return"cancelled"===e.reason}function createLoginError(e){return isLoginDenied(e)?new It(e.message):isLoginCancelled(e)?new xt(e.message):new Error(e.message)}function processLoginResult(e){return isLoginSuccess(e)?{success:!0,userName:e.config?.userName}:{success:!1,error:createLoginError(e)}}function needsProviderSelection(e){return e.length>1}function getDefaultProvider(e){return e[0]?.value??""}function isAnthropicProvider(e){return"anthropic"===e}function isUserCancellation(e){return e instanceof xt||e instanceof It}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),d.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await m({message:"Select provider",options:e});if(g(t))throw u(`${r.cross} No provider selected.`),new xt("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){u(`${r.cross} ${e}`)}function showAnthropicAuthNote(){p("Command Code authentication complete. Now authenticating with Anthropic...")}function printMessage(e){console.log(""),console.log(e),console.log("")}function renderTaskWithSpinner(e,t,n,r=!0){return new Promise(o=>{const s=__name(e=>{a(),o(e)},"handleComplete"),{unmount:a}=b(A.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:s,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=b(A.createElement(Et,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__name(isGenericUserName,"isGenericUserName"),__name(isGenericUserNameForOutro,"isGenericUserNameForOutro"),__name(formatUserDisplay,"formatUserDisplay"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(isLoginSuccess,"isLoginSuccess"),__name(isLoginDenied,"isLoginDenied"),__name(isLoginCancelled,"isLoginCancelled"),__name(createLoginError,"createLoginError"),__name(processLoginResult,"processLoginResult"),__name(needsProviderSelection,"needsProviderSelection"),__name(getDefaultProvider,"getDefaultProvider"),__name(isAnthropicProvider,"isAnthropicProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage,"getErrorMessage"),__name(showAuthIntro,"showAuthIntro"),__name(promptProviderSelection,"promptProviderSelection"),__name(selectProvider,"selectProvider"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(showAnthropicAuthNote,"showAnthropicAuthNote"),__name(printMessage,"printMessage"),__name(renderTaskWithSpinner,"renderTaskWithSpinner"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var Mt=__name(({env:e,onComplete:t})=>{const[n,r]=P("checking"),[o,s]=P(null);return I(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),I(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),A.createElement(Rt,null,"checking"===n&&A.createElement(Dt,{message:"Checking authentication status..."}),"logged_in"===n&&A.createElement(Ft,{message:"Authenticated"}),"not_logged_in"===n&&A.createElement(Ft,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=b(A.createElement(Mt,{env:e,onComplete:e=>{n(),t(e)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function saveConfigWithSpinner(e){await renderTaskWithSpinner("Saving configuration...","Configuration saved",()=>updateUserConfig({provider:e}),!0)}async function executeLoginFlow(){const e=processLoginResult(await runLoginWithApiKeyFlow());if(!e.success)throw showLoginCancelMessage(e.error.message),e.error;return e.userName}async function handleAnthropicAuth(e){isAnthropicProvider(e)&&(showAnthropicAuthNote(),await performAnthropicAuth())}async function finalizeLogin(e,t,n){await saveConfigWithSpinner(e),printMessage(buildSuccessMessage(t,getAuthFileName(n)))}async function runLogin(){const e=et(),t=await checkAuthWithSpinner(e);if(t.isAuthenticated)return printMessage(buildAlreadyLoggedInMessage(t.userName)),!0;showAuthIntro();const n=await executeLoginFlow();let r="command-code";return isInternalTeamFlagEnforced()&&(r=await selectProvider(),await handleAnthropicAuth(r)),await finalizeLogin(r,n,e),!0}async function loginAction(){try{await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${r.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var Lt=new c("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await L.unlink(e),{existed:!0}}catch(e){return"ENOENT"===e.code?{existed:!1}:{existed:!0,warning:`Could not remove ${t}: ${e.message}`}}}function collectWarnings(...e){return e.map(e=>e.warning).filter(e=>void 0!==e)}async function performLogout(){try{const e=await safeRemoveFile(getAuthFile(),"auth file"),t=collectWarnings(e);return{success:!0,wasAuthenticated:e.existed,warnings:t}}catch(e){return{success:!1,wasAuthenticated:!1,warnings:[],error:e instanceof Error?e.message:"Unknown error"}}}__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var Ot=__name(()=>A.createElement(A.Fragment,null,A.createElement(w,{color:"cyan"},A.createElement(v,{type:"dots"})),A.createElement(w,null," Logging out...")),"LoadingIndicator"),Nt=__name(()=>A.createElement(A.Fragment,null,A.createElement(w,{color:"green"},r.tick),A.createElement(w,null," Logged out")),"SuccessIndicator"),Ut=__name(({errorMessage:e})=>A.createElement(A.Fragment,null,A.createElement(w,{color:"red"},r.cross),A.createElement(w,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),jt=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return A.createElement(Ot,null);case"success":return A.createElement(Nt,null);case"error":return A.createElement(Ut,{errorMessage:t})}},"StatusDisplay"),_t=__name(({onComplete:e})=>{const[t,n]=P("loading"),[r,o]=P(""),[s,a]=P(null);return I(()=>{performLogout().then(e=>{a(e),e.success?n("success"):(o(e.error||"Unknown error"),n("error"))})},[]),I(()=>{if(("success"===t||"error"===t)&&s){const t=setTimeout(()=>e(s),100);return()=>clearTimeout(t)}},[t,s,e]),A.createElement(y,{flexDirection:"column"},A.createElement(w,null," "),A.createElement(y,null,A.createElement(jt,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(T.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(T.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=b(A.createElement(_t,{onComplete:n=>{t(),e(n)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var Bt=new c("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);new c("auth").description("Manage authentication with Command Code").addCommand(Lt).addCommand(Bt).addCommand($t);var Wt="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",Ht="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n";function getMaxLineWidth(e){return Math.max(...e.split("\n").map(e=>e.length))}__name(getMaxLineWidth,"getMaxLineWidth");var zt=getMaxLineWidth(Wt),Gt=getMaxLineWidth(Ht),qt=zt+1,Vt=Gt+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var Kt=__name(e=>{const t=e??getTerminalWidth();return t>=qt?Wt:t>=Vt?Ht:Jt},"getResponsiveCommandLogo"),Jt="⌘ CMD\n",Yt=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),Qt=__name(e=>{console.log(t.white(Kt())),console.log(""),console.log(`${r.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),Zt=__name(async e=>{const t=s.createInterface({input:process.stdin,output:process.stdout});try{const n=await t.question(e);return t.close(),{answer:n,cancelled:!1}}catch{return t.close(),{answer:"",cancelled:!0}}},"promptYesNo"),Xt=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${r.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),en=__name(()=>{console.log(""),console.log(`${r.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),tn=__name(()=>{console.log(""),console.log(`${r.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;Qt(tt());const{answer:e,cancelled:n}=await Zt(`Would you like to sign in now? ${t.dim("(y/n)")}: `);return n?(tn(),!1):Yt(e)?(console.log(""),Xt()):(en(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var nn=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(!W.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=W.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=W.basename(e);return W.dirname(e),this.isUserPath(e)?`<user-home>/${W.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))}},rn=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 on({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new sn(e,o,n,r);case 401:return new an(e,o,n,r);case 403:return new cn(e,o,n,r);case 404:return new ln(e,o,n,r);case 409:return new dn(e,o,n,r);case 422:return new un(e,o,n,r);case 429:return new mn(e,o,n,r);default:return e>=500?new gn(e,o,n,r):new _APIError(e,o,n,r)}}},on=class extends rn{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)}},sn=class extends rn{static{__name(this,"BadRequestError")}status=400},an=class extends rn{static{__name(this,"AuthenticationError")}status=401},cn=class extends rn{static{__name(this,"PermissionDeniedError")}status=403},ln=class extends rn{static{__name(this,"NotFoundError")}status=404},dn=class extends rn{static{__name(this,"ConflictError")}status=409},un=class extends rn{static{__name(this,"UnprocessableEntityError")}status=422},mn=class extends rn{static{__name(this,"RateLimitError")}status=429},gn=class extends rn{static{__name(this,"InternalServerError")}},pn=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 on({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 s=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};throw e.headers.forEach((e,t)=>{n[t]=e}),rn.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"})}},hn=i.object({name:i.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:i.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:i.string().optional(),compatibility:i.array(i.string()).optional(),metadata:i.record(i.string(),i.any()).optional(),"allowed-tools":i.array(i.string()).optional()});function getPersonalSkillsDir(){return W.join(J.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return W.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:t}=e;try{await L.access(t);const e=(await L.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory());return(await Promise.all(e.map(async e=>{try{const n=W.join(t,e.name,"SKILL.md");await L.access(n);const r=await L.readFile(n,"utf-8"),{data:o}=me(r),s=hn.parse(o);return{name:s.name,description:s.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=W.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)}i.object({name:i.string(),description:i.string(),license:i.string().optional(),compatibility:i.array(i.string()).optional(),metadata:i.record(i.string(),i.any()).optional(),"allowed-tools":i.array(i.string()).optional(),content:i.string(),filePath:i.string()}),i.object({name:i.string(),description:i.string(),filePath:i.string()}),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var fn=i.object({absolutePath:i.string().describe("The absolute path to the file to read"),offset:i.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:i.number().optional().describe("Optional number of lines to read")});i.object({content:i.union([i.string(),i.instanceof(Buffer)]),contentType:i.enum(["text","binary"]),fileType:i.string(),size:i.number(),linesRead:i.number().optional()});var yn=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(!B.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new yn("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=B.normalize(t);try{await M.access(o,Q.constants.F_OK|Q.constants.R_OK)}catch{throw new yn(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await M.stat(o)).isFile())throw new yn("Path does not point to a file","NOT_A_FILE");const s=getFileType(o),a=isBinaryFile(s);if(void 0!==n&&void 0===r||void 0===n&&void 0!==r)throw new yn("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new yn("Offset must be >= 0","INVALID_OFFSET");if(void 0!==r&&r<=0)throw new yn("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await M.readFile(o);return{fileType:s,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==r){const e=await readTextFileLines(o,n,r);return{fileType:s,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await M.readFile(o,"utf8");return{content:e,fileType:s,contentType:"text",size:e.length}}}catch(e){if(e instanceof yn)throw e;throw new yn(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var wn={".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=B.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",...wn}[t]||"unknown"}function isBinaryFile(e){return Object.values(wn).includes(e)}async function readTextFileLines(e,t,n){const r=(await M.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),a=r.slice(o,s);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(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=B.isAbsolute(o)?o:B.resolve(process.cwd(),o),s=await readFileContent({absolutePath:e});if("binary"===s.contentType)continue;const a=String(s.content),i=B.relative(process.cwd(),e),c=1e5;if(a.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:a});const l=`{${i}: ${a}}`;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=`{${B.relative(process.cwd(),e.resolvedPath)}: ${e.content}}`;n=n.replace(e.token,t)}return n}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent");var En="read_file",bn="edit_file",kn="write_file",Sn="read_directory",Cn="read_multiple_files",vn="grep",Tn="shell_command",An="think",Pn="todo_write",xn="ask_user_question",In="kill_shell",$n="web_search",Dn="web_fetch",Fn=__name(e=>e===$n,"isWebSearchTool");function toRelativePath(e){const t=global.COMMAND_CODE_CWD||process.cwd(),n=process.env.HOME||process.env.USERPROFILE||"",r=B.relative(t,e);return r.startsWith("..")?n&&e.startsWith(n)?e.replace(n,"~"):e:""===r?B.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=>B.isAbsolute(e)?toRelativePath(e):e),t=t.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),t}__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var Rn=i.object({id:i.string(),timestamp:i.number(),type:i.literal("image"),source:i.object({type:i.enum(["base64","url"]),media_type:i.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:i.string()})}),Mn=i.object({id:i.string(),timestamp:i.number(),input:i.string(),output:i.string().optional(),metadata:i.record(i.string(),i.any()).optional(),images:i.array(Rn).optional().default([])}),Ln=Mn.extend({role:i.literal("user")}),On=Mn.extend({role:i.literal("assistant")}),Nn=Mn.extend({role:i.literal("tool"),name:i.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),Un=Mn.extend({role:i.literal("bash"),command:i.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),jn=Mn.extend({role:i.literal("system")}),_n=Mn.extend({role:i.literal("error")}),Bn=Mn.extend({role:i.literal("info")}),Wn=Mn.extend({role:i.literal("taste-onboarding")}),Hn=Mn.extend({role:i.literal("command-result"),hasError:i.boolean().optional(),details:i.string().optional()}),zn=i.discriminatedUnion("role",[Ln,On,Nn,Un,jn,_n,Bn,Wn,Hn]),Gn=__name((e,t)=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),qn=__name(e=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),Vn=__name(e=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),Kn=__name((e,t,n)=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Jn=__name(e=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),Yn=__name(e=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),Qn=__name(e=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),Zn=__name(()=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Xn=__name((e,t=!1,n)=>zn.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),er=__name(({name:e,input:t})=>{const n=Date.now();return zn.parse({id:crypto.randomUUID(),timestamp:n,role:"tool",name:e,input:t,output:void 0,metadata:{isAgent:!0,status:"running",startTime:n,tokensUsed:0}})},"createAgentToolEntry"),tr=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return zn.parse(n)},"updateEntryWithOutput"),nr=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),rr=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),or=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),sr=["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…"],ar=__name(()=>sr[Math.floor(Math.random()*sr.length)],"getRandomLLMStatus"),ir=__name(e=>{switch(e){case En:return"Read";case bn:return"Edit";case kn:return"Write";case Sn:return"List";case Cn:return"Read Multiple";case vn:return"Search";case Tn:return"Shell";case Pn:return"Todos";case An:return"Thinking…";case $n:return"Web Search";case Dn:return"Web Fetch";case xn:return"Question";case"explore":return"Explore";case In:return"Kill Shell";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),cr=__name((e,t)=>{try{switch(e){case En:case kn:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case bn:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Sn:return toRelativePath(t.path||"directory");case vn:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case Tn: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 Pn:let r;try{r="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=lr(r);return`${e?e.length:0} items`}catch{return"items"}case An:return t.content||"planning";case Cn:const o=t.include||[];return Array.isArray(o)?o.join(", "):"multiple files";case $n:return t.query||"search";case Dn:return t.url||"fetch";case xn:return"User answered questions";case In:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";default:{let e=t?.messages||[];if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return JSON.stringify(t||{})}if(Array.isArray(e)&&e.length>0&&e[0]&&"object"==typeof e[0]&&"content"in e[0]){const t=e[0].content;if("string"==typeof t){const e=t.trim(),n=e.indexOf("."),r=n>0?e.slice(0,n):e;return r.length>80?r.slice(0,80)+"...":r}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),lr=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput");function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(formatOutput,"formatOutput");var dr={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=fn.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${r.cross} Error: ${e.message}`:`${r.cross} Error: Unknown error occurred while reading file`}},"execute")},ur=i.object({filePath:i.string().describe("The absolute path to the file to edit"),oldValue:i.string().describe("The text to replace"),newValue:i.string().describe("The new text to insert"),replacementCount:i.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:i.boolean().optional().describe("Whether to replace all occurrences (default: false)")});i.object({path:i.string(),replacementsCount:i.number(),oldContent:i.string(),newContent:i.string()}),i.object({name:i.string(),message:i.string(),code:i.string().optional()});var mr=i.object({backupFileName:i.string().nullable(),version:i.number().int().positive(),backupTime:i.string().datetime()}),gr=i.object({messageId:i.string().uuid(),trackedFileBackups:i.record(i.string(),mr),timestamp:i.string().datetime()});i.object({type:i.literal("file-history-snapshot"),messageId:i.string().uuid(),snapshot:gr,isSnapshotUpdate:i.boolean()}),i.object({maxFileSize:i.number().int().positive().default(10485760),retentionDays:i.number().int().positive().default(30)});var pr=class extends Error{static{__name(this,"CheckpointError")}code;constructor(e,t){super(e),this.name="CheckpointError",this.code=t}};function getPathHash(e){const{filePath:t}=e;return`${R.createHash("sha256").update(t).digest("hex").slice(0,16)}-${t.length}`}function getBackupFileName(e){const{filePath:t,version:n}=e;return`${getPathHash({filePath:t})}@v${n}`}function getCommandCodeBasePath(){return W.join(J.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:t}=e;return W.join(getCommandCodeBasePath(),"file-history",t)}function getBackupFilePath(e){const{sessionId:t,backupFileName:n}=e;return W.join(getFileHistoryPath({sessionId:t}),n)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await L.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,o=await getAvailableDiskSpace({targetPath:n});return-1===o||o>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await L.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await L.writeFile(r,n);const e=await L.stat(r),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 L.rename(r,t)}catch(e){try{await L.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await L.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await L.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function 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),s=Math.floor(o/60),a=Math.floor(s/24);return a>0?`${a}d ago`:s>0?`${s}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:t}=e;return W.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 hr={maxFileSize:10485760,retentionDays:30},fr=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...hr,...n},this.status={enabled:!0,pausedReason:null,pausedAt:null},this.trackedState={files:new Map,versions:new Map},this.noticeDismissed=!1}getStatus(){return{...this.status}}getTrackedState(){return{files:new Map(this.trackedState.files),versions:new Map(this.trackedState.versions)}}shouldShowPausedNotice(){return null!==this.status.pausedReason&&!this.noticeDismissed}dismissPausedNotice(){this.noticeDismissed=!0}async checkAndResumeIfPossible(){if("disk_full"===this.status.pausedReason){const e=getFileHistoryPath({sessionId:this.sessionId});await hasEnoughDiskSpace({fileSizeBytes:104857600,targetPath:e})&&(this.status.pausedReason=null,this.status.pausedAt=null,this.noticeDismissed=!1)}}async backupFile(e){const{filePath:t}=e;if(await this.checkAndResumeIfPossible(),this.status.pausedReason)return{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};if(!await fileExists({filePath:t})){const e=1,n={backupFileName:null,version:e,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,n),this.trackedState.versions.set(t,e),{success:!0,backup:n,skipped:!0,skipReason:"new_file"}}const n=await getFileSizeBytes({filePath:t});if(n>this.config.maxFileSize)return{success:!1,backup:null,skipped:!0,skipReason:"file_too_large"};const r=getFileHistoryPath({sessionId:this.sessionId});if(!await hasEnoughDiskSpace({fileSizeBytes:n,targetPath:r}))return this.status.pausedReason="disk_full",this.status.pausedAt=getCurrentTimestamp(),this.noticeDismissed=!1,{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};try{const e=await L.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const s=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:s,content:e});const a={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,a),this.trackedState.versions.set(t,n),{success:!0,backup:a,skipped:!1}}catch(e){return{success:!1,backup:null,skipped:!0,skipReason:"read_error"}}}async restoreFile(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName)return void(await fileExists({filePath:t})&&await L.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r}))throw new pr(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");const o=await L.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 L.access(t,L.constants.W_OK),{canRestore:!0}}catch{return{canRestore:!1,error:"Cannot delete file: permission denied"}}}const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});return await fileExists({filePath:r})?{canRestore:!0}:{canRestore:!1,error:`Backup file missing: ${n.backupFileName}`}}getTrackedFileBackups(){const e={};for(const[t,n]of this.trackedState.files)e[t]=n;return e}loadTrackedState(e){const{trackedFileBackups:t}=e;this.trackedState.files.clear(),this.trackedState.versions.clear();for(const[e,n]of Object.entries(t))this.trackedState.files.set(e,n),this.trackedState.versions.set(e,n.version)}async cleanupOrphanedBackups(e){const{referencedBackups:t}=e,n=getFileHistoryPath({sessionId:this.sessionId});let r=0;try{const e=await L.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await L.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await L.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}},yr=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new fr({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 s=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(s={additions:0,deletions:0,fileName:getFileName({filePath:e})})}e.push({messageId:n.messageId,timestamp:n.timestamp,userPrompt:r,fileCount:Object.keys(n.trackedFileBackups).length,filesModified:o,codeChanges:s})}return e.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())}getSnapshot(e){const{messageId:t}=e;return this.snapshots.find(e=>e.messageId===t)||null}async restore(e){const{messageId:t,mode:n}=e;if(!this.getSnapshot({messageId:t}))return{success:!1,error:"Snapshot not found",filesRestored:0,filesDeleted:0,messagesRemoved:0};const r=this.snapshots.findIndex(e=>e.messageId===t);let o=0,s=0,a=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return{success:!1,error:`Restore verification failed:\n${t.join("\n")}`,filesRestored:0,filesDeleted:0,messagesRemoved:0};for(const t of e)await this.fileHistoryManager.restoreFile({filePath:t.filePath,backup:t.backup}),null===t.backup.backupFileName?s++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(a=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:a}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}},wr=null;function initializeCheckpointService(e){const{sessionId:t}=e;return wr=new yr({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return wr?wr.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:s=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!B.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&&s<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await te.access(t,ne.F_OK|ne.R_OK|ne.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let a;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");a=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const i=(a.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=s,c>i)throw createFileEditError(`Expected ${c} replacements, but only found ${i} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||c===i)l=a.split(n).join(r),d=i;else{l=a;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 te.writeFile(t,l,"utf-8"),{path:t,replacementsCount:d,oldContent:a,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 Er={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=ur.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${r.cross} Error: ${e.message}`:`${r.cross} Error: Unknown error occurred while editing file`}},"execute")},br=i.object({path:i.string().describe("The absolute path to the directory to read"),exclude:i.array(i.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:i.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});i.object({files:i.array(i.string()),directories:i.array(i.string())});var kr=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(!B.isAbsolute(t))throw new kr("Path must be absolute, not relative","INVALID_PATH");try{if(!(await M.stat(t)).isDirectory())throw new kr("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof kr)throw e;throw new kr(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await M.readdir(t);let o=[];r&&(o=await loadGitIgnorePatterns(t));const s=[...n,...o],a=[],i=[];for(const n of e){if(shouldIgnoreEntry(n,s))continue;const e=B.join(t,n);try{const t=await M.stat(e);t.isDirectory()?i.push(n):t.isFile()&&a.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:a.sort(),directories:i.sort()}}catch(e){if(e instanceof kr)throw e;throw new kr(`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=B.resolve(e);const r=await findGitRoot(e);for(;n&&isWithinGitRoot(n,r);){const e=B.join(n,".gitignore");try{const n=(await M.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const r=B.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=B.resolve(e);for(;;){try{const e=B.join(t,".git");if((await M.stat(e)).isDirectory())return t}catch{}const e=B.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=B.resolve(e),r=B.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(ge(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 Sr={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=br.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${r.cross} Error: ${e.message}`:`${r.cross} Error: Unknown error occurred while reading directory`}},"execute")},Cr=i.object({filePath:i.string().describe("The absolute path where the file should be written"),content:i.string().describe("The content to write to the file")});async function writeFile2({filePath:e,content:t}){if(!q(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=z(e);return X(n)||await O(n,{recursive:!0}),await backupFileBeforeEdit({filePath:e}),await N(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}`}i.object({success:i.boolean(),message:i.string(),path:i.string().optional()}),__name(writeFile2,"writeFile"),__name(formatOutput4,"formatOutput");var vr={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=Cr.parse(e),n=await writeFile2(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")},Tr=i.object({include:i.array(i.string()).describe("Array of glob patterns to include files"),exclude:i.array(i.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:i.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:i.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:i.string().optional().describe("Base directory for relative paths. Default: current working directory")}),Ar=i.object({filePath:i.string(),content:i.string(),fileType:i.string(),size:i.number()});i.object({content:i.string(),filesRead:i.array(i.string()),errors:i.array(i.object({file:i.string(),error:i.string()})),fileDetails:i.array(Ar)});var Pr=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},xr=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await pe(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:t,exclude:n=[],gitIgnore:r=!0,defaultExclude:o=!0,targetDirectory:s=process.cwd()}=e;if(!t||0===t.length)throw new Pr("At least one include pattern must be provided","NO_PATTERNS");const a=W.resolve(s),i={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...xr);const s=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:a});for(const e of s)try{const t=W.resolve(a,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 Pr)throw e;throw new Pr(`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 Ir={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=Tr.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${r.cross} Error: ${e.message}`:`${r.cross} Error: Unknown error occurred while reading multiple files`}},"execute")},$r=i.object({pattern:i.string().min(1,"Pattern is required"),include:i.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},i.array(i.string()).optional()),directory:i.string().optional()}),Dr=1e5,Fr=5e4;function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=le(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",a="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>Dr)return a="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void o.kill("SIGTERM");s+=t}catch(e){a+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,o.kill("SIGTERM")}}),o.stderr?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>Fr)return void(a+="\n[Error output truncated: too large]");a+=t}catch(e){a+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||a?r(new Error(a||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),a=[];for(const e of s){const t=parseGrepLine(e);t&&a.push(t)}return a}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),__name(formatGrepResults,"formatGrepResults");var Rr={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=$r.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${r.cross} Error: ${e.message}`:`${r.cross} Error: Unknown error occurred while searching files`}},"execute")},Mr=i.object({pattern:i.string().min(1,"Pattern is required"),path:i.string().optional()}),Lr=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 Lr("Pattern parameter is required","INVALID_PATTERN");try{const e=W.resolve(process.cwd(),n),r=process.cwd(),o=r.endsWith(W.sep)?r:r+W.sep;if(e!==r&&!e.startsWith(o))throw new Lr("Search path must be within the current working directory","INVALID_PATH");const s=await pe(t,{cwd:e,ignore:Ze,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),a=await Promise.all(s.map(async t=>{const n=W.join(e,t);try{return{file:t,mtime:(await L.stat(n)).mtimeMs}}catch{return{file:t,mtime:0}}}));return a.sort((e,t)=>t.mtime-e.mtime),{files:a.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof Lr)throw e;if(e instanceof Error)throw new Lr(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new Lr("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 Or={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=Mr.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${r.cross} Error: ${e.message}`:`${r.cross} Error: Unknown error occurred while finding files`}},"execute")},Nr=i.object({command:i.string().min(1,"Command cannot be empty"),args:i.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},i.array(i.string()).optional()),directory:i.string().optional(),timeout:i.preprocess(e=>"string"==typeof e?parseInt(e,10):e,i.number().optional())}),Ur=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,a){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=a}};async function executeShellCommand(e){const{command:t,args:n=[],directory:r,timeout:o=3e4}=e,s=Date.now();if(!t.trim())throw new Ur("Command cannot be empty","EMPTY_COMMAND");let a;if(r){if(B.isAbsolute(r))throw new Ur("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");a=B.resolve(process.cwd(),r)}else a=process.cwd();try{if(!(await L.stat(a)).isDirectory())throw new Ur(`Path is not a directory: ${r}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof Ur)throw e;throw new Ur(`Directory does not exist or is not accessible: ${r||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:a,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((r,a)=>{let i="",c="",l=!1;const d=n.length>0?he([t,...n]):t,u=setTimeout(()=>{if(!l){m.kill("SIGTERM");const e=Date.now()-s;a(new Ur(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",i,c,e))}},o),m=le(d,[],e);m.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>Dr)return c="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void m.kill("SIGTERM");i+=t}catch(e){c+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,m.kill("SIGTERM")}}),m.stderr?.on("data",e=>{try{const t=e.toString();if(c.length+t.length>Fr)return void(c+="\n[Error output truncated: too large]");c+=t}catch(e){c+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),m.on("close",(e,t)=>{l=!0,clearTimeout(u);const n=Date.now()-s;0===e?r({stdout:i.trim(),stderr:c.trim(),exitCode:e,signal:t,duration:n}):a(new Ur(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,i.trim(),c.trim(),n))}),m.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-s;a(new Ur(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),c.trim(),t))})})}catch(e){if(e instanceof Ur)throw e;throw new Ur(`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 jr={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=Nr.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${r.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${r.cross} Error: ${e.message}`}return`${r.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var _r={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 Br={name:"todo_write",description:"Create and manage a structured task list. Use this to track progress, organize complex tasks, and show thoroughness to the user. Create todos when tasks require multiple steps, are non-trivial, or when explicitly requested.",input_schema:{type:"object",properties:{todos:{type:"array",description:"The updated todo list",items:{type:"object",properties:{content:{type:"string",minLength:1,description:"The todo item content"},status:{type:"string",enum:["pending","in_progress","completed"],description:"The status of the todo item"},id:{type:"string",description:"Unique identifier for the todo item"}},required:["content","status","id"]}}},required:["todos"]},execute:todoWrite};async function askUserQuestion(e,t){if(!e.questions||0===e.questions.length)return JSON.stringify({error:"No questions provided"});for(let t=0;t<e.questions.length;t++){const n=e.questions[t];if(!n.question?.trim()||!n.header?.trim()||!n.options)return JSON.stringify({error:`Question ${t+1} is missing required fields (question, header, options)`});if(n.options.length<2||n.options.length>4)return JSON.stringify({error:`Question ${t+1} must have 2-4 options`});for(const e of n.options)if(!e.label?.trim()||!e.description?.trim())return JSON.stringify({error:`Question ${t+1} has an option with missing label or description`});if(n.header.length>12)return JSON.stringify({error:`Question ${t+1} header exceeds maximum length of 12 characters`})}if(!t?.onQuestionRequest)return JSON.stringify({error:"Question request callback not available"});if(t.abortSignal?.aborted)return JSON.stringify({error:"Interrupted by user"});try{const n=await t.onQuestionRequest(e);return t.abortSignal?.aborted?JSON.stringify({error:"Interrupted by user"}):JSON.stringify(n)}catch(e){return e instanceof Error?JSON.stringify({error:e.message}):JSON.stringify({error:"Failed to get user response"})}}function isErrorResponse(e){return"error"in e&&"string"==typeof e.error}function formatOutput6(e){const{result:t,params:n}=e;if(isErrorResponse(t))return`Error: ${t.error}`;if(!t.answers||0===t.answers.length)return"User declined to answer questions";const r=t.answers.filter(e=>e.selectedOptions&&Array.isArray(e.selectedOptions)&&e.selectedOptions.length>0);if(0===r.length)return"User declined to answer questions";const o=[];return r.forEach(e=>{let t=`Question ${e.questionIndex+1}`;n?.questions?.[e.questionIndex]&&(t=n.questions[e.questionIndex].question||t);const r=e.selectedOptions.join(", ");o.push(`${t} → ${r}`)}),o.join("\n")}__name(askUserQuestion,"askUserQuestion"),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var Wr={name:"ask_user_question",description:'Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select "Type something" to provide custom text input\n- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label\n- Use multiSelect: true to allow multiple answers to be selected for a question',acceptsCallbacks:!0,input_schema:{type:"object",properties:{questions:{type:"array",description:"Questions to ask the user",items:{type:"object",properties:{question:{type:"string",description:"The complete question to ask the user. Should be clear, specific, and end with a question mark."},header:{type:"string",description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",description:'The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Type something" option, that will be provided automatically.',items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options"]}}},required:["questions"]},execute:__name(async(e,t)=>{const n=await askUserQuestion(e,{onQuestionRequest:t?.onQuestionRequest,abortSignal:t?.abortSignal});try{return formatOutput6({result:JSON.parse(n),params:e})}catch{return n}},"execute")},Hr=i.object({port:i.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:i.number().int().positive().optional()}).refine(e=>void 0!==e.port&&void 0===e.pid||void 0===e.port&&void 0!==e.pid,{message:"Exactly one of port or pid must be provided"}),zr=class extends Error{static{__name(this,"KillshellError")}code;pid;port;constructor(e,t,n,r){super(e),this.name="KillshellError",this.code=t,this.pid=n,this.port=r}};function isUnixLike(){const e=process.platform;return"darwin"===e||"linux"===e}function isWindows(){return"win32"===process.platform}async function executeCommand(e,t){return new Promise((n,r)=>{const o=le(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",a="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{a+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(a.trim()||s.trim()))}),o.on("error",e=>{r(e)})})}async function findPidByPort(e){try{if(isUnixLike()){const t=(await executeCommand("lsof",["-ti",`:${e}`,"-sTCP:LISTEN"])).trim().split("\n")[0];if(!t||!/^\d+$/.test(t))return null;const n=parseInt(t,10);return isNaN(n)?null:n}if(isWindows()){const t=(await executeCommand("netstat",["-ano"])).split("\n");for(const n of t){const t=n.trim();if(!t)continue;const r=t.split(/\s+/);if(r.length<5)continue;if("LISTENING"!==r[3])continue;const o=r[1].match(/:(\d+)$/);if(!o)continue;const s=parseInt(o[1],10);if(isNaN(s)||s!==e)continue;const a=parseInt(r[r.length-1],10);if(!isNaN(a))return a}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new zr(`No process found listening on port ${e.port}`,"NO_PROCESS_FOUND",void 0,e.port);t=r}else void 0!==e.pid&&(t=e.pid);if(!t)throw new zr("Unable to determine target process","INVALID_TARGET");const r=await getProcessName(t);try{await killProcess(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new zr(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${r.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}__name(isUnixLike,"isUnixLike"),__name(isWindows,"isWindows"),__name(executeCommand,"executeCommand"),__name(findPidByPort,"findPidByPort"),__name(getProcessName,"getProcessName"),__name(isProcessAlive,"isProcessAlive"),__name(waitForProcessTermination,"waitForProcessTermination"),__name(killProcess,"killProcess"),__name(executeKillshell,"executeKillshell"),__name(formatKillshellResult,"formatKillshellResult");var Gr={name:"kill_shell",description:"Terminates processes by port number or PID, useful for freeing occupied ports or stopping stuck development servers. Attempts graceful termination first (SIGTERM/taskkill), then forces if needed. Use with caution - terminating system processes may cause instability.",acceptsCallbacks:!0,input_schema:{type:"object",properties:{port:{type:"number",description:"Port number (1-65535) to free by terminating the listening process. Automatically finds and kills the process using this port."},pid:{type:"number",description:"Process ID to terminate directly. Use when you know the exact PID to kill."}},required:[]},execute:__name(async(e,t)=>{try{const n=Hr.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?`${r.cross} Permission denied: Process termination was not approved`:formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`${r.cross} Error: ${e.message}`:`${r.cross} Error: Unknown error occurred while killing process`}},"execute")},qr=["explore","plan","review","general"],Vr=[{name:"explore",description:"Use this for codebase exploration, search, or understanding tasks that require multiple file operations",tools:"glob, grep, read_file, read_directory, read_multiple_files, think",systemPrompt:'You are a codebase explorer. Your prompt will specify depth level and what information is needed.\n\nTOOLS AVAILABLE:\n- glob: Find files by patterns\n- grep: Search code for keywords/patterns\n- read_file: Read specific files\n- read_directory: List directory contents\n- read_multiple_files: Read many files efficiently\n- think: Reason through findings\n\nDEPTH LEVELS:\n- quick: 1-2 files, answer the specific question only\n- medium: 3-5 files, understand the main component and context\n- thorough: 10+ files, comprehensive understanding\n\nINSTRUCTIONS:\n1. Look for "Depth: [level]" in the prompt (usually on line 2)\n2. Identify exactly what information is needed (specified in the prompt)\n3. Use only the file operations needed to get that information\n4. Stop when you have the requested information\n\nIf no depth level specified, default to "quick".\n\nRESPONSE FORMAT:\n- Provide exactly what was requested\n- Include relevant file paths and code sections\n- Match your depth to the specified level\n- Stop when done - don\'t over-explore',location:"personal",filePath:"__builtin__"}];function isReservedAgentName(e){return!!e&&qr.includes(e.toLowerCase())}function getRootAgentDir(){return W.join(J.homedir(),".commandcode","agents")}function getLocalAgentDir(){return W.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,t){try{const n=(await L.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=W.join(e,n),o=await L.readFile(r,"utf-8"),{data:s,content:a}=me(o),i=s.name||n.replace(".md","");if(isReservedAgentName(i))return null;let c=s.tools||"";return"*"!==c&&'"*"'!==c||(c="*"),{name:i,description:s.description||"",tools:c,systemPrompt:a.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(isReservedAgentName,"isReservedAgentName"),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents");var Kr=2e5;function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.max(0,Math.ceil(t-n))}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>25e3}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?(estimateTokens(e),"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."):e}function calculateUsageFromResponse(e){return(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.output_tokens||0)}function sleep(e){const{delay:t,signal:n}=e;return new Promise((e,r)=>{if(n?.aborted)return r(new Error("Interrupted by user"));const o=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(o),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(function getOversizedOutputError(e,t){return"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."},"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__name(sleep,"sleep");var Jr=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${r.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${r.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${r.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${r.warning} ${e}`)}debug(e){dlog(`[${this.prefix}] ${e}`)}};function getEnterpriseMemoryPath(){switch(K.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return B.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const e=K.homedir();return B.join(e,".commandcode","AGENTS.md")}function getProjectMemoryPaths(e){return[B.join(e,"AGENTS.md"),B.join(e,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:X(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(X(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:X(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return X(e)&&oe(e).isFile()?await M.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=[],s=e.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),a=Array.from(s.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let i=s;for(const e of a){const o=e[1];let s=o;o.startsWith("~/")?s=B.join(K.homedir(),o.slice(2)):B.isAbsolute(o)||(s=B.resolve(B.dirname(t),o));const a=await loadMemoryFile(s);if(a){const t=await processImports(a,s,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(X(r)){const e=await loadMemoryFile(r);if(e){const t=await processImports(e,r);n.set(r,t)}}const o=getUserMemoryPath();if(X(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);n.set(o,t)}}const s=[B.join(e,"AGENTS.md"),B.join(e,".commandcode","AGENTS.md")];for(const e of s)if(X(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=B.isAbsolute(r)?B.dirname(r):B.dirname(B.resolve(e,r));if(t.startsWith(e)&&t!==e){const r=[];let o=t;for(;o.startsWith(e)&&o!==e;)r.push(o),o=B.dirname(o);for(const e of r.reverse()){const t=[B.join(e,"AGENTS.md"),B.join(e,".commandcode","AGENTS.md")];for(const e of t)if(X(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=B.dirname(e);return X(n)||await M.mkdir(n,{recursive:!0}),X(e)||await M.writeFile(e,"# AGENTS.md\n\n","utf-8"),new Promise((n,r)=>{const o=le(t,[e],{stdio:"inherit",shell:!0});o.on("exit",e=>{0===e?n():r(new Error(`Editor exited with code ${e}`))}),o.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),r(e)})})}async function initProjectMemory(e){const t=B.join(e,"AGENTS.md");return X(t)||await M.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(),s=getUserMemoryPath(),a=[B.join(t,"AGENTS.md"),B.join(t,".commandcode","AGENTS.md")];n.has(o)&&r.push(`# Memory from: ${o}\n\n${n.get(o)}`),n.has(s)&&r.push(`# Memory from: ${s}\n\n${n.get(s)}`);for(const e of a)if(n.has(e)){r.push(`# Memory from: ${e}\n\n${n.get(e)}`);break}for(const[e,t]of n)e===o||e===s||a.includes(e)||r.push(`# Memory from: ${e}\n\n${t}`);return r.join("\n\n---\n\n")}catch(e){return null}}__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 Yr=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return W.join(J.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return ye(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=W.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=W.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=ie("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await L.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),!1}}async isProjectInitialized(){try{return(await L.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{if(0===e.length)return;const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),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 L.writeFile(this.sessionFilePath,r.join("\n")+"\n"),this.lastSavedMessagesHash=n}catch(e){console.error("Failed to save messages to session:",e)}}async loadMessages(e){const t=e||this.sessionId,n=W.join(this.projectPath,`${t}.jsonl`);try{const e=(await L.readFile(n,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let r=0;for(const n of e)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){r++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:r,totalLines:e.length}}catch(e){return console.error("Error loading messages:",e),{messages:[],corruptedLines:0,totalLines:0}}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n&&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=cr(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=cr(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=W.join(this.projectPath,`${t}.jsonl`);try{const e=(await L.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=W.join(e,t);try{return(await L.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=W.join(e,t);try{return await L.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=W.join(_SessionManager.getProjectsBasePath(),e);try{try{await L.access(t)}catch{return[]}const e=(await L.readdir(t)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),n=[];for(const r of e){const e=r.replace(".jsonl",""),o=W.join(t,r);try{const r=await L.stat(o),s=(await L.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(s.length>0){let o="",a="";const i=JSON.parse(s[0]);i.gitBranch&&(a=i.gitBranch);for(const e of s){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}n.push({id:e,createdAt:r.birthtime.toISOString(),lastModified:r.mtime.toISOString(),firstMessage:o||"No messages",messageCount:s.length,projectPath:t,gitBranch:a||"-"})}}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=W.join(this.projectPath,`${this.sessionId}.share.json`);try{await L.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=W.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await L.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=W.join(this.projectPath,`${this.sessionId}.share.json`);try{await L.unlink(e)}catch(e){}}getCheckpointsFilePath(){return W.join(this.projectPath,`${this.sessionId}.checkpoints.jsonl`)}async saveSnapshot(e){const{snapshot:t,isUpdate:n}=e,r=this.getCheckpointsFilePath();try{await this.initializeProject();const e={type:"file-history-snapshot",messageId:t.messageId,snapshot:t,isSnapshotUpdate:n};if(n){let n=[];try{n=(await L.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const o=n.findIndex(e=>e.messageId===t.messageId);-1!==o?n[o]=e:n.push(e);const s=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await L.writeFile(r,s)}else await L.appendFile(r,JSON.stringify(e)+"\n")}catch(e){console.error("Failed to save checkpoint snapshot:",e)}}async loadSnapshots(){const e=this.getCheckpointsFilePath();try{const t=(await L.readFile(e,"utf-8")).trim().split("\n").filter(e=>e.trim()),n=[];for(const e of t)try{const t=JSON.parse(e);"file-history-snapshot"===t.type&&n.push(t.snapshot)}catch{}return n}catch{return[]}}async deleteSnapshotsAfter(e){const{messageId:t,inclusive:n=!1}=e,r=this.getCheckpointsFilePath();try{const e=(await L.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),o=e.findIndex(e=>e.messageId===t);if(-1===o)return;const s=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await L.writeFile(r,s)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return r.length>0&&await this.saveMessages(r),r}},Qr=new Jr("AgentExecutor");function agentToTool(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=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,a)=>{let i=null;const c=Date.now();let l=null;try{let d=getAvailableTools(e,{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}),u=Date.now();const m=10,g=[];if(a?.onFeedUpdate){const n=cr(e.name,t);i=er({name:e.name,input:n}),a.onFeedUpdate(i)}l=setInterval(()=>{if(a?.onFeedUpdate&&i){const e=Date.now(),t=Math.floor((e-c)/1e3);i={...i,metadata:{...i.metadata,elapsedSeconds:t}},a.onFeedUpdate(i)}},1e3);const p=await getConfiguredProvider(),h=await isOAuthEnforced();let f;p===Ke&&(f=await yt.getValidAccessToken(),validateOAuthToken({token:f,provider:p}));const y=getApiBaseUrl(),w=new pn({baseUrl:y});let E=0;const b=[];let k=t?.messages;if("string"==typeof k)try{k=JSON.parse(k)}catch(e){k=[]}if(Array.isArray(k)&&k.length>0)for(const e of k)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&b.push({role:"user",content:t})}const S={stream:!0,messages:b,max_tokens:64e3,system:e.systemPrompt,temperature:.3,tools:d,model:`anthropic:${getConfiguredModel()}`},C=await isTasteLearningEnabled(),v={[He]:Yr.getCurrentProjectDirName(),[ze]:C.toString(),[Be]:h.toString()};f&&(v[We]=`Bearer ${f}`);const T=getEnvironmentContext(),A=await getMemoryContent([]),P=crypto.randomUUID();let x="",I=!0;const $=__name(()=>{Qr.debug("[Agent] Abort signal triggered, stopping immediately"),I=!1,l&&(clearInterval(l),l=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",$);try{for(;I;){if(a?.abortSignal?.aborted)throw Qr.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const e=await callAPIWithRetry({request:w,body:{mode:"custom-agent",config:T,memory:A,threadId:P,params:{...S,messages:b}},headers:v,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{E+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&i&&t-u>=m){const e=Math.floor((t-c)/1e3);i={...i,metadata:{...i.metadata,tokensUsed:E,elapsedSeconds:e}},a.onFeedUpdate(i),u=t}},"onTextDelta")});e.usage&&(E=calculateUsageFromResponse(e.usage));const t=e.content.filter(e=>"tool_use"===e.type);if(x=e.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(e,a):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&&b.push({role:"assistant",content:t}),I=!1;break}const n=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);n.length>0&&b.push({role:"assistant",content:n});const r=[],o=new Set;let s=!1;for(const e of t){if(a?.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)&&a?.onPermissionRequest){if(l&&(clearInterval(l),l=null),!await a.onPermissionRequest(e.name,t)){Qr.debug(`Permission denied for tool: ${e.name}`),s=!0;break}l=setInterval(()=>{if(a?.onFeedUpdate&&i){const e=Date.now(),t=Math.floor((e-c)/1e3);i={...i,metadata:{...i.metadata,elapsedSeconds:t}},a.onFeedUpdate(i)}},1e3)}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(!B.isAbsolute(t)){const o=B.resolve(process.cwd(),t);n[e]=o,r=!0,Qr.debug(`Converted '${e}': '${t}' -> '${o}'`)}}"paths"in n&&Array.isArray(n.paths)&&(n.paths=n.paths.map(e=>"string"!=typeof e||B.isAbsolute(e)?e:(r=!0,B.resolve(process.cwd(),e)))),r?(t=n,Qr.debug(`Resolved input for ${e.name}: ${cr(e.name,t)}`)):Qr.debug(`No path resolution needed for ${e.name}: ${cr(e.name,t)}`)}if(a?.onFeedUpdate&&i){const n=cr(e.name,t);g.push({name:e.name,input:n}),g.length>3&&g.shift();const r=Date.now(),o=Math.floor((r-c)/1e3);i={...i,metadata:{isAgent:!0,status:"running",startTime:c,tokensUsed:E,elapsedSeconds:o,recentTools:[...g]}},Qr.debug(`Updating agent with recentTools (${g.length} tools): ${JSON.stringify(g)}`),a.onFeedUpdate(i)}const n=await executeTool(e.name,t,{abortSignal:a?.abortSignal});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const d=checkToolOutputTokensLimit(n,e.name);if(r.push({type:"tool_result",tool_use_id:e.id,content:d}),o.add(e.id),a?.onFeedUpdate&&i){const e=Date.now(),t=Math.floor((e-c)/1e3);i={...i,metadata:{isAgent:!0,status:"running",startTime:c,tokensUsed:E,elapsedSeconds:t,recentTools:[...g]}},a.onFeedUpdate(i)}Qr.debug(`Tool executed successfully: ${e.name}`)}catch(t){const n=t instanceof Error?t.message:"Unknown error";r.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}),o.add(e.id),Qr.error(`Tool execution failed: ${e.name} - ${n}`)}}if(s){const e=b[b.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:b.pop()}I=!1;break}const d=[...r];b.push({role:"user",content:d})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",$)}if(l&&(clearInterval(l),l=null),a?.onFeedUpdate&&i){const e=Date.now(),t=(e-c)/1e3;i={...i,output:x||"DONE",metadata:{isAgent:!0,status:"done",startTime:c,endTime:e,tokensUsed:E,elapsedSeconds:t}},a.onFeedUpdate(i)}return x||"DONE"}catch(e){if(l&&(clearInterval(l),l=null),a?.onFeedUpdate&&i){const t=Date.now(),n=(t-c)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||a?.abortSignal?.aborted;i={...i,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:c,endTime:t,tokensUsed:i?.metadata?.tokensUsed||0,elapsedSeconds:n}},a.onFeedUpdate(i)}throw e}},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let a=[];if("*"===e.tools)a=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)a.push(e);else{const e=r.find(e=>e.name===t);e&&a.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)a.push(t);else{const t=r.find(t=>t.name===e);t&&a.push(t)}}}return a}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let a=null;for(let e=0;e<5;e++){if(o?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:Ge.ALPHA.GENERATE,signal:o,headers:r}),a=fe.fromReadableStream(e);s&&a.on("text",s);let i=null;a.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await a.finalMessage();if(i)throw i;return c}catch(t){if(a=t,o?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);Qr.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw a||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof sn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof cn||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 sn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof cn||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=cr(r.name,r.input),n=Fn(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 Zr=new Map,Xr=null;function initializeAgentManager(e){Xr=e}async function loadAgentTools(){if(!Xr)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Zr.clear();for(const e of Vr){const t=agentToTool(e,Xr);Zr.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Xr);Zr.set(t.name,t)}}async function getAgentTools(){return 0===Zr.size&&await loadAgentTools(),Array.from(Zr.values())}async function getAgentTool(e){return 0===Zr.size&&await loadAgentTools(),Zr.get(e)}function isPathInTasteDirectory(e){const{filePath:t,projectRoot:n}=e,r=B.join(n,".commandcode","taste"),o=B.normalize(B.resolve(n,t)),s=B.normalize(r);return o.startsWith(s)}function getTasteFileInfo(e){const t=B.normalize(B.resolve(e)),n=B.normalize(B.join(process.cwd(),".commandcode","taste")),r=B.normalize(B.join(K.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 s=B.relative(o,t).split(B.sep);return 1===s.length?{isTaste:!0}:2===s.length?{isTaste:!0,category:s[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 eo=[dr,Er,Sr,vr,Ir,Rr,Or,jr,_r,Br,Wr,Gr],to=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],no=new Map(eo.map(e=>[e.name,e])),ro=new Set([...eo.map(e=>e.name),...to.map(e=>e.name)]);function isAgentTool(e){return!ro.has(e)}async function executeTool(e,t,n){let r=no.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from(no.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(!no.has(e)||!0===r.acceptsCallbacks)&&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[...eo.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})),...to]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var oo={};eo.forEach(e=>{oo[e.name]=toPascalCase(e.name)}),to.forEach(e=>{oo[e.name]=toPascalCase(e.name)});var so={};Object.entries(oo).forEach(([e,t])=>{so[t]=e}),initializeAgentManager({clientTools:eo,serverTools:to,toolsMap:no,displayNameToToolName:so});var ao=new class extends we{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;get observerHasRun(){return this._observerHasRun}markObserverRun(){this._observerHasRun=!0}get importHasStarted(){return this._importHasStarted}markImportStarted(){this._importHasStarted=!0}get learningComplete(){return this._learningComplete}markLearningComplete(){this._learningComplete=!0,this.emit("learning-complete")}addEvent(e){const{type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d}=e,u={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d};this.events.unshift(u),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",u)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};function extractLearningWithConfidence(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)\.\s+Confidence:\s*(\d+\.?\d*)/);return n?{text:n[1].trim(),confidence:parseFloat(n[2])}:null}function extractLearnings(e){const{text:t}=e;return t.split("\n").filter(e=>e.trim().startsWith("-")).map(e=>extractLearningWithConfidence({line:e})).filter(Boolean)}function compareLearnings(e){const{oldText:t,newText:n}=e,r=extractLearnings({text:t}),o=extractLearnings({text:n}),s=new Map(r.map(e=>[e.text,e.confidence])),a=[],i=[],c=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?a.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:a,upgraded:i,downgraded:c}}__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings");var io=new Jr("LearningAgent"),co=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=3;request;projectRoot;tasteDir;sessionId;abortSignal;constructor(e){this.request=e.request,this.sessionId=e.sessionId,this.projectRoot=e.projectRoot,this.tasteDir=B.join(e.projectRoot,".commandcode","taste")}updateRequest(e){this.request=e}setAbortSignal(e){this.abortSignal=e}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)return this.pendingMessages=t,{success:!0};if(0===t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length)return{success:!0};this.isProcessing=!0;try{for(await this.runLearningLoop({messages:t}),this.lastProcessedMessageIndex=t.length-1;null!==this.pendingMessages;){const e=this.pendingMessages;this.pendingMessages=null,e.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length>0&&(await this.runLearningLoop({messages:e}),this.lastProcessedMessageIndex=e.length-1)}return{success:!0}}catch(e){const n=e instanceof Error?e.message:String(e);return dlog(`[LearningAgent] ERROR: ${n}`),ao.addEvent({type:"error",message:"learning pass failed",details:n}),this.lastProcessedMessageIndex=t.length-1,{success:!1}}finally{this.isProcessing=!1}}async runLearningLoop(e){const{messages:t}=e,n=["analyzing deltas","computing embeddings","updating weights","refining patterns","processing signals","extracting features","tuning parameters","optimizing priors"],r=n[Math.floor(Math.random()*n.length)];ao.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,a=Math.max(20,s),i=Math.max(0,t.length-a),c=t.slice(i);let l=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){const e=await this.callLearningAPI({conversation:u}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&io.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||ao.addEvent({type:"no_learnings",message:"no changes to taste"}),ao.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",s="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await Q.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const a=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&s)try{i=await Q.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:i});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{ao.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{ao.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{ao.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:a})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(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(B.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 s=B.normalize(o);if(s.startsWith(".."))throw new Error(`Security: ${t} path traversal attempt detected. Attempted: ${o}`);const a=B.join(this.tasteDir,s);if(!B.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 s="write_file"===t||"edit_file"===t;if(B.isAbsolute(e)&&e.startsWith(this.tasteDir))if(s){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(B.isAbsolute(e))throw new Error(`Invalid path: Absolute path outside taste directory: ${e}`);const t=B.normalize(e);if(t.startsWith(".."))throw new Error(`Security: Path traversal attempt detected: ${e}`);if(n=t.startsWith(".commandcode/taste")||t.startsWith(".commandcode"+B.sep+"taste")?t.replace(/^\.commandcode[/\\]taste/,this.tasteDir):B.join(this.tasteDir,t),n=B.normalize(n),!n.startsWith(this.tasteDir))throw new Error(`Security: Resolved path escapes taste directory: ${e} -> ${n}`);if(s&&!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(!Q.existsSync(this.tasteDir)){Q.mkdirSync(this.tasteDir,{recursive:!0});const e=B.join(this.tasteDir,"taste.md");Q.writeFileSync(e,"","utf-8")}}async reorganizeIfNeeded(){const e=B.join(this.tasteDir,"taste.md");if(!Q.existsSync(e))return!1;const t=Q.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=B.join(this.tasteDir,t),o=B.join(n,"taste.md");Q.mkdirSync(n,{recursive:!0}),ao.addEvent({type:"refactored",message:`moved: ${e.name} package`,details:`moved to ${t}/taste.md`});const s=`# ${e.name}\n${e.learnings.join("\n")}\n`;Q.writeFileSync(o,s,"utf-8");const a=`# ${e.name}\nSee [${t}/taste.md](${t}/taste.md)\n`;r=r.replace(e.fullSection,a)}return Q.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 Q.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=Q.readdirSync(t,{withFileTypes:!0});let o="";for(let e=0;e<r.length;e++){const s=r[e],a=e===r.length-1,i=a?"└── ":"├── ";if(s.isDirectory()){o+=`${n}${i}${s.name}/\n`;const e=n+(a?" ":"│ ");o+=await this.buildTree({dir:B.join(t,s.name),prefix:e})}else if("taste.md"===s.name){const e=(Q.readFileSync(B.join(t,s.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${n}${i}${s.name} (${e} learnings)\n`}else o+=`${n}${i}${s.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===Ke&&(o=await yt.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[He]:Yr.getCurrentProjectDirName(),[Be]:r.toString()};o&&(s[We]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const c={conversation:t,tools:a,model:i,threadId:this.sessionId};let l=0,d=null;for(;l<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:Ge.ALPHA.TASTE.LEARN,body:c,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),l++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),d;if(l>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),d;const n=1e3*Math.pow(2,l);dlog(`[LearningAgent] retrying API call (${l}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(e){const{projectRoot:t}=e,n=B.join(t,".commandcode","taste");return Q.existsSync(n)}};async function getTasteContent(){try{const e=process.cwd(),t=B.join(e,".commandcode","taste","taste.md");if(!X(t))return null;const n=await M.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 lo=new Jr("ContextEngine"),uo=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;requestInterrupted=!1;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];learningAgent;checkpointManager;constructor(e,t){const n=getApiBaseUrl();this.request=new pn({baseUrl:n}),this.callbacks=e,this.sessionManager=new Yr(t),this.learningAgent=new co({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new pn({baseUrl:e}),this.learningAgent.updateRequest(this.request)}createSessionStoreAdapter(){return{saveSnapshot:__name(async e=>{await this.sessionManager.saveSnapshot(e)},"saveSnapshot"),loadSnapshots:__name(async()=>this.sessionManager.loadSnapshots(),"loadSnapshots"),deleteSnapshotsAfter:__name(async e=>{await this.sessionManager.deleteSnapshotsAfter(e)},"deleteSnapshotsAfter"),getMessageAtIndex:__name(e=>this.sessionManager.getMessageAtIndex({index:e.index,messages:this.messages}),"getMessageAtIndex"),getMessageIndexById:__name(e=>this.sessionManager.getMessageIndexById({messageId:e.messageId,messages:this.messages}),"getMessageIndexById"),truncateMessagesAtIndex:__name(async e=>{const t=await this.sessionManager.truncateMessagesAtIndex({index:e.index,messages:this.messages});this.messages=t},"truncateMessagesAtIndex"),getMessageCount:__name(()=>this.sessionManager.getMessageCount({messages:this.messages}),"getMessageCount")}}setupCheckpointSessionStore(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),this.checkpointManager.runCleanup().catch(()=>{})}async interrupt(e=!1){if(this.requestInterrupted=!0,this.abortController){this.abortController.abort(),this.abortController=null,lo.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)){const n=t.message.content.filter(e=>"tool_use"===e.type),r=[];if(n.length>0){const e=n.map(e=>({type:"tool_result",tool_use_id:e.id,content:"Interrupted by user",is_error:!0}));r.push(...e),lo.debug(`Added tool_result blocks for ${e.length} interrupted tool calls`)}e&&r.push({type:"text",text:"Interrupted by user"}),r.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:r}))}if(e){const e=Gn("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>lo.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=Gn(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 s=[];t&&t.length>0&&t.forEach(e=>{s.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&s.push({type:"text",text:n});const a={role:"user",content:s},i=crypto.randomUUID(),c=this.createMessageWithMeta(a,{messageId:i});return this.addMessageAndSync(c),this.checkpointManager.createSnapshot({messageId:i}).catch(e=>lo.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,o).catch(e=>lo.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){lo.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}async processMessages(){let e="";this.requestInterrupted=!1,this.abortController=new AbortController,this.learningAgent.setAbortSignal(this.abortController.signal);let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.checkIfInterrupted(),this.updateContextUsage(o);const s=o.content.filter(e=>"tool_use"===e.type),a=o.content.filter(e=>"server_tool_use"===e.type);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===s.length){const t=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===a.length){const t=Vn(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>lo.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>lo.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=Gn(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>lo.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=Vn(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:s}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=Gn(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>lo.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&lo.debug("Request interrupted or insufficient credits"),this.formatAPIError(e)}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const{messages:t,corruptedLines:n,totalLines:r}=await this.sessionManager.loadMessages(e);this.messages=t;try{await this.loadCheckpoints()}catch(t){lo.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return lo.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async compactConversation({preserveCurrentInteraction:e=!1}={preserveCurrentInteraction:!1}){const t=this.messages.length,n=this.contextTokensUsed;let r=-1;if(e)for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("user"===t.message.role){const n=t.message.content;if(!Array.isArray(n)){r=e;break}if(!n.some(e=>"tool_result"===e.type)){r=e;break}}}let o=0;const s=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}s.push(n)}else s.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?s.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&s.push(n)}"user"!==a&&"assistant"!==a&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,n-o);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:Kr}),{messagesRemoved:t-s.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){}}))}async syncMessageToShare(e,t){try{const n=nn.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Ge.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.requestInterrupted||this.abortController?.signal.aborted)throw new Error("Interrupted by user")}initializeInteractionTokens(){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message)}async prepareAPICall(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(t),t===Ke&&(r=await yt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},s={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId()};lo.debug(`calling API (${o.model}, ${this.messages.length} msgs, ${e.length} tools)`);const a=await isTasteLearningEnabled(),i={[He]:Yr.getCurrentProjectDirName(),[ze]:a.toString(),[Be]:n.toString()};return r&&(i[We]=`Bearer ${r}`),{body:s,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:Ge.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers}),n=fe.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.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(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),s=Math.max(o,1e3),a=Math.min(s,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:a,signal:this.abortController?.signal})}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.requestInterrupted||this.abortController?.signal.aborted||e instanceof sn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof an||401===e?.status||e instanceof cn||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.requestInterrupted||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 cn||403===e?.status)return e;if(e instanceof an||401===e?.status)return new Error('Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');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 s=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:s}),n.add(o.id),isAgentTool(o.name)||this.showToolSuccess(o,s)}catch(e){const r=e instanceof Error?e.message:"Unknown error";"Interrupted by user"===r&&isAgentTool(o.name)?n.add(o.id):(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,onQuestionRequest:this.callbacks.onQuestionRequest,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=cr(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=Kn(e.name,t,n),o=tr(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=cr(e.name,r),s=Kn(e.name,o,n),a=tr(s,t);this.callbacks.onFeedUpdate(a)}showToolError(e,t){const n=cr(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=Kn(e.name,n,r),s=tr(o,nr(t));this.callbacks.onFeedUpdate(s)}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=Vn(t.trim());this.callbacks.onFeedUpdate(e),t=""}const e=cr(n.name,n.input),r=Kn(n.name,e),o=Fn(n.name)?"Found 10 results":"Content fetched",s=tr(r,o);this.callbacks.onFeedUpdate(s)}if(t.trim()){const e=Vn(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:Kr}),this.checkAndCompactIfNeeded()}async checkAndCompactIfNeeded(){const e=Math.floor(17e4);if(this.contextTokensUsed>e){lo.debug(`Context tokens (${this.contextTokensUsed}) exceeded threshold (${e}), triggering automatic compaction`);try{const e=await this.compactConversation({preserveCurrentInteraction:!0});lo.debug(`Automatic compaction completed: removed ${e.messagesRemoved} messages, saved ${e.tokensSaved} tokens`)}catch(e){lo.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 s=await this.checkpointManager.restore({messageId:t,mode:n});return!s.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:Kr})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}},mo=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{const s=le("/bin/bash",["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"]});let a="",i="",c=null;n>0&&(c=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:a,stderr:i+(i?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>Dr)return i="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void s.kill("SIGTERM");a+=t}catch(e){i+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,s.kill("SIGTERM")}}),s.stderr?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>Fr)return void(i+="\n[Error output truncated: too large]");i+=t}catch(e){i+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),s.on("close",n=>{c&&clearTimeout(c),t({stdout:a.trim(),stderr:i.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{c&&clearTimeout(c),t({stdout:a,stderr:i+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),go=__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"),po=__name(()=>{const[e,t]=P({isExecuting:!1,currentCommand:null});return{executeBash:$(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await mo(e,{timeout:3e4,cwd:process.cwd()}),o=go(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]=tr(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]=tr(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),ho=class extends we{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||W.join(e,".commandcode","settings.local.json"),this.config=this.getDefaultConfig(),this.loadConfig()}getDefaultConfig(){return{enabled:!0,defaultScope:"session",autoApprove:{create:!1,edit:!1,delete:!1,execute:!1,shellCommands:!1},trustedPaths:[],trustedCommands:[],sessionPermissions:new Map,projectPermissions:new Map,sessionShellPermissions:new Map,projectShellPermissions:new Map}}async loadConfig(){try{const e=await L.readFile(this.configPath,"utf-8"),t=JSON.parse(e);t.permissions&&("acceptEdits"===t.permissions.defaultMode&&(this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0),t.permissions.autoApprove&&(void 0!==t.permissions.autoApprove.create&&(this.config.autoApprove.create=t.permissions.autoApprove.create),void 0!==t.permissions.autoApprove.update&&(this.config.autoApprove.edit=t.permissions.autoApprove.update),void 0!==t.permissions.autoApprove.delete&&(this.config.autoApprove.delete=t.permissions.autoApprove.delete)),t.permissions.allow&&t.permissions.allow.forEach(e=>{if(e.startsWith("Bash(")&&e.endsWith(")")){const t=e.slice(5,-1);this.config.trustedCommands.push(t)}}))}catch(e){}}async requestPermission(e){if(!this.config.enabled)return{allowed:!0};const t=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)?{allowed:!0}:this.config.sessionPermissions.has(t)?{allowed:this.config.sessionPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("permission-request",e,n=>{this.handleUserChoice(e,n).then(t)})})}async handleUserChoice(e,t){const n=e.action,r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionPermissions.set(n,!0);break;case"project":await this.createCommandCodeSettings(),this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getFileKey(e){const t=W.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=W.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=W.join(this.projectRoot,".commandcode"),t=W.join(e,"settings.local.json");try{await L.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await L.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 L.writeFile(t,JSON.stringify(n,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const t=W.join(this.projectRoot,".commandcode"),n=W.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await L.mkdir(t,{recursive:!0});try{const t=await L.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 L.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},fo=__name((e={})=>{const[t,n]=P(null),[r,o]=P(null),[s,a]=P(!1);return I(()=>{const t=e.projectRoot||process.cwd(),r=new ho(t);return r.on("permission-request",(t,n)=>{o(t),a(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),a(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:$(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:$(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:$(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:$(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:$(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:$((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:$(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");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 yo=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,s="";for(let e=0;e<t.length;e++){const a=t[e];'"'!==a&&"'"!==a||o?a===s&&o?(o=!1,s=""):" "!==a||o?r+=a:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=a)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const o=n.substring(0,r),s=n.substring(r+1).trim();return{commandName:o,rawArguments:s,positionalArgs:parsePositionalArguments({input:s})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let o=t;return o=o.replace(/\$ARGUMENTS/g,n),o=o.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:o}}function loadCustomCommands(){const e=[],t=W.join(process.cwd(),".commandcode","commands"),n=W.join(J.homedir(),".commandcode","commands");function loadCommandsFromDirectory(t,n,r=""){if(Z.existsSync(t))try{const o=Z.readdirSync(t,{withFileTypes:!0});for(const s of o){const o=W.join(t,s.name);if(s.isDirectory())loadCommandsFromDirectory(o,n,r?`${r}/${s.name}`:s.name);else if(s.isFile()&&s.name.endsWith(".md")){const t=W.basename(s.name,".md"),a=Z.readFileSync(o,"utf-8").trim();e.push({name:t,source:n,content:a,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}function isDirectoryEmpty(){try{return 0===re(process.cwd()).length}catch{return!1}}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new pn({baseUrl:e});return await t.get({endpoint:Ge.ALPHA.WHOAMI})}__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),__name(isDirectoryEmpty,"isDirectoryEmpty"),__name(getAuthenticatedEntity,"getAuthenticatedEntity");var wo=["Code","Code - Insiders","VSCodium","Cursor"],Eo="Code",bo={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},ko=__name(e=>be(e).href,"formatPathForTerminal"),So=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),Co=__name(({home:e,configSegments:t,variant:n})=>B.join(e,...t,n,"User","keybindings.json"),"buildKeybindingsPath"),vo=__name(({home:e,configSegments:t,variants:n})=>{for(const r of n){const n=Co({home:e,configSegments:t,variant:r});if(Q.existsSync(B.dirname(n)))return r}return null},"findExistingVariant"),To=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Ao(t.when)},"isTerminalShiftEnterBinding"),Ao=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),Po=__name(e=>{const t=ke(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),xo=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),Io=__name(({error:e,content:t})=>{const n=e.message;return xo(t)&&(n.includes("Expected double-quoted property name")||n.includes("Unexpected token")||n.includes("is not valid JSON"))?"Invalid JSON: trailing comma detected. Remove the comma before the closing bracket.":n.includes("Expected")&&n.includes(",")&&n.includes("or")?"Invalid JSON: missing comma between elements.":n.includes("Unterminated string")||n.includes("Bad string")?"Invalid JSON: unterminated string. Check for missing closing quotes.":"Invalid JSON syntax. Please check the file format."},"formatJsonParseError"),$o=__name(e=>{let t="",n=!1,r=!1;for(let o=0;o<e.length;o++){const s=e[o];if(n)t+=s,r?r=!1:"\\"===s?r=!0:'"'===s&&(n=!1);else if('"'!==s){if(","===s){let t=o+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=s}else n=!0,t+=s}return t},"removeTrailingCommas"),Do=__name(e=>{try{const t=ke(e),n=$o(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:Io({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),Fo=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:ko(t)}),"createSuccessResult"),Ro=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:ko(t)}),"createErrorResult"),Mo=__name(()=>{const e=K.homedir(),t=K.platform();if(process.env.VSCODE_PORTABLE)return B.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const n=So(t);if(!n)return Co({home:e,configSegments:[".config"],variant:Eo});const r=vo({home:e,configSegments:n,variants:wo});return Co({home:e,configSegments:n,variant:r??Eo})},"getVSCodeKeybindingsPath"),Lo=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)To(n)&&(n.command===bo.command&&n.args?.text===bo.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),Oo=__name(e=>{try{if(!Q.existsSync(e)){const t=B.dirname(e);return Q.existsSync(t)||Q.mkdirSync(t,{recursive:!0}),{rawContent:"",keybindings:[]}}const t=Q.readFileSync(e,"utf-8");if(Po(t))return{rawContent:t,keybindings:[]};const n=Do(t.trim());return n.success?Array.isArray(n.data)?{rawContent:t,keybindings:n.data}:Ro({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:e}):Ro({message:`Failed to parse existing VSCode key bindings: ${n.error}`,keybindingsPath:e})}catch(t){const n=t instanceof Error?t.message:"Unknown error";return Ro({message:`Failed to read keybindings file: ${n}`,keybindingsPath:e})}},"readKeybindingsFile"),No=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(bo,null,2);if(Po(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Ro({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?Ro({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,o+1)+",\n"+n+e.substring(o+1)},"generateNewContent");function setupVSCodeTerminal(){const e=Mo();try{const t=Oo(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=Lo(r);if(o.hasConflicting)return Ro({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return Fo({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=No({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(Q.writeFileSync(e,s,"utf-8"),Fo({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Ro({message:`Failed to configure VSCode key binding: ${t instanceof Error?t.message:"Unknown error"}`,keybindingsPath:e})}}function isVSCodeTerminal(){return"vscode"===process.env.TERM_PROGRAM}__name(setupVSCodeTerminal,"setupVSCodeTerminal"),__name(isVSCodeTerminal,"isVSCodeTerminal");var Uo={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return Uo[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(e=process.cwd()){const t=ye(e);return B.join(J.homedir(),".commandcode","projects",t)}function getGlobalProjectSettingsPath(e=process.cwd()){return B.join(getGlobalProjectSettingsDir(e),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await M.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(e,t=process.cwd()){try{const n=getGlobalProjectSettingsPath(t),r=B.dirname(n);await M.mkdir(r,{recursive:!0}),await M.writeFile(n,JSON.stringify(e,null,2))}catch(e){const t=e instanceof Error?e.message:String(e);dlog("Error saving global project settings:",e),ao.addEvent({type:"error",message:`Failed to save global project settings: ${t}`})}}async function loadLocalProjectSettings(e=process.cwd()){try{const t=B.join(e,".commandcode","settings.local.json"),n=await M.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function loadMergedProjectSettings(e=process.cwd()){try{const t=mergeSettings(await loadGlobalProjectSettings(e),await loadLocalProjectSettings(e)),n=t.tasteOnboarding,r=n?.learnedSessions?.["claude-code"]?.length||0;return dlog(`[Config] project settings loaded (taste: ${n?.completed?"complete":n?.skipped?"skipped":"pending"}, learned: ${r} sessions)`),t}catch(e){return dlog("[Settings] error loading",e),{}}}function mergeSettings(e,t){const n={...e};return t.tasteOnboarding&&(n.tasteOnboarding={...e.tasteOnboarding,...t.tasteOnboarding},(e.tasteOnboarding?.learnedSessions||t.tasteOnboarding?.learnedSessions)&&(n.tasteOnboarding.learnedSessions={...e.tasteOnboarding?.learnedSessions,...t.tasteOnboarding?.learnedSessions})),n}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName,"getProjectDirName"),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings");var jo=B.join(K.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=se(e,{encoding:"utf8"}),n=Se.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(e,t){const n=[];try{await M.access(e)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const r=await M.readdir(e);for(const o of r){if(!/^\d{4}$/.test(o))continue;const r=B.join(e,o);if(!(await M.stat(r)).isDirectory())continue;const s=await M.readdir(r);for(const e of s){if(!/^\d{2}$/.test(e))continue;const s=B.join(r,e);if(!(await M.stat(s)).isDirectory())continue;const a=await M.readdir(s);for(const r of a){if(!/^\d{2}$/.test(r))continue;const a=B.join(s,r);if(!(await M.stat(a)).isDirectory())continue;t?.({phase:"scanning",totalFiles:n.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${e}/${r}`});const i=(await M.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(e=>B.join(a,e));n.push(...i)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return n}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const a=e.slice(s,s+n),i=await Promise.all(a.map(t));for(const e of i)null!==e&&o.push(e);r?.(Math.min(s+n,e.length),e.length)}return o}async function findCodexSessions(e,t,n=0){const r=e||process.cwd(),o=[];dlog(`[Codex] scanning for project: ${r}`);const s=await findAllSessionFiles(jo,t);if(0===s.length)return dlog("[Codex] no session files found"),t?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${s.length} session files to scan`),t?.({phase:"reading",totalFiles:s.length,processedFiles:0,matchedSessions:0});let a=0;const i=await processFilesInBatches(s,async e=>{const t=await readSessionMeta(e);if(!t)return null;if(t.cwd===r)try{const n=await M.stat(e),r=B.basename(e,".jsonl");return{id:t.id||r,filePath:e,createdAt:new Date(t.timestamp||n.birthtime),lastModified:n.mtime,messageCount:0,agent:"codex",projectDir:t.cwd}}catch{return null}return null},10,(e,n)=>{a=o.length,t?.({phase:"reading",totalFiles:n,processedFiles:e,matchedSessions:a})});o.push(...i);const c=n>0?o.slice(0,n):o;return dlog(`[Codex] matched ${c.length} sessions for project`),t?.({phase:"complete",totalFiles:s.length,processedFiles:s.length,matchedSessions:c.length}),c.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await M.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=!0===e?.demoShown;if(isOnboardingDone(e))return dlog("[Onboarding] "+(e?.skipped?"user skipped":"already completed")),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[],demoShown:t};const n=await findNewSessions(e?.learnedSessions||{}),r=(n["claude-code"]?.length||0)+(n.codex?.length||0);return r>0?(dlog(`[Onboarding] found ${r} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:r,hasTasteContent:!0,agentSessions:buildAgentSessionsList(n),demoShown:t}):t?(dlog("[Onboarding] no new sessions to learn from"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t}):(dlog("[Onboarding] first time user, will show demo"),{shouldTrigger:!0,reason:"no_sessions",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:!1}}}async function getSessionFilesFromDir(e){try{return(await M.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(e){const t={},n=e["claude-code"]||[],r=e.codex||[];try{const e=B.join(K.homedir(),".claude","projects");await M.access(e);const r=getProjectDirName(process.cwd()),o=(await M.readdir(e)).filter(e=>e===r);for(const r of o){const o=B.join(e,r);if((await M.stat(o)).isDirectory()){const e=await getSessionFilesFromDir(o);e.length>0&&(t["claude-code"]=e.filter(e=>!n.includes(e)))}}dlog(`[Sessions] claude-code: ${t["claude-code"]?.length||0} new, ${n.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(t.codex=e.filter(e=>!r.includes(e)));dlog(`[Sessions] codex: ${t.codex?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}return t}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0,await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function markDemoShown(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.demoShown=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markDemoShown,"markDemoShown"),__name(triggerTasteOnboarding,"triggerTasteOnboarding");var _o="# Taste (Continuously Learned by CommandCode.ai)",Bo=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return Bo.test(t)?t.replace(Bo,`$1${_o}`):t}__name(migrateHeader,"migrateHeader");var Wo=class{static{__name(this,"TasteManager")}static async initializeProject(){const e=process.cwd(),t=B.join(e,".commandcode","taste");await M.mkdir(t,{recursive:!0});const n=B.join(t,"taste.md");try{await M.access(n);const e=await M.readFile(n,"utf-8"),t=migrateHeader({content:e});t!==e&&await M.writeFile(n,t,"utf-8")}catch{await M.writeFile(n,_o+"\n\n")}}static async isInitialized(){const e=process.cwd(),t=B.join(e,".commandcode","taste");try{return await M.access(t),!0}catch{return!1}}},Ho=__name(()=>W.join(J.homedir(),".commandcode","agents"),"getRootAgentDir"),zo=__name(()=>W.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),Go=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=P("idle"),[s,a]=P(""),i=[...eo.map(e=>e.name),...to.map(e=>e.name)],c=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void a("Agent configuration is incomplete");o("saving");try{const n="personal"===e.location?Ho():zo();await L.mkdir(n,{recursive:!0});const r=`${e.agentType}.md`,o=W.join(n,r),s=Array.from(e.selectedTools).map(e=>oo[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===i.length?'"*"':JSON.stringify(s),c=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await L.writeFile(o,c,"utf-8"),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");k((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||c()});const l=Array.from(e.selectedTools).map(e=>oo[e]||e).join(", "),d="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return A.createElement(y,{flexDirection:"column",gap:1},A.createElement(y,{flexDirection:"column"},A.createElement(y,{gap:1},A.createElement(w,{color:"white",bold:!0},"Name:"),A.createElement(w,{color:"gray"},e.agentType)),A.createElement(y,{gap:1},A.createElement(w,{color:"white",bold:!0},"Location:"),A.createElement(w,{color:"gray"},d)),A.createElement(y,{gap:1},A.createElement(w,{color:"white",bold:!0},"Tools:"),A.createElement(w,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===i.length?"*":l))),A.createElement(y,{gap:1},A.createElement(w,{color:"white",bold:!0},"Description"),A.createElement(w,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),A.createElement(w,{color:"gray"},e.ccToolDefinition),A.createElement(y,{gap:1},A.createElement(w,{color:"white",bold:!0},"System Prompt:")),A.createElement(w,{color:"gray"},e.sysPrompt),!n&&A.createElement(y,{marginTop:1},"idle"===r&&A.createElement(y,{gap:1},A.createElement(w,{color:"green",dimColor:!0},"Press"),A.createElement(w,{color:"green",bold:!0},"Enter"),A.createElement(w,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===r&&A.createElement(w,{color:"yellow"},"Saving agent..."),"saved"===r&&A.createElement(w,{color:"green"},"✓ ",s),"error"===r&&A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"red"},"✗ Error: ",s),A.createElement(w,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),qo=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=P("menu"),a=[...eo.map(e=>e.name),...to.map(e=>e.name)];let i=new Set;if("*"===e.tools||'"*"'===e.tools)i=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>so[e]||e);i=new Set(t)}const c={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(k((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return A.createElement(y,{flexDirection:"column"},A.createElement(Go,{config:c,onSaveComplete:()=>s("menu"),viewOnly:!0}),A.createElement(y,{marginTop:1},A.createElement(w,{color:"gray"},"Press Enter to go back")));if("edit"===o)return A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"yellow"},"Edit functionality coming soon..."),A.createElement(w,{color:"gray"},"Press Esc to go back"));if("delete"===o){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],o=__name(async r=>{if("confirm-delete"===r.value)try{await L.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return A.createElement(y,{flexDirection:"column",gap:1},A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"red"},"Delete agent"),A.createElement(w,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),A.createElement(y,null,A.createElement(Ce,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>A.createElement(w,{color:e?"white":"gray"},` ${t}`)})))}return A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"white",bold:!0},e.name),A.createElement(y,{marginTop:1},A.createElement(Ce,{items:l,onSelect:d,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>A.createElement(w,{color:e?"white":"gray"},` ${t}`)})),A.createElement(y,{marginTop:1},A.createElement(w,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),Vo=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=P([]),[o,s]=P([]),[a,i]=P([]),[c,l]=P(!0),[d,u]=P(!1),[m,g]=P(null),[p,h]=P(!1),f=__name(()=>W.join(J.homedir(),".commandcode","agents"),"getRootAgentDir"),E=__name(()=>W.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),b=__name(async(e,t)=>{try{u(!1);const n=(await L.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=W.join(e,n),o=await L.readFile(r,"utf-8"),{data:s,content:a}=me(o);let i=s.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:s.name||n.replace(".md",""),description:s.description||"",tools:i,sysPrompt:a.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");I(()=>{__name(async()=>{l(!0);const[e,t]=await Promise.all([b(f(),"personal"),b(E(),"project")]),n=Vr.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));r(e),s(t),i(n),l(!1)},"loadAgents")()},[d]);const k=[{label:"Create new agent",value:"create_new_agent"}];n.forEach(e=>{k.push({label:e.name,value:e.filePath})}),o.forEach(e=>{k.push({label:e.name,value:e.filePath})});const S=n.length+o.length,C=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...n,...o].find(e=>e.filePath===t.value);e&&(g(e),h(!0))}},"handleAgentSelect");if(c)return A.createElement(w,{color:"gray"},"Loading agents...");if(p&&m){const e=m.filePath.startsWith("__builtin__:");return A.createElement(qo,{agent:m,onBack:()=>{h(!1),g(null)},setRevalidateAgent:u,isReadOnly:e})}const v=__name(({isSelected:e,label:t})=>{const r=k.find(e=>e.label===t),s=r?.value||"",a=n[0]?.filePath===s,i=o[0]?.filePath===s;return A.createElement(y,{flexDirection:"column"},a&&n.length>0&&A.createElement(y,{marginTop:1},A.createElement(w,{color:"gray",bold:!0},"User agents")),i&&o.length>0&&A.createElement(y,{marginTop:1},A.createElement(w,{color:"gray",bold:!0},"Project agents")),A.createElement(y,null,A.createElement(w,{color:"white"},e?">":" "),A.createElement(w,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return A.createElement(y,{flexDirection:"column"},A.createElement(y,{marginBottom:1},A.createElement(w,{color:"white",bold:!0},"Agents"),S>0?A.createElement(w,{color:"gray"}," ","(",S," agent",S>1?"s":"",")"):A.createElement(w,{color:"gray"}," (No custom agents)")),t&&A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(w,{color:"green",dimColor:!0},"Created agent: ",t)),A.createElement(Ce,{items:k,onSelect:C,indicatorComponent:()=>null,itemComponent:v}),a.length>0&&A.createElement(y,{flexDirection:"column",marginTop:1},A.createElement(w,{color:"gray",bold:!0},"Default agents"),a.map(e=>A.createElement(w,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),A.createElement(y,{flexDirection:"column",marginTop:1},A.createElement(w,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),A.createElement(w,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents"),Ko=__name(({onSelect:e})=>A.createElement(Ce,{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})=>A.createElement(w,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>A.createElement(w,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector"),Jo=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=P(!1),[m,g]=P(!1),p=$(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),h=$(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[m,a]);return"agentType"===e?A.createElement(A.Fragment,null,A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(oo).some(e=>ye(e)===ye(t))||Object.keys(oo).some(e=>ye(e)===ye(t)))&&A.createElement(w,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(ye(t))&&A.createElement(w,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",qr.join(", "))),A.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=ye(t);Object.values(oo).some(t=>ye(t)===e)||Object.keys(oo).some(t=>ye(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?A.createElement(A.Fragment,null,A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"white"},"Enter the system prompt for your agent:"),A.createElement(w,{color:"gray"},"Be comprehensive for best results.")),A.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?A.createElement(A.Fragment,null,A.createElement(w,{color:"white"},"When should ","Command Code"," use this agent?"),A.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow"),Yo=__name(({onSelect:e})=>A.createElement(Ce,{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})=>A.createElement(w,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>A.createElement(w,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector"),Qo=["·","○","◇","☆","✧","☆","◇","○","⌘"],Zo=[8,5,4,4,4,4,4,5,20],Xo=[5,4,4,4,4,4,5],es=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Zo.length;e++)if(n+=Zo[e],t<n)return Qo[e];const r=t-58;n=0;for(let e=0;e<Xo.length;e++)if(n+=Xo[e],r<n)return Qo[7-e];return Qo[0]},"getWaveSymbol"),ts=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=P(0);I(()=>{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<ts.length?ts[n]:"#B799E6"},"getCharColor");return A.createElement(w,null,e.split("").map((e,t)=>A.createElement(w,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=P(0);return I(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),A.createElement(w,{color:"#E4CCFF",bold:!0},es(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var ns=__name(({status:e,timeElapsed:t,tokens:n})=>{const[o,s]=P(0),a=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}I(()=>{if(o===n)return;const e=n-o,t=Math.max(1,Math.ceil(Math.abs(e)/20)),r=e>0?t:-t,a=setInterval(()=>{s(e=>{const t=e+r;return r>0&&t>=n||r<0&&t<=n?n:t})},30);return()=>clearInterval(a)},[n,o]),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");const i=a>70,c=a>40&&a<=70;return A.createElement(y,{width:a,height:1,paddingLeft:0,marginLeft:0},A.createElement(CMDIcon,null),A.createElement(y,{marginRight:1},A.createElement(ShimmerText,{text:e})),i?A.createElement(A.Fragment,null,A.createElement(y,{columnGap:1},A.createElement(w,{dimColor:!0},`(${formatTime3(t)}`),A.createElement(w,{dimColor:!0},"•"),A.createElement(w,{color:"gray"},r.arrowDown),A.createElement(w,{dimColor:!0},`${formatToken(Math.round(o))}`),A.createElement(w,{dimColor:!0},"•"),A.createElement(y,{columnGap:1},A.createElement(w,{bold:!0,color:"gray"},"esc"),A.createElement(w,{dimColor:!0},"to interrupt)")))):c?A.createElement(y,{columnGap:1},A.createElement(w,{dimColor:!0},`(${formatToken(Math.round(o))})`)):A.createElement(A.Fragment,null))},"Status"),rs=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:s})=>{const[a,i]=P(!1),[c,l]=P(0),d=$(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||a){if(!a||n.isPasteEnd){if(a&&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)))}},[a,t]);return A.createElement(y,{flexDirection:"column"},r?A.createElement(y,null,A.createElement(CMDIcon,null),A.createElement(w,{color:"white"},"Generating agent from description...")):A.createElement(TextInput,{key:c,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:d,onSubmit:()=>{0!==e.trim().length&&n()}}),s&&A.createElement(y,{marginTop:1},A.createElement(w,{color:"red"},`${o.warning} ${s}`)))},"RecommendedFlow"),os=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=P(!1),[a,i]=P(0),c=D(()=>[...eo.map(e=>e.name),...to.map(e=>e.name)],[]),l=D(()=>[{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=D(()=>{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]":"[ ]"} ${oo[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 k((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[a];if(e){const a=d[e.value];if(!a)return;"continue"===a.type?r():"toggle"===a.type?(s(!o),i(0)):"category"===a.type?n(a.value):"tool"===a.type&&t(a.value)}}}),A.createElement(y,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return A.createElement(y,{key:`divider-${t}`},A.createElement(w,{color:"gray"}," ",e.label));if("spacer"===e.type)return A.createElement(y,{key:`spacer-${t}`,height:1});if("label"===e.type)return A.createElement(y,{key:`label-${t}`},A.createElement(w,{color:"gray"}," ",e.label));const o="continue"===e.type;return A.createElement(y,{key:`item-${t}`},A.createElement(w,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),A.createElement(y,{marginTop:1},e.size===c.length&&A.createElement(w,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&A.createElement(w,{color:"gray"},e.size," tools selected"),0===e.size&&A.createElement(w,{color:"gray"},"No tools selected")))},"ToolsSelector"),ss=__name(({onComplete:e})=>{const[t,n]=P("location"),[r,o]=P(!1),[s,a]=P(null),[i,c]=P("agentType"),l=D(()=>[...eo.map(e=>e.name),...to.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=P(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"),E=__name(async()=>{try{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===Ke&&(r=await yt.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[Be]:t.toString()};r&&(s[We]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new pn({baseUrl:i}),l=await c.post({headers:s,endpoint:Ge.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:ye(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof sn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(bt):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),b=__name(()=>{m({...u,agentType:ye(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),k=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),S=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),C=__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"),T=__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 A.createElement(y,{flexDirection:"column",gap:1},A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"white",bold:!0},"Create new agent"),A.createElement(w,{color:"gray"},p())),A.createElement(y,null,"location"===t&&A.createElement(Ko,{onSelect:h}),"method"===t&&A.createElement(Yo,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&A.createElement(rs,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:E}),"configuration"===t&&"manual"===u.method&&A.createElement(y,{flexDirection:"column",gap:1},A.createElement(Jo,{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:b,onSysPromptSubmit:k,onCCToolDefinitionSubmit:S})),"tools"===t&&A.createElement(os,{selectedTools:u.selectedTools,onToggleTool:v,onToggleCategory:T,onComplete:C}),"summary"===t&&A.createElement(Go,{config:u,onSaveComplete:g})))},"AgentNew"),as=__name(({onCancel:e})=>{const[t,n]=P(null),[r,o]=P(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return k((t,n)=>{n.escape&&e()}),A.createElement(y,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&A.createElement(Vo,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&A.createElement(ss,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig"),is=__name(({messages:e})=>0===e.length?null:A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(y,{marginBottom:0},A.createElement(w,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>A.createElement(y,{key:t},A.createElement(w,{dimColor:!0},o.pointerSmall," "),A.createElement(w,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages");function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedImages:n,detectedContent:r,setInput:o,setDetectedImages:s,setDetectedContent:a,incrementInputKey:i}=e,c=x(!1),l=x(""),d=x(null),u=x(""),m=$(async(e,t)=>{let c=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectClipboardImage();if(l){const e=`[Image#${n.length+1}]`;return s(e=>[...e,l]),o(t+e),void i()}let d=c;if(!d.trim()){const e=await detectClipboardText();d=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(d){if(d.length>300){const e=`[Text#${r.length+1}]`;a(e=>[...e,d]),o(t+e)}else o(t+d);i()}},[n.length,r.length,s,a,o,i]),g=$(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(c.current){const e=l.current,t=u.current;l.current="",u.current="",c.current=!1,d.current=null,e&&await m(e,t)}},500)},[m]);return{handlePaste:$(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return c.current&&(c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)),await m(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!c.current)return c.current=!0,u.current=n.textBeforePaste??t,l.current=n.pastedContent??n.cleanedContent,g(),!0;if(c.current&&!n.isPasteEnd)return void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current)),g(),!0;if(c.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current));const e=l.current,t=u.current;return l.current="",u.current="",c.current=!1,await m(e,t),!0}return!(!n.isPasteEnd||n.isPasteStart||c.current)},[t,m,g]),resetPasteState:$(()=>{c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:$(()=>c.current,[])}}__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste");var cs=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.COMPACT="/compact",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.TERMINAL_SETUP="/terminal-setup",e))(cs||{}),ls=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"},{command:"/terminal-setup",description:"Setup VSCode keybindings"}];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 ds=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=P(0),[s,a]=P(0),{stdout:i}=C(),c=i?.columns??80,l=Math.max(20,c-22-2-1-2),d=D(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...ls.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),u=D(()=>{const e=s,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,s]);return I(()=>{o(0),a(0)},[n]),k((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<s&&a(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=s+8&&a(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?A.createElement(y,{flexDirection:"column",paddingLeft:2},A.createElement(w,{color:"dim"},"No commands found")):(d.length,A.createElement(y,{flexDirection:"column",paddingLeft:1},A.createElement(y,{columnGap:2},A.createElement(y,{flexDirection:"column",width:22},u.map((e,t)=>{const n=s+t;return A.createElement(w,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),A.createElement(y,{flexDirection:"column"},u.map((e,t)=>{const n=s+t;return A.createElement(w,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateText({text:e.description,maxWidth:l}))})))))},"CommandMenu"),us=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?"red":e>=70?"yellow":"dim","getColor"),o=`context: ${n}% left before auto-compact`;return A.createElement(y,{paddingRight:1},A.createElement(w,{color:r(t)},o))},"ContextUsage");function loadGitignore(e){const t=ve(),n=G(e,".gitignore");if(X(n))try{const e=ee(n,"utf8");t.add(e)}catch{}return t.add(".git"),t}__name(loadGitignore,"loadGitignore");var ms=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=P(process.cwd()),[s,a]=P([]),[i,c]=P(0),[l,d]=P(0),u=n.trim()?15:10,m=$((e,t=process.cwd())=>{if(!e.trim())return[];const n=loadGitignore(t);if(e.endsWith("/")){const r=G(t,e);try{const e=re(r),o=[];return e.forEach(e=>{const s=G(r,e);try{const e=oe(s),r=H(t,s);if(n.ignores(r))return;o.push({name:r,path:s,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()||"",s=G(t,r.join("/"));try{const e=re(s),r=[],a=o.toLowerCase();return e.forEach(e=>{const i=e.toLowerCase();if(!o||i.includes(a)){const o=G(s,e);try{const e=oe(o),s=H(t,o);if(n.ignores(s))return;r.push({name:s,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(),s=__name((e,a=0)=>{if(!(a>8))try{re(e).forEach(i=>{const c=G(e,i);try{const e=oe(c),l=H(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&&s(c,a+1)}catch(e){}})}catch(e){}},"searchRecursively");return s(t),r.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),s=n===o,a=r===o;if(s&&!a)return-1;if(!s&&a)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=$(e=>{try{const t=re(e),n=[],r=process.cwd(),o=loadGitignore(r);"/"!==e&&n.push({name:"..",path:z(e),isDirectory:!0}),t.forEach(t=>{const s=G(e,t);try{const e=oe(s),a=H(r,s);if(o.ignores(a))return;n.push({name:t,path:s,isDirectory:e.isDirectory()})}catch{}}),n.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),a(n),c(0),d(0)}catch{}},[]);I(()=>{if(n.trim()){const e=m(n);a(e),c(0),d(0)}else g(r)},[r,g,n,m]),k((r,a)=>{if(a.escape)t();else if(a.upArrow)c(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t});else if(a.downArrow)c(e=>{const t=Math.min(s.length-1,e+1);return t>=l+u&&d(t-u+1),t});else{if(a.rightArrow){const e=s[i];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(V(e.path)))}if(a.return){const t=s[i];if(!t)return;return void e(t.path)}}});const p=s.slice(l,l+u);return A.createElement(y,{flexDirection:"column",paddingLeft:1},A.createElement(y,{marginBottom:1,flexDirection:"column"},A.createElement(w,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),A.createElement(w,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===p.length?A.createElement(w,{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 A.createElement(w,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),gs=__name(()=>{const[e,t]=P("continuous learning"),n=x([]),r=x(0),o=x(null),s=x(!1);I(()=>{const e=__name(e=>"analyzing"===e.type?(s.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):s.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(s.current=!1,void(n.current.length>0?(r.current=0,a()):t("continuous learning"))):void 0,"handleNewEvent"),a=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const s="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,a()},s)},"cycleThroughNextEvent");return ao.on("new-event",e),()=>{ao.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+19>100;let i=e;if(a){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 A.createElement(y,null,!a&&A.createElement(w,{color:"green"},"● taste: "),A.createElement(w,null,i),!a&&A.createElement(w,{dimColor:!0}," (ctrl+t to expand)"))},"LearningFeedMini"),ps=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=P([]),[s,a]=P(0),[i,c]=P(!0);I(()=>{l()},[]);const l=__name(async()=>{c(!0);const e=await Yr.listSessions();r(e.slice(0,30)),c(!1)},"loadSessions");if(k((r,o)=>{o.escape?t():o.upArrow?a(e=>Math.max(0,e-1)):o.downArrow?a(e=>Math.min(n.length-1,e+1)):o.return&&n.length>0&&s<n.length&&e(n[s].id)}),i)return A.createElement(y,{flexDirection:"column",paddingLeft:2},A.createElement(w,{color:"gray"},"Loading sessions..."));if(0===n.length)return A.createElement(y,{flexDirection:"column",paddingLeft:2},A.createElement(w,{color:"gray"},"No previous sessions found"),A.createElement(w,{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),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),u=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return A.createElement(y,{flexDirection:"column",paddingLeft:1,width:"100%"},A.createElement(w,{color:"cyan",bold:!0},"Resume Session"),A.createElement(w,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),A.createElement(y,{marginTop:1}),A.createElement(y,{columnGap:2,marginBottom:1},A.createElement(y,{width:5},A.createElement(w,{color:"gray"}," ")),A.createElement(y,{width:13},A.createElement(w,{color:"gray"},"Modified")),A.createElement(y,{width:20},A.createElement(w,{color:"gray"},"Git Branch")),A.createElement(y,{width:11},A.createElement(w,{color:"gray"},"# Messages")),A.createElement(y,null,A.createElement(w,{color:"gray"},"Summary"))),A.createElement(y,{columnGap:2},A.createElement(y,{flexDirection:"column",width:5},n.map((e,t)=>A.createElement(w,{key:`sel-${t}`,color:s===t?"white":"gray"},s===t?`${o.pointer} ${t+1}.`:` ${t+1}.`))),A.createElement(y,{flexDirection:"column",width:13},n.map((e,t)=>A.createElement(w,{key:`mod-${e.id}`,color:s===t?"white":"gray"},d(e.lastModified)))),A.createElement(y,{flexDirection:"column",width:20},n.map((e,t)=>A.createElement(w,{key:`branch-${e.id}`,color:s===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),A.createElement(y,{flexDirection:"column",width:11},n.map((e,t)=>A.createElement(w,{key:`msg-${e.id}`,color:s===t?"white":"gray"},e.messageCount))),A.createElement(y,{flexDirection:"column"},n.map((e,t)=>A.createElement(w,{key:`summary-${e.id}`,color:s===t?"white":"gray"},u(e.firstMessage))))))},"SessionsResumeTable"),hs=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],fs=["","","[118;5u"];function isNewlineShortcutKey(e){const{inputChar:t,key:n,isPasting:r}=e;return!r&&(!(!n.return||!n.shift)||!(!n.ctrl||!n.return)||!(!n.ctrl||"j"!==t)||!("\r"!==t||n.return||n.ctrl||n.shift||n.meta)||hs.includes(t))}__name(isNewlineShortcutKey,"isNewlineShortcutKey");var ys=__name(()=>A.createElement(y,{flexDirection:"column",paddingLeft:1},A.createElement(w,{color:"dim",bold:!0},"Available Shortcuts:"),A.createElement(y,{columnGap:4},A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"dim"},"! for bash mode"),A.createElement(w,{color:"dim"},"/ for commands"),A.createElement(w,{color:"dim"},"@ for file paths"),A.createElement(w,{color:"dim"},"shift + tab to toggle auto-accept")),A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"dim"},"double tap esc to clear input"),A.createElement(w,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),A.createElement(w,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),ws=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:s="Enter your input…",showFileList:a,setShowFileList:i,fileSearchQuery:c,setFileSearchQuery:l,onCommand:d,contextUsage:u,tasteLearning:m=!1,tasteUsage:g=!1,shareInfo:p,showShareNotification:h,unshareNotificationMessage:f,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:S,currentProvider:C,showProviderInfo:v,autoAcceptMode:T=!1,onToggleAutoAccept:F,hintMessage:R,historyManager:M,pendingExitKey:L=null,onOverlayVisibilityChange:O,onDoubleEscapeEmpty:N})=>{const[U,j]=P(0),[_,B]=P(!1),[W,z]=P(!1),[G,q]=P(!1),[V,K]=P(!1),[J,Y]=P(""),[Q,Z]=P(!1),[X,ee]=P(0),[te,ne]=P([]),[re,oe]=P([]),[se,ae]=P(""),ie=x(!1),ce=x(!1),[le,de]=P(-1),[ue,me]=P(""),ge=x(0),{handlePaste:pe,resetPasteState:he,isPasting:fe}=useBracketedPaste({input:e,detectedImages:re,detectedContent:te,setInput:n,setDetectedImages:oe,setDetectedContent:ne,incrementInputKey:__name(()=>j(e=>e+1),"incrementInputKey")});I(()=>{const e=a||V||Q;O?.(e)},[a,V,Q,O]);const ye=$(()=>{n(""),z(!1),K(!1),Y(""),Z(!1),ne([]),oe([]),ae(""),he(),de(-1),me(""),j(e=>e+1)},[n,he]);k(async(t,r)=>{if(r.upArrow){if(a||V||Q)return;const t=e.indexOf("\n"),r=-1===t||ge.current<=t;if(0!==e.length&&-1===le&&!r)return;const o=M?.count()??0;if(0===o)return;-1===le&&me(e);const s=Math.min(le+1,o-1);return void(s!==le&&(de(s),n(M?.getAt(s)||""),j(e=>e+1)))}if(r.downArrow){if(a||V||Q)return;if(-1===le)return;const t=e.lastIndexOf("\n");if(!(-1===t||ge.current>t))return;const r=le-1;return de(r),n(-1===r?ue:M?.getAt(r)||""),void j(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return;if(getIsExpandToolShortcut(r,t))return ie.current=!0,n(e),j(e=>e+1),void setTimeout(()=>{ie.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:fe()}))return ce.current=!0,ie.current=!0,n(e+"\n"),j(e=>e+1),void setTimeout(()=>{ce.current=!1,ie.current=!1},0);if(r.meta&&r.backspace)return void ye();if(r.meta&&"w"===t)return ie.current=!0,void ye();const o=r.ctrl&&"v"===t||fs.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();if(r){const e=`[Image#${re.length+1}]`;oe(e=>[...e,r]),n(t+e),j(e=>e+1)}return void(ie.current=!0)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return q(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(r.escape){if(V)return;if(Q)return Z(!1),n(se),void j(e=>e+1);const t=Date.now();return t-X<500?(e.length>0?ye():N?.(),ee(0)):ee(t),B(!1),void z(!1)}_&&(r.backspace||r.delete)&&0===e.length&&B(!1)}});const we=$(async t=>{if(await pe(t))return;if(ie.current)return void(ie.current=!1);-1!==le&&de(-1);const r=1===t.length,o=t.slice(-1);if(r){if("?"===o&&!_)return B(!0),n(""),void j(e=>e+1);if("!"===o&&!W)return B(!1),z(!0),n(""),void j(e=>e+1)}if("/"!==o||V||"/"!==t||(K(!0),Y("")),V&&!t.startsWith("/")&&(K(!1),Y("")),V&&t.startsWith("/")){const e=t.substring(1);Y(e)}"@"!==o||a||(i(!0),l(""));const s=t.lastIndexOf("@");if(t.length<e.length&&-1!==s&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(s+1);!e.includes(" ")&&(i(!0),l(e))}if(a)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)i(!1),l("");else{const n=t.substring(e+1);l(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);l(e),i(!1)}else l(n)}}_&&(t!==e||t.length<e.length)&&B(!1),0===t.length&&(z(!1),K(!1),Y(""),Z(!1),oe([]),ne([]),l(""),ae(""),he()),n(t)},[_,e,n,a,i,V,W,re,le,pe,he]),Ee=$(async()=>{if(_)return void B(!1);let n=e.trim();if(!W&&n.startsWith("/"))return M?.add(n),d&&d(n),z(!1),K(!1),Y(""),oe([]),ne([]),de(-1),void me("");n.length>0&&M?.add(n),de(-1),me("");let r=[];const o=re.length>0,s=te.length>0;if(!W&&o){const e=[];re.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!W&&s){let e=n;te.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:W?"bash":"user",images:r}),z(!1),K(!1),Y(""),oe([]),ne([])},[t,d,_,e,W,re,te,M]),be=$(t=>{const r=H(process.cwd(),t);let o;if(a&&""!==c){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),i(!1),l(""),j(e=>e+1)},[n,i,e,a,c,l]),ke=$(()=>{i(!1),l("")},[i,l]),Se=$(t=>{if("/resume"===t)M?.add(t),de(-1),me(""),ae(e),K(!1),Y(""),Z(!0),n(""),j(e=>e+1);else{const e=Object.values(cs).includes(t);K(!1),Y(""),e?(M?.add(t),de(-1),me(""),n(""),j(e=>e+1),d&&d(t)):(n(t+" "),j(e=>e+1))}},[d,n,e,M]),Ce=$(()=>{K(!1),Y(""),n(""),de(-1),me(""),j(e=>e+1)},[n]),ve=$(e=>{Z(!1),n(""),ae(""),de(-1),me(""),j(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Te=$(()=>{Z(!1),n(se),de(-1),me(""),j(e=>e+1)},[se,n]),Ae=$(e=>{ge.current=e},[]),Pe=D(()=>T?!_&&!Q:!_&&0===e.length&&!W&&!Q,[_,e,W,Q,T]),xe=__name(()=>_||a||V||Q||G?0:Pe||L||W?3:4,"getBottomMargin");return A.createElement(y,{width:"100%",flexDirection:"column",marginBottom:xe()},!Q&&A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(w,{color:W?"green":"gray"},o.line.repeat(process.stdout.columns||80)),A.createElement(TextInput,{key:U,value:e,placeholder:s,onChange:we,onSubmit:()=>{ce.current?ce.current=!1:a||V||Q||Ee()},showCursor:r,onCursorChange:Ae,prefix:`${W?"!":o.pointer} `,prefixColor:W?"green":"white"}),A.createElement(w,{color:W?"green":"gray"},o.line.repeat(process.stdout.columns||80))),_&&A.createElement(ys,null),G&&A.createElement(y,{paddingTop:1},A.createElement(w,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),a&&A.createElement(ms,{onSelectFile:be,onClose:ke,searchQuery:c}),V&&A.createElement(ds,{onSelectCommand:Se,onClose:Ce,searchQuery:J}),Q&&A.createElement(ps,{onSelectSession:ve,onClose:Te}),(Pe||L)&&A.createElement(y,{flexDirection:"column",paddingLeft:1},A.createElement(y,{flexDirection:"row",justifyContent:"space-between"},A.createElement(y,null,L?A.createElement(w,{dimColor:!0},"Press Ctrl+C again to exit"):T?A.createElement(y,{flexDirection:"row"},A.createElement(w,{color:"#E4CCFF"},"» accept edits on"," "),A.createElement(w,{dimColor:!0},"(shift+tab to toggle)")):A.createElement(w,{color:"dim"},"? shortcuts")),A.createElement(y,{flexDirection:"column",alignItems:"flex-end"},m&&A.createElement(gs,null),u&&A.createElement(us,{usage:u}))),(b||S||v&&C)&&A.createElement(y,{flexDirection:"row",columnGap:1},b&&A.createElement(w,null,o.tick," ","Command Code"," updated:"," ",A.createElement(w,{dimColor:!0},"v",b.updatedFrom),A.createElement(w,{dimColor:!0}," ",o.arrowRight," "),A.createElement(w,null,"v",b.updatedTo)),!b&&S&&A.createElement(w,{color:"yellow",dimColor:!0},o.info," Update available:"," ",S.currentVersion," ",o.arrowRight," ",S.latestVersion),v&&C&&A.createElement(w,{color:"green",dimColor:!0},o.bullet," Provider:"," ",getProviderDisplayName(C)))),W&&A.createElement(y,{paddingLeft:1},A.createElement(w,{color:"green"},"! for bash mode")),h&&p&&A.createElement(y,{paddingLeft:1},A.createElement(w,{color:"#E4CCFF"},"SHARED: ",p.url," (copied to clipboard)")),f&&A.createElement(y,{paddingLeft:1},A.createElement(w,{color:f.includes("NOT SHARED")?"red":"#E4CCFF"},f)),E&&A.createElement(y,{paddingLeft:1},A.createElement(w,{color:"#E4CCFF"},E)))},"InputBox"),Es=A.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:E,unshareNotificationMessage:b,tasteNotificationMessage:k,updateStatus:S,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,autoAcceptMode:$,onToggleAutoAccept:D,hintMessage:F,historyManager:R,pendingExitKey:M,onResetPendingExitKey:L,onDoubleEscapeEmpty:O,retryAttempt:N})=>{const[U,j]=P(0),_=x(o);return I(()=>{M&&o!==_.current&&o.length>0&&L?.(),_.current=o},[o,M,L]),I(()=>{if(!t)return void j(0);const e=setInterval(()=>{j(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),A.createElement(y,{flexDirection:"column"},A.createElement(is,{messages:e}),A.createElement(y,{flexDirection:"row",justifyContent:"space-between"},A.createElement(y,{flexDirection:"column"},(t||n.isExecuting)&&null===N&&A.createElement(ns,{tokens:m,timeElapsed:U,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),F&&A.createElement(y,{marginLeft:1},A.createElement(w,{dimColor:!0}," ","⎿"," Tip: ",F)))),A.createElement(ws,{input:o,setInput:s,onSubmit:a,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:E,unshareNotificationMessage:b,tasteNotificationMessage:k,updateStatus:S,updateFailedInfo:C,currentProvider:v,showProviderInfo:T,autoAcceptMode:$,onToggleAutoAccept:D,hintMessage:F,historyManager:R,pendingExitKey:!M||t||n.isExecuting?null:M,onDoubleEscapeEmpty:O}))}),bs=__name(({onClose:e})=>{const[t,n]=P(ao.getEvents());k((t,n)=>{n.ctrl&&"t"===t&&(yo(),e())},{isActive:!0}),I(()=>{const e=__name(()=>{n(ao.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return ao.on("new-event",e),ao.on("cleared",t),()=>{ao.off("new-event",e),ao.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),s=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const a={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:a,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),a=__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 A.createElement(y,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(Te,{name:"vice"},A.createElement(w,null,Kt()))),A.createElement(y,{marginBottom:1,width:"100%",justifyContent:"space-between"},A.createElement(y,null,A.createElement(w,{bold:!0},"Learning Feed"),A.createElement(w,{dimColor:!0}," - Real-time taste learning activity")),A.createElement(w,{dimColor:!0},"Press ctrl+t to close")),A.createElement(y,{flexDirection:"column"},0===t.length?A.createElement(y,null,A.createElement(w,{dimColor:!0},"No learning events yet...")):A.createElement(y,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:o}=s(e.message),c="moved"===t?i(e.details):null,l="upgraded"===t||"downgraded"===t?a(r):null;return A.createElement(y,{key:e.id,marginBottom:1},A.createElement(y,{flexDirection:"column"},A.createElement(y,null,A.createElement(w,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?A.createElement(w,{dimColor:!0}," (",c.fullPath,")"):e.details?A.createElement(w,{dimColor:!0}," (",e.details,")"):null),A.createElement(y,{marginLeft:1},A.createElement(w,{dimColor:!0},"⎿"," "),c?A.createElement(A.Fragment,null,A.createElement(w,null,c.category," package ("),A.createElement(w,{dimColor:!0},c.oldPath),A.createElement(w,null," → ",c.newPath),A.createElement(w,null,")")):l?A.createElement(A.Fragment,null,A.createElement(w,null,l.text," ("),A.createElement(w,{dimColor:!0},"confidence: "),A.createElement(w,{dimColor:!0},l.oldPercent,"%"),A.createElement(w,null," → "),A.createElement(w,{color:l.diff>0?"green":"red"},l.newPercent,"%"),A.createElement(w,null,")")):A.createElement(A.Fragment,null,A.createElement(w,null,r),o&&A.createElement(w,{dimColor:!0}," (",o,")")))))}return A.createElement(y,{key:e.id,marginBottom:1},A.createElement(w,{dimColor:!0},o.pointerSmall," ",e.message))}))))},"LearningFeedFull"),ks=__name(({onClose:e})=>{const[t,n]=P([]),[r,o]=P(0),[s,a]=P(!0),[i,c]=P(null);I(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),a(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(k((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),s)return A.createElement(y,{paddingLeft:1,paddingTop:1},A.createElement(w,{color:"dim"},"Loading memory files..."));if(i)return A.createElement(y,{paddingLeft:1,paddingTop:1},A.createElement(w,{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 A.createElement(y,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},A.createElement(y,null,A.createElement(w,{color:"white",bold:!0},"Select memory to edit:")),A.createElement(y,{columnGap:4,marginTop:1},A.createElement(y,{flexDirection:"column"},u.map((e,t)=>A.createElement(w,{key:t,color:r===t?"white":"dim"},r===t?"> ":" ",e.label))),A.createElement(y,{flexDirection:"column"},u.map((e,t)=>A.createElement(w,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector"),Ss=class extends Pe{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},Cs=new Ae;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=D(()=>{if(!e)return"";try{const t=Cs.parse(e);return"string"!=typeof t?e:t.trim()}catch{return e}},[e]);return A.createElement(w,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return A.createElement(y,null,A.createElement(w,null,o.nodejs),A.createElement(y,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},A.createElement(Markdown,null,e)))}Cs.setOptions({renderer:new Ss({strong:t.bold,em:t.italic,del:t.strikethrough,codespan:t.yellow,code:t.yellow,heading:t.bold.underline,firstHeading:t.bold.underline,link:t.cyan,href:t.cyan.underline,blockquote:t.gray.italic,table:t.reset,hr:t.reset,paragraph:t.reset,html:t.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0}),__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var vs={"Interrupted by user":"Interrupted by user","Insufficient credits":bt};function UserMessage({content:e}){const t="Interrupted by user"===e,n="Insufficient credits"===e,r=e.startsWith("Error:"),s=t||n||r;let a=s&&vs[e]||e;return A.createElement(y,{paddingX:1,backgroundColor:s?void 0:"#333333"},A.createElement(w,{color:s?"red":"#AAAAAA",bold:!s},o.pointer),A.createElement(y,{marginLeft:1},A.createElement(w,{color:s?"red":"white",wrap:"wrap"},a)))}__name(UserMessage,"UserMessage");var Ts="#6B7280";function truncateToolOutputForDisplay({output:e,maxLines:t=1}){const n=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),r=n.split("\n");return r.length<=t?n:r.slice(0,t).join("\n")}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const c=xe.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(A.createElement(y,{key:`${t}-${r}-removed`,width:"100%"},A.createElement(w,{color:"gray",dimColor:a},u.toString().padStart(3)," "),A.createElement(y,{backgroundColor:"#712F37"},A.createElement(w,{dimColor:a},"-"),A.createElement(w,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(A.createElement(y,{key:`${t}-${r}-added`,width:"100%"},A.createElement(w,{color:"gray",dimColor:a},u.toString().padStart(3)," "),A.createElement(y,{backgroundColor:"#325B30"},A.createElement(w,{dimColor:a},"+"),A.createElement(w,{dimColor:a}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:A.createElement(y,{flexDirection:"column"},o&&!r&&A.createElement(w,{color:"gray"},"Updated"," ",A.createElement(w,{color:"white",bold:!0},n)," ","with ",A.createElement(w,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",A.createElement(w,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&A.createElement(w,{color:"red"},"Rejected update to",A.createElement(w,{color:"red"},` ${n}`)),A.createElement(y,{flexDirection:"column",marginLeft:s},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=lr(e);return t?A.createElement(y,{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 A.createElement(y,{key:e.id||t,flexDirection:"row"},A.createElement(y,{width:2},A.createElement(w,{color:r},n)),A.createElement(w,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):A.createElement(w,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:s=!1,metadata:a,expandedOutput:i=!1}){const c="Thinking…"===e,l="Todos"===e,d="Edit"===e,u=!0===a?.isTasteFile,m=a?.tasteCategory,g=!0===a?.permissionDenied,p=!c&&!l&&!u,{name:h}=detectTerminal(),f="iTerm2"===h?"shift":"ctrl",E=!0===a?.isAgent,b=t&&E?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():t,k=!c&&b&&!u,S=a?.status,C=a?.tokensUsed||0,v="number"==typeof a?.elapsedSeconds?Math.floor(a.elapsedSeconds):0;let T,P;if(r)T="yellow",P="→";else if(s)T="red",P=o.nodejs;else if(c)T=Ts,P="✻";else if(l&&n){const e=lr(n),t=e?.every(e=>"completed"===e.status);T=t?"#22C55E":"#D4A017",P=o.nodejs}else T="#22C55E",P=o.nodejs;return A.createElement(y,null,c&&A.createElement(w,{color:T},P),A.createElement(y,{flexDirection:"column",marginLeft:c?1:0},A.createElement(y,null,c?A.createElement(A.Fragment,null,A.createElement(w,{color:Ts},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!i&&A.createElement(w,{dimColor:!0},"(",`${f}+o to expand`,")")):u?A.createElement(A.Fragment,null,A.createElement(w,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),A.createElement(w,null," ","Using your taste ",m?"package of ":"packages",m&&A.createElement(w,{bold:!0},m))):A.createElement(w,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),k&&A.createElement(w,null," ",A.createElement(Markdown,null,`(${b})`))),E&&("running"===S||n)&&A.createElement(y,{columnGap:1,marginLeft:p?1:0},p&&A.createElement(w,null,"⎿"," "),"running"===S?A.createElement(w,{color:"gray"},"Running (",formatTime2(v)," | ",formatTokens(C),")"):"interrupted"===S?A.createElement(w,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===S||s?A.createElement(w,{color:"red",wrap:"wrap"},n," (",formatTime2(v)," | ",formatTokens(C),")"):"Interrupted by user"===n?A.createElement(A.Fragment,null,A.createElement(w,{color:"red",wrap:"wrap"},"Interrupted by user")):A.createElement(A.Fragment,null,A.createElement(w,{wrap:"wrap"},"Done"),A.createElement(w,{color:"gray"}," ","(",formatTime2(v)," | ",formatTokens(C),")"))),n&&!u&&!E&&A.createElement(y,{columnGap:1,marginLeft:p?1:0},p&&A.createElement(w,null,"⎿"," "),l?formatTodosForDisplay(n):c?i?A.createElement(y,{width:"100%",flexDirection:"column"},A.createElement(w,null," "),A.createElement(w,{color:Ts,wrap:"wrap",italic:!0},n)):null:d&&a?.oldValue&&a?.newValue?A.createElement(y,{flexDirection:"column"},(()=>{const e=i?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:a.oldValue,newValue:a.newValue,dimDiff:g,permissionDenied:g,maxLines:e});return A.createElement(A.Fragment,null,n,r&&A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"… (",o-10," more lines) (",`${f}+o to expand`,")")))})(),g&&n&&A.createElement(y,{marginTop:1},A.createElement(w,{color:"red",wrap:"wrap"},n))):A.createElement(y,{width:"100%"},A.createElement(w,{color:s?"red":"",wrap:"wrap"},i?n:A.createElement(A.Fragment,null,truncateToolOutputForDisplay({output:n,maxLines:"Question"===e?10:1}),n.includes("\n")&&"Question"!==e&&A.createElement(w,{dimColor:!0}," ","(",`${f}+o to expand`,")"))))),r&&!E&&A.createElement(y,{columnGap:1,marginLeft:1},A.createElement(w,null,"⎿"," "),A.createElement(w,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),A.createElement(y,null,A.createElement(w,{color:o},s),A.createElement(y,{flexDirection:"column",marginLeft:1},A.createElement(y,null,A.createElement(w,{color:"gray"},"$ "),A.createElement(w,{color:o,bold:!0},e)),A.createElement(y,{columnGap:1,marginLeft:1},A.createElement(w,null,"⎿"," "),A.createElement(w,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage");var As="Coding agent that continuously learns your taste of writing code.",Ps=[{key:"Shift+Tab",description:"Toggle auto-accept mode"},{key:"Ctrl+T",description:"Toggle learning feed"},{key:"Ctrl+O",description:"Toggle expanded tool output (Shift+O in iTerm2)"},{key:"Esc Esc",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],xs=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume",description:"Resume a conversation"},{key:"-c, --continue",description:"Continue the last conversation"},{key:"-t, --trust",description:"Auto-trust project (skip initial permission prompt)"},{key:"-p, --print [query]",description:"Run in non-interactive mode, output response and exit"},{key:"--dangerously-skip-permissions",description:"Bypass all permission prompts (use with caution)"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],Is=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/model",description:"Switch between Command Code models"},{key:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{key:"/compact",description:"Compact the conversation history"},{key:"/login",description:"Authenticate with CommandCode via browser"},{key:"/logout",description:"Remove stored authentication"},{key:"/exit",description:"Exit the REPL"}],$s=[{key:"cmd info",description:"Display system information"},{key:"cmd config",description:"Manage CLI configuration"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Ds=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Fs=["cmd Start interactive session",'cmd "fix the login bug" Start with a task',"cmd -c Continue last conversation","cmd -r Resume a past session",'cmd -p "your query" Run non-interactive query',"cmd info Show system information"],Rs='Start with a prompt: cmd "fix the login bug"';function getPackageJson(){const e=import.meta.url,t=Ee(e),n=z(t);return JSON.parse(ee(G(n,"./../package.json"),"utf8"))}__name(getPackageJson,"getPackageJson");var Ms="cmd";function getBinNames(){const e=getPackageJson();return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name]:[Ms]}function getInvokedCommandName(){try{const e=getBinNames(),t=process.argv[1];if(!t)return e[0]||Ms;const n=W.basename(t).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(n)?n:e[0]||Ms}catch{return Ms}}function HelpMessage(){const e=getInvokedCommandName(),t=D(()=>Is.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return A.createElement(y,{flexDirection:"column",paddingY:1},A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(y,null,A.createElement(w,{bold:!0},"Command Code"),A.createElement(w,{color:"gray"}," v","0.10.10")),A.createElement(w,{color:"gray"},As)),A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(w,{bold:!0},"Usage"),A.createElement(y,{paddingLeft:2},A.createElement(w,null,e," <command> [options]"))),A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(w,{bold:!0},"Options"),A.createElement(y,{flexDirection:"column",paddingLeft:2},xs.map(t=>A.createElement(y,{key:t.key},A.createElement(w,null,t.key.replace(/^cmd/,e).padEnd(20)),A.createElement(w,{color:"gray"},t.description))))),A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(w,{bold:!0},"Commands"),A.createElement(y,{flexDirection:"column",paddingLeft:2},$s.map(t=>A.createElement(y,{key:t.key},A.createElement(w,null,t.key.replace(/^cmd/,e).padEnd(20)),A.createElement(w,{color:"gray"},t.description))))),A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(w,{bold:!0},"Slash Commands"),A.createElement(y,{flexDirection:"column",paddingLeft:2},t.map(e=>A.createElement(y,{key:e.key},A.createElement(w,null,e.key.padEnd(17)),A.createElement(w,{color:"gray"},e.description))))),A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(w,{bold:!0},"Keyboard Shortcuts"),A.createElement(y,{flexDirection:"column",paddingLeft:2},Ps.map(e=>A.createElement(y,{key:e.key},A.createElement(w,null,e.key.padEnd(15)),A.createElement(w,{color:"gray"},e.description))))),A.createElement(y,{flexDirection:"column",marginBottom:1},A.createElement(w,{bold:!0},"Examples"),A.createElement(y,{flexDirection:"column",paddingLeft:2},Fs.map((t,n)=>A.createElement(w,{key:n},t.replace(/^cmd/,e))))),A.createElement(y,{marginBottom:1},A.createElement(w,{color:"cyan"},"❯"),A.createElement(w,{color:"gray"}," ",Rs.replace(/cmd/,e))),A.createElement(y,{flexDirection:"column"},A.createElement(w,{bold:!0},"Links"),A.createElement(y,{flexDirection:"column",paddingLeft:2},Ds.map(e=>A.createElement(y,{key:e.key},A.createElement(w,null,e.key.padEnd(20)),A.createElement(w,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?A.createElement(HelpMessage,null):A.createElement(y,{flexDirection:"column"},A.createElement(w,{wrap:"wrap"},A.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return A.createElement(y,null,A.createElement(w,{color:"red"},t?o.pointer:o.warning),A.createElement(y,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?A.createElement(w,{color:"red",wrap:"wrap"},e):A.createElement(Markdown,{color:"red"},e)))}function InfoMessage({content:e}){return A.createElement(y,null,A.createElement(w,{dimColor:!0},o.info),A.createElement(y,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},A.createElement(Markdown,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return A.createElement(y,{flexDirection:"column",marginBottom:0,marginTop:-1},A.createElement(y,{columnGap:1},A.createElement(w,null,"⎿"," "),A.createElement(y,{flexGrow:1,flexShrink:1,minWidth:0},A.createElement(w,{color:n?"yellow":void 0},e))),t&&A.createElement(y,{marginLeft:3},A.createElement(w,{dimColor:!0},"See ",t)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(ErrorMessage,"ErrorMessage"),__name(InfoMessage,"InfoMessage"),__name(CommandResultMessage,"CommandResultMessage");var Ls=W.join(J.homedir(),".commandcode","updates.json");function ensureDir(){const e=W.dirname(Ls);Z.existsSync(e)||Z.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!Z.existsSync(Ls))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=Z.readFileSync(Ls,"utf-8");return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null,...JSON.parse(e)}}catch{return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}}}function writeUpdatesConfig(e){ensureDir(),Z.writeFileSync(Ls,JSON.stringify(e,null,2))}function updateUpdatesConfig(e){writeUpdatesConfig({...readUpdatesConfig(),...e})}function shouldCheckForUpdate(){const e=readUpdatesConfig();return!!e.autoUpdate&&Date.now()-e.lastCheckedAt>=e.checkIntervalMs}function recordUpdateCheck(){updateUpdatesConfig({lastCheckedAt:Date.now()})}function setPendingUpdate(e){updateUpdatesConfig({lastCheckedAt:Date.now(),pending:e})}function clearPendingUpdate(){updateUpdatesConfig({pending:null})}function getPendingUpdate(e){const t=readUpdatesConfig();return t.pending?t.pending.currentVersion!==e?(clearPendingUpdate(),null):t.pending:null}__name(function getDefaultConfig(){return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}},"getDefaultConfig"),__name(ensureDir,"ensureDir"),__name(readUpdatesConfig,"readUpdatesConfig"),__name(writeUpdatesConfig,"writeUpdatesConfig"),__name(updateUpdatesConfig,"updateUpdatesConfig"),__name(shouldCheckForUpdate,"shouldCheckForUpdate"),__name(recordUpdateCheck,"recordUpdateCheck"),__name(setPendingUpdate,"setPendingUpdate"),__name(clearPendingUpdate,"clearPendingUpdate"),__name(getPendingUpdate,"getPendingUpdate");var Os=Ie(ce),Ns=getPackageJson();function isLocalDevelopmentBuild(){try{const e=process.argv[1];if(!e)return!1;if(e.includes("/usr/local/bin/dmd"))return!0;const t=Z.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}function shouldSkipUpdateSystem(){return!!process.env.CI||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=ie("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return Ns.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort($e.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&$e.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&$e.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:o,updateAvailable:s}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:o,updateAvailable:s}}async function executeUpdate(e){try{return await Os(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!$e.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=de(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`)}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const o=n||await checkForUpdateAvailable();return o?.updateAvailable?(r?.(o.latestVersion),await executeUpdate(o.latestVersion)?{success:!0,updateInfo:o}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:o})):{success:!1}}function getCurrentGitBranch(){try{return ie("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","ignore"],cwd:process.cwd()}).trim()||null}catch(e){return null}}function getGitHeaderInfo(){return{branch:getCurrentGitBranch(),isLocal:isLocalDevelopmentBuild()}}function getModelShortName(e){const t=Object.values(Ye).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(isLocalDevelopmentBuild,"isLocalDevelopmentBuild"),__name(shouldSkipUpdateSystem,"shouldSkipUpdateSystem"),__name(fetchVersions,"fetchVersions"),__name(getCurrentVersion,"getCurrentVersion"),__name(isAlphaVersion,"isAlphaVersion"),__name(filterVersions,"filterVersions"),__name(getLatestVersion,"getLatestVersion"),__name(determineUpdateTarget,"determineUpdateTarget"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(executeUpdate,"executeUpdate"),__name(checkForUpdateAsync,"checkForUpdateAsync"),__name(doUpdateCheck,"doUpdateCheck"),__name(maybeRunPendingUpdate,"maybeRunPendingUpdate"),__name(performAutoUpdate,"performAutoUpdate"),__name(getCurrentGitBranch,"getCurrentGitBranch"),__name(getGitHeaderInfo,"getGitHeaderInfo"),__name(getModelShortName,"getModelShortName");var Us=A.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=Kt();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~"),m=getGitHeaderInfo();return A.createElement(E,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return A.createElement(y,{key:"header",marginBottom:1,flexDirection:"column"},A.createElement(Te,{name:"vice"},A.createElement(w,null,a.trimEnd())),A.createElement(y,{flexDirection:"column",marginTop:1},A.createElement(y,null,A.createElement(w,{color:"gray"},"# "),A.createElement(w,{bold:!0},"Command Code"),A.createElement(w,{color:"gray"}," v",i)),A.createElement(w,{color:"gray"},"# models: ",c," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),A.createElement(y,null,A.createElement(w,{color:"gray"},"# ",u,m&&m.isLocal&&m.branch&&A.createElement(w,{color:"gray"}," (branch: ",m.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":return A.createElement(UserMessage,{content:t.input});case"assistant":return A.createElement(AssistantMessage,{content:t.input});case"tool":return A.createElement(ToolMessage,{name:ir(t.name||""),input:t.input,output:t.output||"",isPending:or(t),hasError:rr(t),metadata:t.metadata,expandedOutput:r});case"bash":return A.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:or(t),hasError:rr(t)});case"system":return A.createElement(SystemMessage,{content:t.input});case"info":return A.createElement(InfoMessage,{content:t.input});case"error":return A.createElement(ErrorMessage,{content:t.input});case"command-result":return A.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});default:return A.createElement(A.Fragment,null)}})();return A.createElement(y,{key:t.id,marginBottom:1,width:"90%"},n)})});function getModelOptions(){return Object.values(Ye).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}__name(getModelOptions,"getModelOptions");var js=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");k((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return A.createElement(y,{flexDirection:"column",paddingX:0,width:"100%"},A.createElement(y,null,A.createElement(w,{color:"#E4CCFF",bold:!0},"Select model")),A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),A.createElement(Ce,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),s=o?.value===n,a=o?.description?`${o.label} (${o.description})`:o?.label||t;return A.createElement(y,null,A.createElement(w,{color:e?"green":"gray"},` ${a.padEnd(24)}`),A.createElement(w,{color:e?"green":"gray"},o?.modelName),s&&A.createElement(w,{color:"green"}," ✓"))}}),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press "),A.createElement(w,{dimColor:!0,bold:!0},"Esc"),A.createElement(w,{dimColor:!0}," to cancel")))},"ModelSelector"),_s=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=P(0),s=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],a=__name(e=>{const r=s.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=W.basename(e.filePath),n=W.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 A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},A.createElement(y,{marginBottom:1},A.createElement(w,{bold:!0,color:"yellow"},`${l()} ${"edit"===e.action?c():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&A.createElement(y,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:c(),marginLeft:0}).diffContent),A.createElement(y,{marginBottom:1},A.createElement(w,{bold:!0},"Do you want to ",i()," ",A.createElement(w,{color:"cyan"},c()),"?")),A.createElement(Ce,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:r,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:"cyan"},e?o.pointer:" "),itemComponent:({label:e,isSelected:t})=>A.createElement(w,{color:t?"cyan":"white"},e.includes("(shift+tab)")?A.createElement(A.Fragment,null,e.split("(shift+tab)")[0],A.createElement(w,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?A.createElement(A.Fragment,null,e.split("(")[0],A.createElement(w,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),Bs=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");k((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return A.createElement(y,{flexDirection:"column",paddingX:0,width:"100%"},A.createElement(y,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},A.createElement(y,null,A.createElement(w,{bold:!0},"Select AI Provider")),n&&A.createElement(y,{flexDirection:"row"},A.createElement(w,{dimColor:!0},"Current: "),A.createElement(w,{color:"green"},getProviderDisplayName(n)),a&&A.createElement(w,{color:"yellow"}," [OAuth enforced]"))),A.createElement(y,{marginBottom:0},A.createElement(w,{dimColor:!0},"Available Providers:")),A.createElement(Ce,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>A.createElement(w,{color:e?"cyan":"gray",bold:e},` ${t}`)}),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector"),Ws=__name(({staticKey:e})=>A.createElement(E,{items:[{staticKey:e}],key:e},()=>A.createElement(w,{key:e},"\0")),"Responsive");function RetryMessage({attempt:e}){const[t,n]=P(0);if(I(()=>{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 A.createElement(y,{marginBottom:1},A.createElement(w,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}__name(RetryMessage,"RetryMessage");var Hs=[{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"}],zs=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=D(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=P(Math.max(0,r.length-1)),[a,i]=P(Math.max(0,r.length-8)),[c,l]=P("checkpoint"),[d,u]=P(null),[m,g]=P(0),p=D(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),h=D(()=>p?Hs:Hs.filter(e=>"conversation"===e.mode),[p]);if(I(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),k((e,p)=>{p.escape?"mode"===c?(l("checkpoint"),u(null),g(0)):n():"checkpoint"===c?p.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):p.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):p.return&&r.length>0&&(u(r[o]),l("mode"),g(0)):"mode"===c&&(p.upArrow?g(e=>Math.max(0,e-1)):p.downArrow?g(e=>Math.min(h.length-1,e+1)):p.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode}))}),0===r.length)return A.createElement(y,{flexDirection:"column",paddingLeft:2,paddingTop:1},A.createElement(w,{color:"#E4CCFF",bold:!0},"Rewind"),A.createElement(w,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press "),A.createElement(w,{dimColor:!0,bold:!0},"Esc"),A.createElement(w,{dimColor:!0}," to close")));if("mode"===c&&d)return A.createElement(y,{flexDirection:"column",paddingLeft:2,paddingTop:1},A.createElement(w,{color:"#E4CCFF",bold:!0},"Rewind"),A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"Restore to: "),A.createElement(w,{color:"white"},truncateString({text:d.userPrompt||"checkpoint",maxLength:50}))),A.createElement(y,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return A.createElement(y,{key:e.mode,flexDirection:"column"},A.createElement(y,{flexDirection:"row"},A.createElement(w,{color:n?"#E4CCFF":void 0},n?"> ":" "),A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:n?"#E4CCFF":"white"},e.label),A.createElement(w,{dimColor:!0},e.description))),!r&&A.createElement(w,null," "))})),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press "),A.createElement(w,{dimColor:!0,bold:!0},"Enter"),A.createElement(w,{dimColor:!0}," to confirm, "),A.createElement(w,{dimColor:!0,bold:!0},"Esc"),A.createElement(w,{dimColor:!0}," to go back")));const f=r.slice(a,a+8);return A.createElement(y,{flexDirection:"column",paddingLeft:2,paddingTop:1},A.createElement(w,{color:"#E4CCFF",bold:!0},"Rewind"),A.createElement(w,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),A.createElement(y,{marginTop:1}),A.createElement(y,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,c=t===f.length-1,l=n===r.length-1;return A.createElement(y,{key:e.messageId,flexDirection:"column"},A.createElement(y,{flexDirection:"row"},A.createElement(w,{color:s?"#E4CCFF":void 0},s?"> ":" "),A.createElement(y,{flexDirection:"column"},A.createElement(y,null,A.createElement(w,{color:s?"#E4CCFF":"white"},truncateString({text:e.userPrompt||"(no prompt)",maxLength:60})),A.createElement(w,{dimColor:!0}," • "),A.createElement(w,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),l&&" (latest)")),A.createElement(w,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!c&&A.createElement(w,null," "))})),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press "),A.createElement(w,{dimColor:!0,bold:!0},"Enter"),A.createElement(w,{dimColor:!0}," to select, "),A.createElement(w,{dimColor:!0,bold:!0},"Esc"),A.createElement(w,{dimColor:!0}," to cancel")))},"RewindSelector"),Gs=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=S(),[r,s]=P([]),[a,i]=P(0),[c,l]=P(!0),[d,u]=P(0),m=30;I(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await Yr.listSessions();s(e),l(!1)},"loadSessions");if(k((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[a].id):(o.escape||o.ctrl&&"c"===t)&&n()}),c)return A.createElement(y,{flexDirection:"column",paddingLeft:2,paddingTop:1},A.createElement(w,{color:"gray"},"Loading sessions..."));const p=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),a=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===a?"1 week ago":`${a} weeks ago`},"formatRelativeTime"),h=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return A.createElement(y,{flexDirection:"column"},A.createElement(w,{color:"gray"},"No sessions available"));const f=r.slice(d,d+m),E=d;return A.createElement(y,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&A.createElement(y,{marginBottom:1},A.createElement(w,{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)")),A.createElement(y,{columnGap:2,marginBottom:1},A.createElement(y,{width:7},A.createElement(w,{color:"gray"}," ")),A.createElement(y,{width:13},A.createElement(w,{color:"gray"},"Modified")),A.createElement(y,{width:11},A.createElement(w,{color:"gray"},"# Messages")),A.createElement(y,{width:20},A.createElement(w,{color:"gray"},"Git Branch")),A.createElement(y,null,A.createElement(w,{color:"gray"},"Summary"))),A.createElement(y,{columnGap:2},A.createElement(y,{flexDirection:"column",width:7},f.map((e,t)=>{const n=E+t;return A.createElement(w,{key:`sel-${n}`,color:a===n?"cyan":"gray"},a===n?`${o.pointer} ${n+1}.`:` ${n+1}.`)})),A.createElement(y,{flexDirection:"column",width:13},f.map((e,t)=>{const n=E+t;return A.createElement(w,{key:`mod-${e.id}`,color:a===n?"white":"gray"},p(e.lastModified))})),A.createElement(y,{flexDirection:"column",width:11},f.map((e,t)=>{const n=E+t;return A.createElement(w,{key:`msg-${e.id}`,color:a===n?"white":"gray"},e.messageCount)})),A.createElement(y,{flexDirection:"column",width:20},f.map((e,t)=>{const n=E+t;return A.createElement(w,{key:`branch-${e.id}`,color:a===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),A.createElement(y,{flexDirection:"column"},f.map((e,t)=>{const n=E+t;return A.createElement(w,{key:`summary-${e.id}`,color:a===n?"white":"gray"},h(e.firstMessage))}))))},"SessionTable"),qs=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=P(0),s=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],a=__name(e=>{const r=s.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),i=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"",n=t?`${e.command} ${t}`:e.command;return n.length>60?n.substring(0,57)+"...":n},"getCommandDisplay");return A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},A.createElement(y,{marginBottom:1},A.createElement(w,{bold:!0,color:"yellow"},"Execute Shell Command")),A.createElement(y,{marginBottom:1},A.createElement(w,{bold:!0},"Command Code needs to execute ",A.createElement(w,{color:"cyan"},i()),".")),e.workingDirectory&&A.createElement(y,{marginBottom:1},A.createElement(w,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&A.createElement(y,{marginBottom:1},A.createElement(w,{color:"gray",italic:!0},e.description)),A.createElement(Ce,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:a,initialIndex:r,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:"cyan"},e?o.pointer:" "),itemComponent:({label:e,isSelected:t})=>A.createElement(w,{color:t?"cyan":"white"},e.includes("(shift+tab)")?A.createElement(A.Fragment,null,e.split("(shift+tab)")[0],A.createElement(w,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt"),Vs=__name(({onClose:e,staticKey:t})=>{const[n,r]=P([]),[o,s]=P(!0),[a,i]=P(null),{stdout:c}=C(),l=c?.columns??80,d=__name((e,t)=>e.length<=t?e:t<=3?e.substring(0,t):e.substring(0,t-3)+"...","truncateText");I(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),n=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];r(n)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=__name(async t=>{const r=n.find(e=>e.value===t.value);if(r)try{await De([{file:r.filePath,line:1}]),yo(),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");k((t,n)=>{n.escape&&(yo(),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?A.createElement(y,{flexDirection:"column",paddingX:0,width:"100%"},A.createElement(w,{color:"#E4CCFF",bold:!0},"Agent Skills"),A.createElement(w,{dimColor:!0},"Loading skills...")):a?A.createElement(y,{flexDirection:"column",paddingX:0,width:"100%"},A.createElement(w,{color:"red",bold:!0},"Agent Skills"),A.createElement(w,{dimColor:!0},a),A.createElement(y,{marginTop:1}),A.createElement(w,{dimColor:!0},"Press ",A.createElement(w,{bold:!0},"Esc")," to close")):0===n.length?A.createElement(y,{flexDirection:"column",paddingX:0,width:"100%"},A.createElement(w,{color:"#E4CCFF",bold:!0},"Agent Skills"),A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"No skills found")),A.createElement(w,{dimColor:!0},"Create skills in:"),A.createElement(w,{dimColor:!0}," ~/.commandcode/skills/ (user)"),A.createElement(w,{dimColor:!0}," .commandcode/skills/ (project)"),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press ",A.createElement(w,{bold:!0},"Esc")," to close"))):A.createElement(y,{flexDirection:"column",paddingX:0,width:"100%"},A.createElement(y,null,A.createElement(w,{color:"#E4CCFF",bold:!0},"Agent Skills")),A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"Select a skill to open in your editor. Skills provide specialized guidance for coding tasks.")),A.createElement(Ce,{items:n,onSelect:u,initialIndex:0,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const r=n.find(e=>e.label===t),o=r?.location?` (${r.location})`:"",s=Math.max(30,l-35),a=r?.description?d(r.description,s):"";return A.createElement(y,null,A.createElement(w,{color:e?"green":"white"},` ${t}`),A.createElement(w,{color:"gray"},o.padEnd(25-t.length)),A.createElement(w,{color:"gray"},a))}}),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press ",A.createElement(w,{bold:!0},"Esc")," to cancel")))},"SkillsConfig"),Ks=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=P(!1),[s,a]=P(!0);I(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{a(!1)}},"loadSettings")()},[]),k((t,n)=>{if(!n.return&&" "!==t)return n.escape?(yo(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?A.createElement(y,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},A.createElement(w,{color:"blue",bold:!0},"Taste Settings"),A.createElement(w,{dimColor:!0},"Loading configuration...")):A.createElement(y,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},A.createElement(w,{bold:!0},"Taste Learning"),A.createElement(w,{dimColor:!0},"Configure taste learning preferences for this project"),A.createElement(y,{marginTop:1}),A.createElement(y,{justifyContent:"space-between"},A.createElement(w,null,"Taste learning",A.createElement(w,{dimColor:!0}," - Learn from your interactions")),A.createElement(w,{color:r?"green":"gray"},r?"enabled":"disabled")),A.createElement(y,{marginTop:1}),A.createElement(w,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),A.createElement(w,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig"),Js=__name(e=>{const[t,n]=P(e),[r,o]=P(null);return I(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):o(e.message)},"handleNewEvent");return ao.on("reset",t),ao.on("new-event",r),()=>{ao.off("reset",t),ao.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new pn({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===Ke)try{const e=await yt.getValidAccessToken();validateOAuthToken({token:e,provider:n}),o=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const s={[He]:Yr.getCurrentProjectDirName(),[Be]:r.toString()};return o&&(s[We]=`Bearer ${o}`),{request:t,headers:s}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}__name(createRequestClient,"createRequestClient"),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch");var Ys="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Scan prompts. ${t} casual observations like a dev friend glancing at your work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words\n- sound human, not robotic\n\nPrompts:\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${Ys}`,max_tokens:200,temperature:.7,stream:!0},threadId:`observer-${Date.now()}`}}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),ao.addEvent({type:"insight",message:n}))}e=t[t.length-1]}},"emitCompletedLines");return{addText:__name(r=>{t++,dlog(`[ObserverAPI] text chunk ${t}: "${r.substring(0,50)}..."`),e+=r,n()},"addText"),emitRemaining:__name(()=>{e.trim()&&(dlog(`[ObserverAPI] emitting final insight: ${e.trim()}`),ao.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=fe.fromReadableStream(e),dlog("[ObserverAPI] created MessageStream")}catch(e){throw dlog(`[ObserverAPI] MessageStream creation failed: ${e instanceof Error?e.message:String(e)}`),e}const n=createInsightEmitter();t.on("text",e=>{n.addText(e)});try{await t.finalMessage(),dlog(`[ObserverAPI] stream complete, ${n.getChunkCount()} chunks received`)}catch(e){throw dlog(`[ObserverAPI] stream failed: ${e instanceof Error?e.message:String(e)}`),e}n.emitRemaining()}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${Ge.ALPHA.GENERATE} with model: ${Ys}`);const r=buildRequestBody(n);let o;try{o=await e.post({endpoint:Ge.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(o),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const a=buildObserverPrompt(n,4);await callObserverAPI(e,t,a)}async function observeSessionPrompts(e){if(ao.observerHasRun)return;ao.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const o=Math.min(r.length,6);for(let t=0;t<o;t++){if(ao.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const o=r[t];try{await processBatch(e,n,o,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),ao.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var Qs=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(e=0){const t=[];try{const n=B.join(K.homedir(),".claude","projects");await M.access(n);const r=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${r}`);const o=(await M.readdir(n)).filter(e=>e===r);for(const r of o){const o=B.join(n,r);try{if(!(await M.stat(o)).isDirectory())continue;const n=(await M.readdir(o)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${n.length} sessions`);for(const r of n){const n=B.join(o,r),s=await M.stat(n),a=r.replace(".jsonl","");if(t.push({id:a,filePath:n,createdAt:s.birthtime,lastModified:s.mtime,messageCount:0,agent:"claude-code"}),e>0&&t.length>=e)break}if(e>0&&t.length>=e)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return t}static async findCodexSessions(e=0,t){try{ao.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&ao.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await M.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{ao.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),s=o.tasteOnboarding?.learnedSessions||{},a=s["claude-code"]?.length||0,i=s.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${i} learned`);const c=await findNewSessions(s),l=c["claude-code"]||[],d=c.codex||[],u=l.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${l.length} new, codex=${d.length} new`),0===u){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);ao.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:a+i,agentSessions:o,status:"already-learned"}}if(l.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>l.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const m=n.length+r.length;dlog(`[Import] total sessions: ${m} (claude-code: ${n.length}, codex: ${r.length})`),ao.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const g=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of g){ao.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const p=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${p.length} batches`);const h=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});ao.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${p.length} batch${1===p.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new pn({baseUrl:o});let a=!0;for(let e=0;e<p.length;e++){const t=p[e],n=e+1,r=p.length;r>1&&ao.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new co({request:s,sessionId:`taste-import-batch-${e}-${Date.now()}`,projectRoot:process.cwd()}),c=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:c})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),ao.markLearningComplete(),await h,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const i=await this.extractLearningSummary(),c=[];if(n.length>0&&c.push(`Claude Code (${n.length})`),r.length>0&&c.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),ao.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}return ao.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${c.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),ao.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const e=B.join(process.cwd(),".commandcode","taste","taste.md"),t=await M.readFile(e,"utf-8"),n=t.match(/^- .+Confidence:/gm),r=n?n.length:0;return{totalLearnings:r,categories:t.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},Zs=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),Xs=__name(e=>{const[t,n]=P({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return I(()=>{ao.reset(),ao.markImportStarted(),(async()=>{try{const t=await Promise.race([Qs.importAndLearn(),Zs(12e4)]);if(t.success)return void n(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void n(e=>({...e,isImporting:!1,alreadyLearned:!0,learnedSessionCount:t.learnedSessions||0,totalSessionCount:t.totalSessions||0,agentSessions:t.agentSessions||[],waitingForInput:!0}));const r=t.errors.join("\n");n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}catch(t){const r=t instanceof Error?t.message:String(t);n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}})()},[e]),t},"useImportProcess"),ea=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{k((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput"),ta=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=P(null),[o,s]=P(null),a=x(!1);return I(()=>{if(a.current)return;let n=null;return(async()=>{try{a.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{ao.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{ao.reset(),e()}}__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var na=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=x(n),o=$(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=$(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=$(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=$(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),c=$(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),l=$(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current())},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:a,handleErrorDismiss:i,handleDemoComplete:c,handleSkip:l}},"useOnboardingHandlers"),ra=__name(({conditions:e,autoLearn:t})=>{const[n,r]=P("checking"),o=x(!1);return I(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),I(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow"),oa=__name(({error:e})=>A.createElement(y,{padding:1},A.createElement(y,{flexDirection:"column",borderColor:"red",padding:1},A.createElement(y,{marginBottom:1},A.createElement(w,null,"Error initializing onboarding: ",e)),A.createElement(y,null,A.createElement(w,null,"Continuing without onboarding...")))),"OnboardingError"),sa=[{type:"user",text:"I always prefer pnpm",duration:2e3},{type:"learned",text:"Learned: pnpm (95% preference)",details:".commandcode/taste/taste.md",duration:2e3},{type:"user",text:"I prefer commander over meow",duration:2e3},{type:"updated",text:"Updated: commander boosted (60% → 95%), meow adjusted (90% → 35%)",details:".commandcode/taste/cli/taste.md",duration:2e3},{type:"user",text:"I prefer TypeScript for Node CLIs",duration:2e3},{type:"learned",text:"Learned: TypeScript for CLIs (90% preference)",details:".commandcode/taste/cli/taste.md",duration:2e3}],aa=__name(({onComplete:e})=>{const[t,n]=P(0),[r,s]=P(!1),a=t>=sa.length;I(()=>{if(t>=sa.length)return;if(r)return;const e=sa[t],o=setTimeout(()=>{n(e=>Math.min(e+1,sa.length))},e.duration);return()=>clearTimeout(o)},[t,r]),k((t,r)=>{r.escape?e():a?(r.return||" "===t)&&e():" "===t?s(e=>!e):r.return&&n(e=>Math.min(e+1,sa.length))});const i=sa.slice(0,t);return A.createElement(y,{flexDirection:"column"},A.createElement(y,null,A.createElement(w,{color:"cyan"},"Meet Your Coding Taste")),A.createElement(y,null,A.createElement(w,null,"Command Code learns your coding style as you work.")),A.createElement(y,null,A.createElement(w,null,"Here's how your preferences evolve in real-time:")),A.createElement(y,{flexDirection:"column",marginY:1},0===i.length&&!a&&A.createElement(w,{dimColor:!0},"Starting demo..."),i.map((e,t)=>"user"===e.type?A.createElement(y,{key:t},A.createElement(w,{color:"white"},`${o.pointer} ${e.text}`)):A.createElement(y,{key:t,marginBottom:1,marginTop:0,marginLeft:1},A.createElement(y,null,A.createElement(w,null,"⎿"),A.createElement(y,{flexDirection:"column",marginLeft:2,marginTop:0},A.createElement(w,{color:"green"},e.text),e.details&&A.createElement(w,{dimColor:!0},"Saved(",e.details,")")))))),a&&A.createElement(y,{flexDirection:"column",marginY:1,width:80},A.createElement(y,null,A.createElement(w,{color:"green",bold:!0},"Demo Complete!"," ")),A.createElement(w,null,"Command Code will now use these preferences to generate better suggestions tailored to your coding style. The more you code, the smarter it gets."),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Press Enter to get started →"))),!a&&A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent"),ia=__name(()=>`(run /${Je} anytime)`,"getSkipHint"),ca=__name(()=>A.createElement(w,null,"Skip for now"," ",A.createElement(w,{dimColor:!0},ia())),"SkipOptionText"),la=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:s,demoShown:a=!1})=>{const[i,c]=P(1),l=a?2:3,d=a?2:3;return k((e,t)=>{if(t.escape)s();else if(t.upArrow)c(e=>1===e?l:e-1);else if(t.downArrow)c(e=>e===l?1:e+1);else if("1"!==e)if("2"!==e)if("3"!==e||a){if(t.return){if(1===i)return void n();if(2===i)return void(a?s():r());s()}}else s();else a?s():r();else n()}),A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},A.createElement(w,{color:"cyan",bold:!0},"Build Your Coding Taste"),A.createElement(y,{marginTop:1,flexDirection:"column"},A.createElement(w,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),A.createElement(y,{marginTop:1},A.createElement(w,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),A.createElement(y,{marginTop:1,flexDirection:"column"},A.createElement(y,null,A.createElement(w,{color:1===i?"cyan":"gray"},1===i?o.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!a&&A.createElement(y,null,A.createElement(w,{color:2===i?"cyan":"gray"},2===i?o.pointer:" "," ","2. No, show me a demo instead")),A.createElement(y,null,A.createElement(w,{color:i===d?"cyan":"gray"},i===d?o.pointer:" "," ",d,". ",A.createElement(ca,null)))),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),da=__name(({onDemo:e,onSkip:t})=>{const[n,r]=P(1);return k((o,s)=>{s.escape?t():s.upArrow||s.downArrow?r(e=>1===e?2:1):"1"!==o?"2"!==o?s.return&&(1===n?e():t()):t():e()}),A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},A.createElement(w,{color:"cyan",bold:!0},"No Previous Sessions Found"),A.createElement(y,{marginTop:1,flexDirection:"column"},A.createElement(w,null,"No previous sessions found to analyze."),A.createElement(y,{marginTop:1},A.createElement(w,null,"Would you like to see how taste learning works?"))),A.createElement(y,{marginTop:1,flexDirection:"column"},A.createElement(y,null,A.createElement(w,{color:1===n?"cyan":"gray"},1===n?o.pointer:" "," 1. Yes, show me a demo")),A.createElement(y,null,A.createElement(w,{color:2===n?"cyan":"gray"},2===n?o.pointer:" "," 2."," ",A.createElement(ca,null)))),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice"),ua=__name(({error:e})=>A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},A.createElement(w,{color:"red",bold:!0},"Oops, something went wrong:"),A.createElement(y,{marginTop:1},A.createElement(w,null,e))),"ErrorSection"),ma=[o.bullet,o.squareSmallFilled,o.lozenge,o.star,o.triangleRight,o.triangleUp,o.circleFilled,o.pointer],ga=__name(()=>A.createElement(w,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),pa=["percolating","excavating","deciphering","triangulating","osmosing","metabolizing","grokking","spelunking","interpolating","marinating","crystallizing","synthesizing","calibrating","fermenting","coalescing","transmuting","simmering","distilling","ruminating","perusing","assimilating","untangling","decoding","absorbing","harmonizing","digesting","contemplating","extrapolating","materializing","finalizing"],ha=__name(()=>{const[e,t]=P(()=>Math.floor(Math.random()*pa.length));I(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*pa.length))},2e3);return()=>clearInterval(e)},[]);const n=pa[e];return A.createElement(w,{color:"yellow"},n,"...")},"PulsingText"),fa=__name(e=>String(e).padStart(3," "),"padNum"),ya=__name(e=>ma[e%ma.length],"getSymbol"),wa=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${fa(t)} ↓${fa(n)} (↑↓ scroll)`,"buildStatusLine"),Ea=__name(({insights:e})=>{const[t,n]=P(0),[r,o]=P(!0),s=e.length,a=s>10,i=Math.max(0,s-10);if(I(()=>{r&&a&&n(i)},[s,r,a,i]),k((e,t)=>{if(a)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(i,e+1);return t===i&&o(!0),t}))}),0===s)return null;const c=e.slice(t,t+10),l=t,d=s-t-10;return A.createElement(y,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&A.createElement(w,{dimColor:!0},wa(s,l,d,r)),c.map((e,n)=>{const r=t+n;return A.createElement(y,{key:r,marginBottom:0},A.createElement(w,{dimColor:!0},ya(r)," ",e))}))},"ScrollableInsights"),ba=__name(({label:e,message:t,active:n,complete:r,items:s,insights:a,isIntro:i,isAllComplete:c,summary:l})=>{if(i)return A.createElement(y,{flexDirection:"column",marginBottom:0},A.createElement(ga,null),A.createElement(y,{marginTop:0},A.createElement(w,{dimColor:!0},"⎿"),A.createElement(y,{marginLeft:2},c?A.createElement(w,{color:"green"},"learned your coding taste"):A.createElement(ha,null))));const d=__name(()=>{const[e,t]=P(!0);return I(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),A.createElement(w,{color:"yellow"},e?o.circleFilled:o.circle)},"PulsingDot"),u=__name(()=>r?A.createElement(w,{color:"green"},o.nodejs):n?A.createElement(d,null):A.createElement(w,{dimColor:!0},o.circle),"getStatusIcon"),m=s.length>0||a.length>0||t||l&&l.learningCount>0;return!r||n||m?A.createElement(y,{flexDirection:"column",marginBottom:0},(n||r)&&A.createElement(y,{marginBottom:0},A.createElement(y,{marginRight:1},u()),A.createElement(w,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!l||0===l.learningCount)&&A.createElement(y,{marginLeft:3,marginBottom:0},A.createElement(w,{dimColor:!0},t)),s.length>0&&A.createElement(y,{flexDirection:"column",marginLeft:1,marginBottom:0},s.map((e,t)=>A.createElement(w,{key:t,dimColor:!0},`${o.bullet} ${e}`))),a.length>0&&A.createElement(Ea,{insights:a}),r&&l&&l.learningCount>0&&A.createElement(y,{flexDirection:"column",marginLeft:1,marginBottom:0},A.createElement(y,{marginBottom:1,flexDirection:"row"},A.createElement(w,null,"⎿"),A.createElement(y,{marginLeft:2},A.createElement(w,{color:"green"},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),A.createElement(y,{flexDirection:"column",marginLeft:1},A.createElement(w,{dimColor:!0},o.pointerSmall," Stored in"," ",l.storage),A.createElement(w,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),ka=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return A.createElement(y,{flexDirection:"column",marginBottom:1},e.map((e,n)=>A.createElement(y,{key:e.id,marginLeft:0===n?0:3},A.createElement(ba,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),Sa=__name(({steps:e})=>A.createElement(ka,{steps:e}),"ProgressSection"),Ca=__name(({isImporting:e=!1,waitingForInput:t=!1})=>A.createElement(A.Fragment,null,e&&A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"ESC to cancel")),t&&A.createElement(y,{marginTop:1},A.createElement(w,{bold:!0},"Press ENTER to continue"))),"HelpTextSection"),va=[{id:"importing",label:"Initializing Taste Profile",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"batching",label:"Organizing your sessions",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"learning",label:"Learning your coding taste",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"complete",label:"Learned your coding taste!",message:"",active:!1,complete:!1,items:[],insights:[],summary:{learningCount:0,categories:[],storage:".commandcode/taste/taste.md"}}],Ta=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=Js(va),{isImporting:s,waitingForInput:a,error:i}=Xs(t);return ea({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),A.createElement(y,{flexDirection:"column",padding:1},o&&A.createElement(ua,{error:o}),!o&&A.createElement(Sa,{steps:r}),A.createElement(Ca,{isImporting:s,waitingForInput:a}))},"ImportProgress"),Aa=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:c})=>"asking"===e?"has_sessions"!==t?.reason?A.createElement(da,{onDemo:i,onSkip:c}):A.createElement(la,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:c,demoShown:t.demoShown}):"learning"===e?A.createElement(Ta,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?A.createElement(aa,{onComplete:a}):null,"OnboardingStepRenderer"),Pa=__name(({onComplete:e,autoLearn:t=!1})=>{I(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=ta({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=ra({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:c,handleImportError:l,handleErrorDismiss:d,handleDemoComplete:u,handleSkip:m}=na({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?A.createElement(oa,{error:r}):"done"===s?null:A.createElement(Aa,{step:s,conditions:n,onImportStart:i,onImportComplete:c,onImportError:l,onErrorDismiss:d,onDemoComplete:u,onDemo:()=>a("demo"),onSkip:m})},"TasteOnboarding"),xa=__name(({onTrust:e,onExit:t})=>{const{exit:n}=S(),[r,s]=P(1),a=process.cwd().replace(process.env.HOME||"","~");return k((o,a)=>{a.upArrow||a.downArrow?s(1===r?2:1):a.return?1===r?e():(t(),n()):"1"===o?e():("2"===o||a.escape||a.ctrl&&"c"===o)&&(t(),n())}),A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},A.createElement(w,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),A.createElement(y,{marginTop:1},A.createElement(w,{color:"gray"},a)),A.createElement(y,{marginTop:1,flexDirection:"column"},A.createElement(w,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),A.createElement(y,{marginTop:1},A.createElement(w,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),A.createElement(y,{marginTop:1,flexDirection:"column"},A.createElement(y,null,A.createElement(w,{color:1===r?"cyan":"gray"},1===r?o.pointer:" "," 1. Yes, proceed")),A.createElement(y,null,A.createElement(w,{color:2===r?"cyan":"gray"},2===r?o.pointer:" "," 2. No, exit"))))},"TrustPrompt"),Ia=__name(({onComplete:e,onCancel:t})=>{const[n,r]=P(!1),[o,s]=P(""),{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u,cancel:m}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return k((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");m()}}),n?A.createElement(At,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):A.createElement(wt,{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u})},"LoginOverlay"),$a=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;constructor(){this.filePath=B.join(K.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await M.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean).slice(-100);let t=0;this.buffer=e.map(e=>{try{return JSON.parse(e).p}catch{return t++,""}}).filter(Boolean),t>0&&dlog(`[PromptHistory] Skipped ${t} corrupted entries`)}catch(e){e instanceof Error&&"code"in e&&"ENOENT"===e.code||dlog(`[PromptHistory] Failed to load history: ${e instanceof Error?e.message:String(e)}`),this.buffer=[]}this.initialized=!0}}add(e){if(!e||0===e.trim().length)return;const t=e.length>500?e.slice(0,500)+"...":e;this.buffer.push(t),this.buffer.length>500&&(this.buffer=this.buffer.slice(-500)),this.writeQueue.push({p:t,t:Date.now()}),this.scheduleFlush()}getAt(e){if(e<0||e>=this.buffer.length)return;const t=this.buffer.length-1-e;return this.buffer[t]}count(){return this.buffer.length}getAll(){return[...this.buffer]}isInitialized(){return this.initialized}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,await this.flush()},100))}async flush(){if(0===this.writeQueue.length)return;if(this.isFlushing)return void this.scheduleFlush();if(this.writeFailures>=3)return void(this.writeQueue=[]);this.isFlushing=!0;const e=this.writeQueue;this.writeQueue=[];try{const t=B.dirname(this.filePath);await M.mkdir(t,{recursive:!0});const n=e.map(e=>JSON.stringify(e)).join("\n")+"\n";await M.appendFile(this.filePath,n),this.writeFailures=0,await this.rotateIfNeeded()}catch(t){this.writeFailures++;const n=t instanceof Error?t.message:String(t);this.writeFailures<3?(this.writeQueue.unshift(...e),dlog(`[PromptHistory] Write failed, retrying (${this.writeFailures}/3): ${n}`)):dlog(`[PromptHistory] Write disabled after 3 failures: ${n}`)}finally{this.isFlushing=!1}}async rotateIfNeeded(){try{const e=await M.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await M.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await M.writeFile(this.filePath,n.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${n.length} of ${t.length} entries`)}catch(e){dlog(`[PromptHistory] Rotation failed (non-critical): ${e instanceof Error?e.message:String(e)}`)}}async cleanup(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);const e=Date.now();for(;this.isFlushing;){if(Date.now()-e>=5e3){dlog("[PromptHistory] Cleanup timed out waiting for flush after 5000ms");break}await new Promise(e=>setTimeout(e,10))}await this.flush()}};function createHistoryManager(){return new $a}__name(createHistoryManager,"createHistoryManager");var Da=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),Fa=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r})=>{const o=[];e.forEach((s,a)=>{const i=a===t&&!r,c=n.has(a);let l,d;i?(l="●",d="cyan"):c?(l="✓",d="green"):(l="○",d="gray"),o.push(A.createElement(w,{key:a},A.createElement(w,{color:d},l),A.createElement(w,{color:i?"cyan":void 0}," ",s.header),a<e.length-1?A.createElement(w,{dimColor:!0}," | "):null))});const s=r;return o.push(A.createElement(w,{key:"review"},A.createElement(w,{dimColor:!0}," | "),A.createElement(w,{color:s?"cyan":"gray"},s?"●":"○"),A.createElement(w,{color:s?"cyan":void 0,bold:s}," ","Review"))),A.createElement(y,null,o)},"TabIndicator"),Ra=__name(({questions:e,onResponse:t})=>{const[n,r]=P(0),[s,a]=P(new Map),i=x(new Map),[c,l]=P(""),[d,u]=P(new Set),[m,g]=P(null),[p,h]=P(!1),[f,E]=P(!1),[b,S]=P(!1),[C,v]=P(null),[T,I]=P(!1),$=e[n],D=$?.multiSelect??!1,F=s.get(n),R=$?[...$.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],M=R.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),L=new Map(M.map((e,t)=>[e.label,R[t]])),O=__name(e=>{"submit"===e.value?W():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),N=__name(()=>{if(!F||0===F.length)return 0;const e=F[0],t=$.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),U=__name(e=>{if(!p)if(D){const t=Da(e.value,$.options.length-1);if(null===t)return;const n=$.options[t]?.label||"";u(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=Da(e.value,$.options.length-1);if(null===t)return;h(!0);const n=$.options[t]?.label||"";B([n])}},"handleSelect"),j=__name(()=>{if(p)return;h(!0);const e=Array.from(d);B(e)},"handleMultiSelectDone"),_=__name(()=>{if(!p&&c.trim())if(D){const e=new Set($.options.map(e=>e.label));u(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(c.trim()),n})}else h(!0),B([c.trim()])},"handleOtherSubmit"),B=__name(t=>{i.current.set(n,t);const o=new Map(i.current);a(o);const s=__name(t=>{const n=e[t],r=i.current.get(t);if(n?.multiSelect&&r){u(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==r?.length)l("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);l(t&&e?e:"")}},"restoreStateForQuestion");if(n<e.length-1){const e=n+1;s(e),r(e),h(!1),S(!1),v(null),I(!1)}else if(e.every((e,t)=>o.has(t)))u(new Set),l(""),E(!0),h(!1);else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(s(t),r(t)),h(!1),S(!1),v(null),I(!1)}},"finishQuestion"),W=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:i.current.get(t)||[]}));t({answers:n})},"submitAnswers"),H=__name(t=>{E(!1),r(t),I(!1),S(!1),v(null);const n=e[t],o=i.current.get(t);if(n?.multiSelect&&o){u(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),n?.multiSelect||1!==o?.length)l("");else{const e=o[0],t=!n.options.some(t=>t.label===e);l(t&&e?e:"")}},"editQuestion"),z=__name(t=>{if(t<0||t>=e.length)return;D&&(d.size>0?i.current.set(n,Array.from(d)):i.current.delete(n),a(new Map(i.current))),h(!1),S(!1),v(null),I(!1);const o=e[t],s=i.current.get(t);if(o?.multiSelect&&s){u(new Set(s));const e=s.find(e=>!o.options.some(t=>t.label===e));l(e||"")}else if(u(new Set),o?.multiSelect||1!==s?.length)l("");else{const e=s[0],t=!o.options.some(t=>t.label===e);l(t&&e?e:"")}r(t)},"navigateToQuestion"),G=__name(()=>{if(!m||!D)return;if("done"===m.value)return;const e=Da(m.value,$.options.length-1);if(null===e)return;const t=$.options[e]?.label||"";u(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return k((t,r)=>{if(" "===t&&D&&!b&&G(),"d"!==t||!D||b||f||j(),!f&&!p){if(r.downArrow&&!b&&!T&&m&&M.length>0&&m.value===M[M.length-1]?.value&&S(!0),r.upArrow&&!b&&!T&&m&&M.length>0&&m.value===M[0]?.value&&(D?I(!0):(S(!0),v(M.length-1))),r.upArrow&&b){S(!1),v(M.length-1);const e=M[M.length-1];e&&g(e)}if(r.downArrow&&b)if(S(!1),D)I(!0);else{v(0);const e=M[0];e&&g(e)}if(r.upArrow&&T&&(I(!1),S(!0)),r.downArrow&&T){I(!1),v(0);const e=M[0];e&&g(e)}r.return&&T&&D&&j()}if(p||b||T||(f?r.leftArrow&&H(e.length-1):r.leftArrow&&n>0?z(n-1):r.rightArrow&&(n<e.length-1?z(n+1):(D&&(d.size>0?i.current.set(n,Array.from(d)):i.current.delete(n),a(new Map(i.current))),E(!0)))),r.escape&&!p)if(f)E(!1);else if(b){S(!1);const e=C??M.length-1;v(e);const t=M[e];t&&g(t)}else if(T){I(!1);const e=M[M.length-1];e&&g(e)}}),$||f?f?A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},A.createElement(y,{marginBottom:1},A.createElement(Fa,{questions:e,currentIndex:e.length,answeredQuestions:new Set(s.keys()),isReviewPage:!0})),e.map((e,t)=>A.createElement(y,{key:t,marginBottom:1,flexDirection:"column"},A.createElement(w,{dimColor:!0},t+1,". ",e.question),A.createElement(w,{color:"green"}," ",s.get(t)?.join(", ")||"No answer"))),A.createElement(Ce,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:O,initialIndex:0,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:"cyan"},e?o.pointer:" "),itemComponent:({label:e,isSelected:t})=>A.createElement(w,{color:t?"cyan":"white"},e)}),A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},o.arrowLeft," to go back and edit"))):A.createElement(y,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},A.createElement(y,{marginBottom:1},A.createElement(Fa,{questions:e,currentIndex:n,answeredQuestions:new Set(s.keys()),isReviewPage:!1})),A.createElement(y,{marginBottom:1},A.createElement(w,{bold:!0},$.question)),b||T?A.createElement(y,{flexDirection:"column"},M.map((e,t)=>{const n=L.get(e.label),r=D&&n&&d.has(n.label),s=!D&&n&&F?.includes(n.label),a=r||s;return A.createElement(y,{key:t,flexDirection:"column"},A.createElement(y,null,A.createElement(w,null," "),A.createElement(w,{color:a?"green":"white"}," ",t+1,"."," "),D&&(a?A.createElement(w,{color:"green"},"[",o.tick,"]"," "):A.createElement(w,{dimColor:!0},"[ ] ")),A.createElement(w,{color:a?"green":"white"},n?.label||""),!D&&a&&A.createElement(w,{color:"green"}," ",o.tick)),n?.description&&A.createElement(y,null,A.createElement(w,null," "),A.createElement(w,{dimColor:!0},D?" ":" ",n.description)))})):A.createElement(Ce,{key:`${n}-${C??"default"}`,items:M,initialIndex:C??N(),onSelect:U,onHighlight:g,indicatorComponent:({isSelected:e})=>A.createElement(w,{color:"cyan"},e?o.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=L.get(e),r=D&&n&&d.has(n.label),s=!D&&n&&F?.includes(n.label),a=r||s,i=e.match(/^\s*(\d+)\.\s*(.*)$/),c=i?.[1]||"",l=i?.[2]||e;return A.createElement(y,{flexDirection:"column"},A.createElement(y,null,A.createElement(w,{color:t?"cyan":a?"green":"white"}," ",c,"."," "),D&&(a?A.createElement(w,{color:"green"},"[",o.tick,"]"," "):A.createElement(w,{dimColor:!0},"[ ] ")),A.createElement(w,{color:t?"cyan":a?"green":"white"},l),!D&&a&&A.createElement(w,{color:"green"}," ",o.tick)),n?.description&&A.createElement(w,{dimColor:!0},D?" ":" ",n.description))}}),A.createElement(y,null,A.createElement(w,{color:"cyan"},b?o.pointer:" "),A.createElement(w,{color:b?"cyan":void 0}," ",M.length+1,"."," "),D&&(d.has(c.trim())?A.createElement(w,{color:"green"},"[",o.tick,"] "):A.createElement(w,{dimColor:!0},"[ ] ")),A.createElement(Fe,{value:c,onChange:e=>{const t=c.trim();l(e),D&&u(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:_,placeholder:"Type something...",focus:b})),D&&A.createElement(y,null,A.createElement(w,{color:"cyan"},T?o.pointer:" "),A.createElement(w,{color:T?"cyan":void 0,bold:T}," ",n===e.length-1?"Submit":"Next")),e.length>1&&A.createElement(y,{marginTop:1},A.createElement(w,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=ir(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,a=e.metadata?.elapsedSeconds||0,i=e.metadata?.recentTools||[],[c,l]=P(".");return I(()=>{const e=setInterval(()=>{l(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),A.createElement(y,{flexDirection:"column",marginBottom:1,width:"90%"},A.createElement(y,null,A.createElement(w,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&A.createElement(w,null," ","(",o,")")),A.createElement(y,{columnGap:1,marginLeft:1},A.createElement(w,null,"⎿"," "),A.createElement(w,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",c)),i.length>0&&A.createElement(y,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=ir(e.name);return A.createElement(y,{key:t,columnGap:1},A.createElement(w,{color:"gray"},"⎿"),A.createElement(w,{color:"gray"}," ",n),e.input&&A.createElement(w,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:A.createElement(LiveAgentStatusInner,{entry:e})}__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus");var{setText:Ma}=ue;function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}__name(createKillShellPermissionRequest,"createKillShellPermissionRequest");var La=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1})=>{const{exit:c}=S(),[l,d]=P(""),[u,m]=P("Ready..."),[g,p]=P(null),[h,f]=P(o);I(()=>{if(h){const e=setTimeout(()=>{f(null)},3e4);return()=>clearTimeout(e)}},[h]);const{stdout:E}=C(),[b,v]=P(!1),[T,D]=P(!1),[F,R]=P(!1),[M,L]=P(!1),[O,N]=P(!1),[U,j]=P(!1),[_,B]=P(!1),[W,H]=P(!1),[z,G]=P(null),[q,V]=P(null),[K,J]=P(getConfiguredModel()),[Y,Q]=P(!1),[Z,X]=P(!1),[ee,te]=P(!1),ne=x(null),re=x(null),[oe,se]=P(0),[ae,ie]=P(!1),{executeBash:ce,executionState:le}=po(),[de,ue]=P(""),[me,ge]=P([]),[pe,he]=P([]),[fe,ye]=P(!1),[we,Ee]=P([]),[be,ke]=P(crypto.randomUUID()),[Se,Ce]=P(!1),[ve,Te]=P(!1),Ae=x(null),[Pe,xe]=P(!1),[Ie,$e]=P(!1),[De,Fe]=P(!0),[Re,Me]=P(!1),[Le,Oe]=P(!1),[Ne,Ue]=P(null),[je,_e]=P(!1),Be=x(!1),[We,He]=P(!1),[ze,qe]=P(0),[Ve,Ke]=P(null),[Je,Qe]=P(null),[Ze,Xe]=P(null),tt=x(!1),nt=x(!1),rt=x(Ze);I(()=>{rt.current=Ze},[Ze]);const[ot,st]=P(!1),[at,it]=P(""),[ct,lt]=P(!1),[dt,ut]=P(!!r),[mt,gt]=P(""),pt=x(null),ht=x(null),ft=__name(()=>{pt.current&&clearTimeout(pt.current),ht.current&&clearTimeout(ht.current),ne.current&&clearTimeout(ne.current),re.current&&clearTimeout(re.current)},"cleanupTimers"),[wt,Et]=P(!1),[bt,kt]=P(!1),St=x(null),Ct=x(0),[vt,Tt]=P(null),At=$(()=>{St.current=null,Tt(null),ht.current&&(clearTimeout(ht.current),ht.current=null)},[]);I(()=>{if(We){ft();try{c()}catch{process.exit(0)}}},[We,c]);const Pt=$(()=>{Oe(!0),Me(!1),_e(!1),yo(),se(e=>e+1),e&&Ce(!0)},[e,t]),xt=__name(async()=>{try{const e=await isTasteLearningEnabled();lt(e),e&&await Wo.initializeProject()}catch(e){}},"loadTasteStatus"),It=__name(async()=>{const e=await getConfiguredProvider();V(e);const t=await isOAuthEnforced();Q(t)},"loadCurrentProvider"),$t=x([]),Dt=x(null),Ft=x(null),[Rt,Mt]=P(null),[Lt,Ot]=P(null),{requestShellPermission:Nt,service:Ut,respondToPrompt:jt,clearSessionPermissions:_t,setEnabled:Bt}=fo({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{Mt({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),Dt.current&&m("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Mt({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),Dt.current&&m("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?m("Permission granted"):m("Permission denied")},"onPermissionResponse")}),Wt=__name(e=>{pt.current&&clearTimeout(pt.current),gt(e),pt.current=setTimeout(()=>{gt(""),pt.current=null},5e3)},"showHintMessage");I(()=>()=>ft(),[]),I(()=>{Ut&&applyAutoAcceptMode({enabled:dt,service:Ut})},[dt,Ut]),I(()=>{(async()=>{if(await Yr.isProjectInitialized())if($e(!0),Fe(!1),xt(),It(),t){const e=await Yr.listSessions();if(e.length>0){const t=e[0];un(t.id)}}else e&&Ce(!0);else if(n)if(await Yr.initializeProject(),$e(!0),Fe(!1),xt(),It(),t){const e=await Yr.listSessions();if(e.length>0){const t=e[0];un(t.id)}}else e&&Ce(!0);else isDirectoryEmpty()?(await Yr.initializeProject(),$e(!0),Fe(!1),xt(),It()):(xe(!0),Fe(!1))})()},[e,t,n,c]),I(()=>{i||triggerTasteOnboarding({projectTrusted:Ie,onboardingComplete:Le,isOnboardingMode:Re,tasteOnboardingCheckedRef:Be,setIsOnboardingMode:Me})},[Ie,Le,Re,i]),I(()=>{if(Re&&!Ne){const e=Zn();Ue(e.id),ge(t=>[...t,e])}else!Re&&Ne&&(ge(e=>e.filter(e=>e.id!==Ne)),Ue(null))},[Re,Ne]),I(()=>{$t.current=we},[we]),I(()=>{(async()=>{if(q&&"anthropic"===q&&Y)try{await yt.getValidAccessToken()||m("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){m("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[q,Y]),I(()=>{if(!fe)return;if(null!==g)return;const e=setInterval(()=>{m(ar())},7e3);return()=>clearInterval(e)},[fe,g]);const Ht=$(()=>{const e=!fe&&!Rt&&!Lt,t=Dt.current?.hasCheckpoints()??!1;e&&t&&Et(!0)},[fe,Rt]),zt=__name(()=>{ut(e=>{const t=!e;return t&&Rt&&(jt({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),Rt.resolve(!0),Mt(null)),t})},"handleToggleAutoAccept");async function getBillingLink(){if(Je)return Je;try{const e=await getAuthKey();if(!e)return;const t=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return Qe(e),e}if(t.org){const e=`https://commandcode.ai/${t.org.login}/settings/billing`;return Qe(e),e}}catch(e){return"https://commandcode.ai/settings/billing"}}k((e,t)=>{if(t.shift&&t.tab||""===e)zt();else if(F||M||O||U||_||z||W||wt||bt)vt&&At();else{if(""===e||t.ctrl&&"c"===e){const e=Date.now(),t=e-Ct.current;return Ct.current=e,void("ctrl-c"===St.current&&t<2e3?(ht.current&&(clearTimeout(ht.current),ht.current=null),He(!0)):(d(""),St.current="ctrl-c",Tt("ctrl-c"),ht.current&&clearTimeout(ht.current),ht.current=setTimeout(()=>{St.current=null,Tt(null),ht.current=null},2e3)))}if(t.ctrl&&"t"===e)return yo(),H(e=>!e),void se(e=>e+1);if(getIsExpandToolShortcut(t,e))return yo(),ie(e=>!e),void se(e=>e+1);if(t.escape){if(Lt)return Lt.reject(new Error("Question cancelled by user")),Ot(null),void m("Question cancelled");if(Rt)jt({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),Rt.resolve(!1),Mt(null),m("Permission denied");else if(fe&&Dt.current){Dt.current.interrupt(!0);const e=pe.length>0;if(ye(!1),p(null),he([]),m("Interrupted by user"),!e){const e=Qn("Interrupted by user");ge(t=>[...t,e])}if($t.current.length>0){const e=$t.current.join("\n");d(t=>t?e+"\n"+t:e),Ee([]),$t.current=[]}}}t.meta||t.ctrl}}),I(()=>{const e=__name(()=>{yo(),se(e=>e+1)},"handleResize");if(E)return E.on("resize",e),()=>{E.off("resize",e)}},[E]),I(()=>{Dt.current||!Ie||Se||ve||(Dt.current=new uo({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?he(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(he(t=>t.filter(t=>t.id!==e.id)),ge(t=>[...t,e])):ge(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...$t.current];return $t.current=[],Ee([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{qe(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ke(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{p(e)},"onRetryUpdate"),onProviderChange:__name(e=>{V(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("kill_shell"===e&&Ut){const e=createKillShellPermissionRequest(t);return Ut.requestShellPermission(e).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"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Ot({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=rt.current;return e?{sessionId:be,secret:e.secret}:null},"getShareInfo")},be),(async()=>{await en()})())},[be,Se,ve,Ie]),I(()=>{if(!Ie)return;const e=createHistoryManager();return Ae.current=e,e.init(),()=>{e.cleanup()}},[Ie]),I(()=>{a&&Ie&&!De&&Dt.current&&!Se&&!nt.current&&(nt.current=!0,Gt({role:"user",input:a}))},[a,Ie,De,Se]),__name(getBillingLink,"getBillingLink");const Gt=__name(async({role:e,input:t,images:n})=>{if(t.length)if(h&&f(null),qe(0),"bash"===e){if(tt.current)return;tt.current=!0;const e=Jn(t);ge([...me,e]),d(""),await ce(t,e=>{ge(e)},()=>{yo(),se(e=>e+1)}),tt.current=!1}else{if(fe)return Ee(e=>[...e,t]),void d("");if(tt.current)return;tt.current=!0,ye(!0),m(ar()),d("");try{Dt.current&&await Dt.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){m("Insufficient credits");const e=await getBillingLink(),t=Qn(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);ge(e=>[...e,t])}else if(e.message.startsWith("Error:")){m("Error");const t=Qn(e.message);ge(e=>[...e,t])}else{m("Error");const t=e.message||"An unexpected error occurred",n=Qn(t);ge(e=>[...e,n])}}finally{ye(!1),"Interrupted by user"!==u&&"Permission denied"!==u&&"Insufficient credits"!==u&&m("Ready..."),tt.current=!1}}},"handleSubmit"),qt=__name(()=>{ge(e=>[...e,Yn("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),Vt=__name(()=>{const e=Gn("/terminal-setup"),t=setupVSCodeTerminal(),n=Xn(t.message,!t.success,t.details);ge(t=>[...t,e,n])},"handleTerminalSetupCommand"),Kt=__name(async()=>{if(ge([]),he([]),yo(),ut(!!r),Xe(null),st(!1),it(""),Dt.current){const e=Dt.current.getSessionManager();e&&await e.deleteShareInfo(),Dt.current=null;const t=crypto.randomUUID();ke(t),_t(),Dt.current=new uo({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?he(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(he(t=>t.filter(t=>t.id!==e.id)),ge(t=>[...t,e])):ge(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...$t.current];return $t.current=[],Ee([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{qe(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ke(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{p(e)},"onRetryUpdate"),onProviderChange:__name(e=>{V(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("kill_shell"===e&&Ut){const e=createKillShellPermissionRequest(t);return Ut.requestShellPermission(e).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"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Ot({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=rt.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}se(e=>e+1),Ke(null),qe(0)},"handleClearCommand"),Jt=__name(()=>{Dt.current?Dt.current.hasCheckpoints()?Et(!0):ge(e=>[...e,qn("No checkpoints available. Start sending messages to create checkpoints.")]):ge(e=>[...e,qn("No active conversation to rewind.")])},"handleRewindCommand"),Yt=__name(async e=>{const{messageId:t,mode:n}=e;if(Et(!1),Dt.current)try{const e=Dt.current.listCheckpoints().find(e=>e.messageId===t);m("Restoring checkpoint...");const r=await Dt.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=Dt.current.getSessionManager(),n=Dt.current.getMessages(),o=t.reconstructFeedFromMessages(n);ge(o),yo(),se(e=>e+1),e&&e.userPrompt&&d(e.userPrompt);const s=[];r.filesRestored>0&&s.push(`${r.filesRestored} file${r.filesRestored>1?"s":""} restored`),r.filesDeleted>0&&s.push(`${r.filesDeleted} file${r.filesDeleted>1?"s":""} deleted`),r.messagesRemoved>0&&s.push(`${r.messagesRemoved} message${r.messagesRemoved>1?"s":""} removed`);const a=s.length>0?`Restored to checkpoint: ${s.join(", ")}.`:"Restored to checkpoint.";ge(e=>[...e,qn(a)]),m("Ready...")}else ge(e=>[...e,Qn(`Failed to restore: ${r.error}`)]),m("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;ge(e=>[...e,Qn(t)]),m("Ready...")}},"handleRewindSelect"),Qt=__name(()=>{Et(!1)},"handleRewindCancel"),Zt=__name(async()=>{if(Dt.current)if(Dt.current.isRequestInProgress())ge(e=>[...e,qn("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{m("Compacting conversation...");const e=await Dt.current.compactConversation();yo(),se(e=>e+1);const t=e.messagesRemoved>0?`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`:"Conversation is already compact.";ge(e=>[...e,qn(t)]),m("Ready..."),Ke({current:Dt.current.getContextTokensUsed()||0,limit:Kr})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;ge(e=>[...e,Qn(t)]),m("Ready...")}else ge(e=>[...e,qn("No active conversation to compact.")])},"handleCompactCommand"),Xt=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await un(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void He(!0);case"/clear":return void await Kt();case"/help":return void qt();case"/share":return void tn();case"/unshare":return void ln();case"/taste":return void R(!0);case"/learn-taste":return void await dn();case"/skills":return void L(!0);case"/provider":return void(isInternalTeamFlagEnforced()?N(!0):m("Provider selection not available"));case"/model":return void j(!0);case"/memory":return void B(!0);case"/init":return void rn();case"/agents":return void D(!0);case"/compact":return void await Zt();case"/rewind":return void Jt();case"/login":return void await on();case"/logout":return void await cn();case"/terminal-setup":return void Vt()}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});await Gt({input:e.content,role:"user"})}},"handleCommand"),en=__name(async()=>{const e=Dt.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&Xe({url:t.url,secret:t.secret})}},"loadShareInfo"),tn=__name(async()=>{if(be){if(Ze)return await Ma(Ze.url),m(""),st(!0),void setTimeout(()=>{st(!1)},3e3);try{m("Creating share link...");const e=Dt.current?.getMessages()||[],t=nn.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new pn({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:Ge.ALPHA.SHARE.CREATE,body:{sessionId:be,messages:t}}),o={url:r.url,secret:r.secret};Xe(o);const s=Dt.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await Ma(r.url),m(""),st(!0),setTimeout(()=>{st(!1)},5e3)}catch(e){m(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else m("No active session to share")},"handleShareCommand"),rn=__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.`;ge(e=>[...e,qn(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;ge(e=>[...e,qn(t)])}},"handleInitCommand"),on=__name(async()=>{const e=et();if(await getAuthKey(e)){let e="";try{const t=await loadCredentials();e=t?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const t=e&&"API Key"!==e&&"Manual API Key"!==e?` as ${e}`:"";return void ge(e=>[...e,qn(`Already logged in${t}`)])}kt(!0)},"handleLoginCommand"),sn=$((e,t)=>{kt(!1),e?(ge(e=>[...e,qn(t)]),Dt.current&&Dt.current.refreshRequest()):ge(e=>[...e,Qn(t)]),m("Ready...")},[]),an=$(()=>{kt(!1),ge(e=>[...e,qn("Authentication cancelled.")]),m("Ready...")},[]),cn=__name(async()=>{const e=await performLogout();e.success?(Dt.current&&Dt.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?ge(t=>[...t,qn(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):ge(e=>[...e,qn("Successfully logged out from Command Code.")]):ge(e=>[...e,qn("Not currently authenticated.")])):ge(t=>[...t,Qn(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),ln=__name(async()=>{if(be){if(!Ze)return it("NOT SHARED: Session is not currently shared"),void setTimeout(()=>it(""),5e3);try{m("Removing share link...");const e=new pn({baseUrl:getApiBaseUrl()});await e.delete({endpoint:Ge.ALPHA.SHARE.DELETE,body:{sessionId:be,secret:Ze.secret}});const t=Dt.current?.getSessionManager();t&&await t.deleteShareInfo(),it("UNSHARED: Sharing has stopped"),m(""),Xe(null),setTimeout(()=>{it("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;m(t),setTimeout(()=>m(""),5e3)}}else m("No active session to unshare")},"handleUnshareCommand"),dn=__name(async()=>{_e(!0),Me(!0);const e=Zn();Ue(e.id),ge(t=>[...t,e])},"handleLearnCommand"),un=__name(async e=>{const t=crypto.randomUUID();Ft.current=t;try{ge([]),he([]),Dt.current=null,ut(!1),ke(e),Ce(!1),Te(!0),Dt.current=new uo({onFeedUpdate:__name(e=>{if(Ft.current===t){const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?he(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(he(t=>t.filter(t=>t.id!==e.id)),ge(t=>[...t,e])):ge(t=>[...t,e])}},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...$t.current];return $t.current=[],Ee([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{qe(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ke(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{p(e)},"onRetryUpdate"),onProviderChange:__name(e=>{V(e)},"onProviderChange"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Ot({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=rt.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await Dt.current.loadSession(e);if(Ft.current!==t)return;await en();const s=[];if(0===n.length&&o>0?s.push(Qn(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(qn("Session loaded but contains no messages.")):(r>0&&s.push(qn(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),Ft.current!==t)return;ge(s),yo(),se(e=>e+1)}catch(e){if(Ft.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";ge([Qn(`Failed to load session: ${n}. Starting fresh session.`)]),Ce(!1),Te(!1),ke(crypto.randomUUID())}},"handleSelectSession"),mn=__name(async()=>{ge([]),he([]),Dt.current=null,ut(!1),ke(crypto.randomUUID()),Ce(!1),Te(!1)},"handleNewSession"),gn=__name(async()=>{try{await Yr.initializeProject(),xe(!1),e?(console.log("No conversations found to resume."),He(!0)):($e(!0),xt(),It())}catch(e){console.error("Failed to initialize project:",e),xe(!1),He(!0)}},"handleTrust"),hn=__name(()=>{He(!0)},"handleNoTrust"),fn=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void G({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),V(e),N(!1);const n=getProviderDisplayName(e);m(`Provider set to ${n}`),ne.current&&clearTimeout(ne.current),X(!0),ne.current=setTimeout(()=>{X(!1),ne.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),m("Failed to set provider"),N(!1)}},"handleProviderSelect"),yn=__name(()=>{N(!1)},"handleProviderCancel"),wn=__name(e=>{const t=Object.values(Ye).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),En=__name(async e=>{try{await setSelectedModel({model:e}),J(e),j(!1);const t=wn(e);m(`Model set to ${t}`),re.current&&clearTimeout(re.current),te(!0),re.current=setTimeout(()=>{te(!1),re.current=null},5e3)}catch(e){console.error("Failed to set model:",e),m("Failed to set model"),j(!1)}},"handleModelSelect"),bn=__name(()=>{j(!1)},"handleModelCancel"),kn=__name(()=>{if(z){G(null),N(!1),V(z.provider);const e=getProviderDisplayName(z.provider);m(`${e} authentication successful`),ne.current&&clearTimeout(ne.current),X(!0),ne.current=setTimeout(()=>{X(!1),ne.current=null},5e3)}},"handleAuthSuccess"),Sn=__name(()=>{G(null)},"handleAuthCancel");if(We)return null;if(Pe)return A.createElement(A.Fragment,null,A.createElement(Ws,{staticKey:oe}),A.createElement(xa,{onTrust:gn,onExit:hn}));if(De)return null;if(Se)return A.createElement(Gs,{onSelectSession:un,onNewSession:mn});if(!Ie)return null;if(Lt)return A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(Us,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:K}),A.createElement(y,{marginY:1},A.createElement(Ra,{questions:Lt.params.questions,onResponse:e=>{Lt.resolve(e),Ot(null),m("Answers submitted")}})));if(Rt){if("shell_command"===Rt.toolName){const e=Rt.params;return A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(Us,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:K}),pe.map(e=>A.createElement(LiveAgentStatus,{key:e.id,entry:e})),A.createElement(y,{marginY:1},A.createElement(qs,{request:e,onResponse:e=>{jt(e);const t="no"!==e.value;Rt.resolve(t),Mt(null),t?(m("Shell command allowed"),dt||Wt("Use shift+tab to enable auto-accept")):m("Shell command denied")},onToggleAutoAccept:zt})))}if("kill_shell"===Rt.toolName){const e=createKillShellPermissionRequest(Rt.params);return A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(Us,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:K}),A.createElement(y,{marginY:1},A.createElement(qs,{request:e,onResponse:e=>{jt(e);const t="no"!==e.value;Rt.resolve(t),Mt(null),t?(m("Process termination allowed"),dt||Wt("Use shift+tab to enable auto-accept")):m("Process termination denied")},onToggleAutoAccept:zt})))}{const e={action:Rt.toolName.includes("edit")?"edit":Rt.toolName.includes("write")?"create":Rt.toolName.includes("delete")?"delete":"edit",filePath:Rt.params.filePath||Rt.params.file_path||Rt.params.path||Rt.params.absolutePath||Rt.params.notebook_path||"unknown",description:`Allow ${Rt.toolName} operation`,oldContent:"edit_file"===Rt.toolName?Rt.params.oldContent:void 0,newContent:"edit_file"===Rt.toolName?Rt.params.newContent:void 0};return A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(Us,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:K}),pe.map(e=>A.createElement(LiveAgentStatus,{key:e.id,entry:e})),A.createElement(y,{marginY:1},A.createElement(_s,{request:e,onResponse:e=>{jt(e);const t="no"!==e.value;Rt.resolve(t),Mt(null),t?(m("File operation allowed"),dt||Wt("Use shift+tab to enable auto-accept")):m("File operation denied")},onToggleAutoAccept:zt})))}}return W?A.createElement(bs,{onClose:()=>{H(!1),se(e=>e+1)}}):F?A.createElement(A.Fragment,null,A.createElement(Ws,{staticKey:oe}),A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"Press Esc to return to conversation")),A.createElement(Ks,{onClose:()=>R(!1),onSettingsChange:xt,staticKey:oe}))):M?A.createElement(A.Fragment,null,A.createElement(Ws,{staticKey:oe}),A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(y,{marginBottom:1},A.createElement(w,{dimColor:!0},"Press Esc to return to conversation")),A.createElement(Vs,{onClose:()=>L(!1),staticKey:oe}))):A.createElement(y,{flexDirection:"column",width:"100%"},A.createElement(Us,{staticKey:oe,feed:me.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:ae,currentModel:K}),Ne&&A.createElement(Pa,{onComplete:Pt,autoLearn:je}),pe.map(e=>A.createElement(LiveAgentStatus,{key:e.id,entry:e})),A.createElement(RetryMessage,{attempt:g}),!O&&!U&&!z&&!_&&!T&&!wt&&!bt&&!Ne&&A.createElement(Es,{queuedMessages:we,isProcessing:fe,executionState:le,status:u,input:l,setInput:d,onSubmit:Gt,showFileList:b,setShowFileList:v,fileSearchQuery:de,setFileSearchQuery:ue,onCommand:Xt,outputTokens:ze,contextUsage:Ve,tasteLearning:ct,shareInfo:Ze,showShareNotification:ot,unshareNotificationMessage:at,updateStatus:h,updateFailedInfo:s,currentProvider:q,showProviderInfo:Z,autoAcceptMode:dt,onToggleAutoAccept:zt,hintMessage:mt,historyManager:Ae.current,pendingExitKey:vt,onResetPendingExitKey:At,onDoubleEscapeEmpty:Ht,retryAttempt:g}),O&&A.createElement(y,{marginY:1},A.createElement(Bs,{onSelect:fn,onCancel:yn,currentProvider:q})),U&&A.createElement(y,{marginY:1},A.createElement(js,{onSelect:En,onCancel:bn,currentModel:K})),T&&A.createElement(y,{marginY:1},A.createElement(as,{onCancel:()=>D(!1)})),_&&A.createElement(y,{marginY:1},A.createElement(ks,{onClose:()=>B(!1)})),wt&&Dt.current&&A.createElement(y,{marginY:1},A.createElement(zs,{checkpoints:Dt.current.listCheckpoints(),onSelect:Yt,onCancel:Qt})),z&&A.createElement(y,{marginY:1},A.createElement(z.Component,{onSuccess:kn,onCancel:Sn})),bt&&A.createElement(y,{marginY:1},A.createElement(Ia,{onComplete:sn,onCancel:an})))},"InteractiveCLI"),Oa=__name(e=>e?{isValid:!0}:{isValid:!1,errorMessage:["Error: Interactive mode requires a TTY terminal.","Please run this command directly in your terminal, not through a pipe or redirect."].join("\n")},"validateTtyEnvironment"),Na=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),Ua=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),ja=__name(({options:e})=>({resume:e.resume,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding}),"buildInteractiveCLIProps"),_a=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),Ba=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),Wa=__name(()=>{Ba()},"initializeTerminal"),Ha=__name(async(e={})=>{const t=Oa(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),Wa(),Na(e)){const e=await Yr.isProjectInitialized(),t=e?await Yr.listSessions():[],n=Ua({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=ja({options:e}),r=_a();b(A.createElement(La,{...n}),r)},"interactiveMode"),za=null,Ga=!1,qa=new Set([bn,kn,Tn]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(Ga)return;Ga=!0;const e=__name(e=>{za?.abort(),process.stderr.write(`\n${e}\n`),process.exit(130)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(0),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(1)})}async function printMode(e={}){setupSignalHandlers(),za=new AbortController;let t=e.query||"";if(!t){process.stdin.isTTY&&(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1));try{t=await readStdin()}catch(e){const t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`Error reading from stdin: ${t}\n`),process.exit(1)}}t.trim()||(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1)),await isAuthenticated()||(process.stderr.write('Error: Not authenticated. Please run "cmd login" first.\n'),process.exit(3)),e.dangerouslySkipPermissions&&process.stderr.write("Warning: Running with --dangerously-skip-permissions. File writes and shell commands will execute without prompts.\n");try{const n=await processQuery({query:t,signal:za.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions});process.stdout.write(n),n.endsWith("\n")||process.stdout.write("\n"),process.exit(0)}catch(e){e instanceof Error&&"AbortError"===e.name&&(process.stderr.write("\nCancelled.\n"),process.exit(130)),e instanceof an&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof cn&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof mn&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof on&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof gn&&(process.stderr.write("Error: The API server encountered an error. Please try again later.\n"),process.exit(7));const t=e instanceof Error?e.message:"Unknown error";/permission denied|access denied|not permitted|unauthorized/i.test(t)&&(process.stderr.write(`Error: ${t}\n`),process.exit(4)),process.stderr.write(`Error: ${t}\n`),process.exit(1)}}__name(readStdin,"readStdin"),__name(isAuthenticated,"isAuthenticated"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode");var Va=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===Ke&&(r=await yt.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,c=crypto.randomUUID(),l=await isTasteLearningEnabled(),d={[He]:Yr.getCurrentProjectDirName(),[ze]:l.toString(),[Be]:n.toString()};return r&&(d[We]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:c}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId},a=await e.post({body:s,stream:!0,endpoint:Ge.ALPHA.GENERATE,headers:t.headers,signal:r});return fe.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(qa.has(e.name)&&!n)return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool "${e.name}" requires permissions. Use --dangerously-skip-permissions to enable file writes and shell commands in print mode.`,is_error:!0};try{const n=await executeTool(e.name,e.input,{abortSignal:t});return{type:"tool_result",tool_use_id:e.id,content:n}}catch(t){if(t instanceof an||t instanceof cn||t instanceof mn||t instanceof on||t instanceof gn)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1}=e,o=getApiBaseUrl(),s=new pn({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let c=0,l="";for(;c<Va;){if(c++,n.aborted)throw new Error("Cancelled");const e=await callApi(s,i,a,n),t=e.content.filter(e=>"text"===e.type),o=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(l+=d),0===o.length)break;const u=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);u.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:u})}return c>=Va&&process.stderr.write(`Warning: Reached maximum conversation turns (${Va}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),l}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery");var Ka=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),Ja=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),Ya=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),t},"buildRuntimeOptions"),Qa=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),Za=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(void 0!==t.print){const n=Za(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=Ka(e);await Ja();const r=Ya(t),o=Qa({options:t,runtimeOptions:r,initialPrompt:n});Ha(o)}__name(interactiveModeAction,"interactiveModeAction"),globalThis.COMMAND_CODE_CWD=process.cwd();var Xa=__name(()=>process.cwd(),"getCwd"),ei=__name(()=>process.argv.slice(2),"getArgs"),ti=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),ni=__name(()=>{const e=Xa(),t=ei(),n=ti(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`)},"logStartupInfo");async function preRun(){ni(),await maybeRunPendingUpdate(),checkForUpdateAsync()}__name(preRun,"preRun");var ri=getPackageJson();function displayCustomHelp(){const e=ri.version,n=getInvokedCommandName(),r=Is.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(t.bold("Command Code")+t.gray(` v${e}`)),console.log(t.gray(As)),console.log(),console.log(t.bold("Usage")),console.log(` ${n} <command> [options]`),console.log(),console.log(t.bold("Options"));for(const e of xs){const r=e.key.replace(/^cmd/,n);console.log(" "+r.padEnd(20)+t.gray(e.description))}console.log(),console.log(t.bold("Commands"));for(const e of $s){const r=e.key.replace(/^cmd/,n);console.log(" "+r.padEnd(20)+t.gray(e.description))}console.log(),console.log(t.bold("Slash Commands"));for(const e of r)console.log(" "+e.key.padEnd(17)+t.gray(e.description));console.log(),console.log(t.bold("Keyboard Shortcuts"));for(const e of Ps)console.log(" "+e.key.padEnd(15)+t.gray(e.description));console.log(),console.log(t.bold("Examples"));for(const e of Fs)console.log(" "+e.replace(/^cmd/,n));console.log(),console.log(t.cyan("❯")+" "+t.gray(Rs.replace(/cmd/,n))),console.log(),console.log(t.bold("Links"));for(const e of Ds)console.log(" "+e.key.padEnd(20)+t.cyan(e.description));console.log()}function createProgram(){const e=new c;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(ri.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume","Resume a session (pick from history)").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").option("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").addOption(new l(je).hideHelp()).addOption(new l(_e).hideHelp()).addOption(new l("-d, --debug","Enable debug mode").hideHelp()).addOption(new l("--local","Use local server").hideHelp()).addOption(new l("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(r&&r!==n?`[cmd] subcommand: ${n}`:`[cmd] running: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const a=t.args;a.length>0&&dlog(`[cmd] arguments: ${a.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks");var oi=new c("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()}),si=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),ai=__name(e=>{const t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`},"formatUptime"),ii=__name(({icon:e,label:t,children:n})=>A.createElement(w,null,A.createElement(w,{color:"cyan"},e," "),A.createElement(w,{dimColor:!0},t.padEnd(12)),n),"Row"),ci=__name(({title:e})=>A.createElement(w,null,A.createElement(w,{color:"gray"},"───"),A.createElement(w,{color:"white"}," ",e," "),A.createElement(w,{color:"gray"},"─".repeat(35))),"Header"),li=__name(({title:e,marginTop:t=0,children:n})=>A.createElement(y,{flexDirection:"column",marginTop:t},A.createElement(ci,{title:e}),A.createElement(y,{flexDirection:"column",paddingY:1},n)),"Section"),di=__name(({cpuCount:e,totalMem:t})=>A.createElement(li,{title:"System Information"},A.createElement(ii,{icon:r.bullet,label:"Date"},A.createElement(w,null,formatDate())),A.createElement(ii,{icon:r.pointer,label:"Platform"},A.createElement(w,{color:"green"},si(K.platform())),A.createElement(w,{dimColor:!0}," ","(",K.platform(),", ",K.arch(),")")),A.createElement(ii,{icon:r.triangleUp,label:"Hostname"},A.createElement(w,null,K.hostname())),A.createElement(ii,{icon:r.bullet,label:"User"},A.createElement(w,{color:"yellow"},K.userInfo().username)),A.createElement(ii,{icon:r.bullet,label:"CPUs"},A.createElement(w,{color:"magenta"},e," cores")),A.createElement(ii,{icon:r.bullet,label:"Memory"},A.createElement(w,{color:"cyan"},t," GB")),A.createElement(ii,{icon:r.play,label:"Uptime"},A.createElement(w,null,ai(K.uptime()))),A.createElement(ii,{icon:r.arrowRight,label:"Home"},A.createElement(w,{dimColor:!0},K.homedir())),A.createElement(ii,{icon:r.pointer,label:"Shell"},A.createElement(w,null,process.env.SHELL||"N/A")),A.createElement(ii,{icon:r.bullet,label:"Node"},A.createElement(w,{color:"green"},process.version))),"SystemInfoSection"),ui=__name(({cpus:e})=>A.createElement(li,{title:"CPU Details",marginTop:1},e.map((e,t)=>A.createElement(ii,{key:t,icon:r.bullet,label:`Core ${t}`},A.createElement(w,null,e.model.trim()),A.createElement(w,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),mi=__name(({networkInterfaces:e})=>A.createElement(li,{title:"Network",marginTop:1},Object.entries(e).map(([e,t])=>{const n=t?.filter(e=>"IPv4"===e.family&&!e.internal);return n&&0!==n.length?n.map((t,n)=>A.createElement(ii,{key:`${e}-${n}`,icon:r.bullet,label:e},A.createElement(w,{color:"green"},t.address))):null})),"NetworkSection"),gi=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>A.createElement(y,{flexDirection:"column"},A.createElement(w,null,"System Information"),A.createElement(w,null,"─".repeat(40)),A.createElement(w,null,"Date ",formatDate()),A.createElement(w,null,"Platform ",si(K.platform())," (",K.platform(),","," ",K.arch(),")"),A.createElement(w,null,"Hostname ",K.hostname()),A.createElement(w,null,"User ",K.userInfo().username),A.createElement(w,null,"CPUs ",e.length," cores"),A.createElement(w,null,"Memory ",t," GB"),A.createElement(w,null,"Uptime ",ai(K.uptime())),A.createElement(w,null,"Home ",K.homedir()),A.createElement(w,null,"Shell ",process.env.SHELL||"N/A"),A.createElement(w,null,"Node ",process.version),r&&A.createElement(A.Fragment,null,A.createElement(w,null,"\n","CPU Details"),A.createElement(w,null,"─".repeat(40)),e.map((e,t)=>A.createElement(w,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),A.createElement(w,null,"\n","Network"),A.createElement(w,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>A.createElement(w,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),pi=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>A.createElement(y,{flexDirection:"column"},A.createElement(di,{cpuCount:e.length,totalMem:t}),r&&A.createElement(ui,{cpus:e}),r&&A.createElement(mi,{networkInterfaces:n})),"StyledInfo"),hi=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=S();I(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=K.cpus(),o=K.networkInterfaces(),s=Math.round(K.totalmem()/1024/1024/1024);return t?A.createElement(gi,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):A.createElement(pi,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),fi=new c("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{const{waitUntilExit:t}=b(A.createElement(hi,{verbose:e.verbose,text:e.text}));await t()}),yi=new c(Je).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=b(A.createElement(Ta,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}catch(e){dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});function getTastePath(e){const{target:t}=e;switch(t){case"local-project":return B.join(process.cwd(),".commandcode","taste");case"local-global":return B.join(K.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 B.join(getTastePath({target:t}),"taste.md")}function getCategoryPath(e){const{target:t,category:n}=e;return B.join(getTastePath({target:t}),n)}function getCategoryTasteFile(e){const{target:t,category:n}=e;return B.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 s=[];for(const e of t){const t=parseLearning({line:e});t&&s.push(t)}s.length>0&&r.push({category:normalizeCategory({category:o}),learnings:s,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 wi=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!X(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(X(n)){let e=await M.readFile(n,"utf-8");const r=migrateHeader({content:e});r!==e&&(await M.writeFile(n,r,"utf-8"),e=r);const o=parseTasteBuckets({content:e,sourcePath:n});t.push(...o)}const r=await M.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(X(n)){let r=await M.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await M.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}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 M.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,s=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:s}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:s})}async removeBucket(e){const{category:t}=e,n=getRootTasteFile({target:this.target});let r=null;if(X(n)){let e=await M.readFile(n,"utf-8");e=migrateHeader({content:e});const o=e.split("\n");let s=-1,a=-1;const i=new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let e=0;e<o.length;e++)if(i.test(o[e])){s=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--;a=n;break}-1===a&&(a=o.length-1);break}if(-1!==s){const e=o.slice(0,s),t=a<o.length-1?o.slice(a+1):[];r={before:e.join("\n").trim(),after:t.join("\n").trim()};const i=[...e,...t].join("\n").trim();""===i?await M.rm(n,{force:!0}):await M.writeFile(n,i+"\n","utf-8")}}const o=getCategoryTasteFile({target:this.target,category:t}),s=B.dirname(o);return X(s)&&await M.rm(s,{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(_o)&&(e=_o+"\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 M.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";X(n)&&(e=await M.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(_o)||(e=_o+"\n\n"+e):e=_o+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await M.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}),s=B.dirname(o);await M.mkdir(s,{recursive:!0});const a=formatBucket({bucket:t});await M.writeFile(o,a,"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(_o)&&(e=_o+"\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 M.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";X(n)&&(e=await M.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(_o)||(e=_o+"\n\n"+e):e=_o+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i,await M.writeFile(n,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return X(e)}},Ei=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!X(e))return[];const t=[],n=await M.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(X(n)){let r=await M.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await M.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});if(!X(n))return null;let r=await M.readFile(n,"utf-8");const o=migrateHeader({content:r});return o!==r&&(await M.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 M.mkdir(n,{recursive:!0});const r=getCategoryTasteFile({target:this.target,category:t.category}),o=B.dirname(r);await M.mkdir(o,{recursive:!0});const s=formatBucket({bucket:t});await M.writeFile(r,s,"utf-8")}async deleteBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t}),r=B.dirname(n);X(r)&&await M.rm(r,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await M.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 X(e)}};async function prepareUploadFormData(e){const{packageName:t,bucket:n,description:r,type:o="category",isPublic:s=!1}=e,a=new FormData;if(a.append("name",t),r&&a.append("description",r),a.append("type",o),a.append("isPublic",String(s)),"category"===o){const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});a.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"});a.append("files[taste.md]",r);const o=getTastePath({target:"local-project"}),s=B.join(o,n.category);if(X(s)){const e=getCategoryTasteFile({target:"local-project",category:n.category});if(X(e)){const t=await M.readFile(e,"utf-8"),r=new Blob([t],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});a.append(`files[${n.category}/taste.md]`,o)}}}return a}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r,isPublic:o=!1}=e,s=new FormData;s.append("name",n),r&&s.append("description",r),s.append("type","project"),s.append("isPublic",String(o));const a=getRootTasteFile({target:"local-project"});if(X(a)){const e=await M.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(X(t)){const n=await M.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});s.append(`files[${e.category}/taste.md]`,o)}}return s}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 bi=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()}${Ge.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 s=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&s.push(t)}catch(t){console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return s}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=getApiBaseUrl(),o=`${r}${Ge.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 s=await getAuthKey();if(!s)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");const a=`${r}${Ge.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,i=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${s}`}});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 s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async 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 s=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category",isPublic:r}),a=`${getApiBaseUrl()}${Ge.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:s});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,s=await getAuthKey();if(!s)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareMultiplePackagesUpload({buckets:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${Ge.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});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()}${Ge.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 s=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(s.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(s.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(s.values()),details:r}}__name(mergeLearnings,"mergeLearnings");var ki=/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"),s=[];let a=0;for(;a<o.length;){const e=o[a],t=a+1,n=e.trim();if(n.startsWith("-"))if(ki.test(n))s.push({text:e,originalLineNum:t}),a++;else{let n=e,r=a+1;for(;r<o.length;){const e=o[r].trim();if(e.startsWith("#")||e.startsWith("-"))break;if(e.length>0&&(n=n+" "+e),ki.test(e)){r++;break}r++}s.push({text:n,originalLineNum:t}),a=r}else s.push({text:e,originalLineNum:t}),a++}let i=null,c=null,l=0;for(const{text:e,originalLineNum:t}of s){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(!ki.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),a=s.length>0?s[s.length-1]:null;if(!a)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=a[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;c<0||c>1?r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}):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=a&&void 0!==a.index?o.substring(0,a.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),s=0===r.length;let a;if(0===t.length)a=`✓ ${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":""}`),a=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:s,issues:t,summary:a}}function formatValidationIssues(e){const{result:n,verbose:r=!0}=e;if(0===n.issues.length){const e=n.summary.charAt(0),r=n.summary.substring(2);return`${t.green(e)} ${t.dim(r)}`}if(!r)return n.summary;const o=n.issues.filter(e=>"error"===e.severity),s=n.issues.filter(e=>"warning"===e.severity),a=[o.length>0?t.red(n.summary):t.yellow(n.summary),""];if(o.length>0){a.push(t.bold(t.red("Errors:")));for(const e of o){const n=e.line?t.dim(` Line ${e.line}: `):" ";a.push(`${n}${t.red(e.message)}`),e.suggestion&&a.push(t.dim(` → ${e.suggestion}`))}a.push("")}if(s.length>0){a.push(t.bold(t.yellow("Warnings:")));for(const e of s){const n=e.line?t.dim(` Line ${e.line}: `):" ";a.push(`${n}${t.yellow(e.message)}`),e.suggestion&&a.push(t.dim(` → ${e.suggestion}`))}a.push("")}return a.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:n,namespace:o,localBucket:s,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${r.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${r.warning} Package '${n}' already exists locally\n`)),console.log(`Local: ${s.learnings.length} learnings`),console.log(`Remote: ${a} learnings (from ${o})\n`);const i=await d.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 (${s.learnings.length} → ${a} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return d.isCancel(i)&&(d.cancel("Operation cancelled"),process.exit(0)),i}async function promptPushStrategy(e){const{packageName:n,namespace:o,localLearningsCount:s,remoteBucket:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${r.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${r.warning} Package '${n}' already exists in ${o}\n`)),console.log(`Local: ${s} learnings`),console.log(`Remote: ${a.learnings.length} learnings (in ${o})\n`);const i=await d.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} → ${s} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return d.isCancel(i)&&(d.cancel("Operation cancelled"),process.exit(0)),i}async function promptGlobalPushStrategy(e){const{packageName:n,localLearningsCount:o,globalBucket:s}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${r.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${r.warning} Package '${n}' already exists in global storage\n`)),console.log(`Local: ${o} learnings`),console.log(`Global: ${s.learnings.length} learnings\n`);const a=await d.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 (${s.learnings.length} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});return d.isCancel(a)&&(d.cancel("Operation cancelled"),process.exit(0)),a}async function promptGlobalPullStrategy(e){const{packageName:n,localBucket:o,globalLearningsCount:s}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${r.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${r.warning} Package '${n}' already exists locally\n`)),console.log(`Local: ${o.learnings.length} learnings`),console.log(`Global: ${s} learnings\n`);const a=await d.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 (${o.learnings.length} → ${s} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});return d.isCancel(a)&&(d.cancel("Operation cancelled"),process.exit(0)),a}async function promptTypeMismatchStrategy(e){const{packageName:n,namespace:o,localType:s,remoteType:a,localLearningsCount:i,remoteLearningsCount:c}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${r.warning} Non-interactive terminal detected, skipping push`)),"skip";const l=`https://commandcode.ai/${o}/${n}`;console.log(t.yellow(`\n${r.warning} Pushing local project taste to individual package '${n}'\n`)),console.log(`Local: ${n} (${i} learnings)`),console.log(`Remote: ${n} (${c} learnings) in ${o}\n`),console.log(`Review package: ${t.cyan(l)}\n`);const u=await d.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 d.isCancel(u)&&(d.cancel("Operation cancelled"),process.exit(0)),u}async function promptSameTypeStrategy(e){const{packageName:n,namespace:o,localLearningsCount:s,remoteLearningsCount:a}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${r.warning} Non-interactive terminal detected, skipping push`)),"skip";const i=`https://commandcode.ai/${o}/taste/${n}`;console.log(t.yellow(`\n${r.warning} Package '${n}' already exists in ${o}\n`)),console.log(`Local: ${s} learnings`),console.log(`Remote: ${a} learnings\n`),console.log(`Review taste package: ${t.cyan(i)}\n`);const c=await d.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} → ${s} learnings)`}],initialValue:"skip"});return d.isCancel(c)&&(d.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:s=!1}=e,a=new wi,i={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return i.success=!1,i.errors.push({bucket:"all",error:"No taste directory found in project"}),i;const c=await a.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=B.basename(process.cwd()),n=new bi;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 a="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(a=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"===a)return i;await n.writeBuckets({buckets:l,projectName:e,namespace:d,type:"project",isPublic:t?s:r?.isPublic??!1});for(const t of l)i.bucketsPushed.push(t.category),i.filePaths[t.category]=`${d}/${e}`,i.mergeDetails[t.category]={added:t.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 Ei;break;case"remote-project":case"remote-user":u=new bi;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:s})}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:s})}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 wi,s={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},a=__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 Ei;break;case"remote-project":case"remote-user":i=new bi;break;default:return s.success=!1,s.errors.push({bucket:"all",error:`Invalid source: ${n}`}),s}try{c=await i.getAllBuckets()}catch(e){return s.success=!1,s.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),s}if(0===c.length)return s.success=!1,s.errors.push({bucket:"all",error:`No taste packages found in ${a}`}),s;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){s.success=!1;const n=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:e.category,error:`Validation failed for taste package in ${a}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${a} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){s.success=!1;for(const e of t)s.errors.push({bucket:e,error:`Taste package not found in ${a}`});return s}for(const e of l)try{const t=await o.getBucket({category:e.category});let a;if(a=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===a)continue;if("overwrite"===a)await o.writeBucket({bucket:e}),s.bucketsPulled.push(e.category),s.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},s.mergeDetails[e.category]=r.details}else n=e,s.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});s.filePaths[e.category]=i}catch(t){s.success=!1,s.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return s}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new wi,s=new bi,a={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await s.downloadPackage({namespace:t,packageName:n});if(!e)return a.success=!1,a.errors.push({bucket:n,error:"Taste package not found in remote"}),a;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){a.success=!1;const r=formatValidationIssues({result:t,verbose:!0});a.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(a.errors.length>0)return a;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a})}catch(e){a.success=!1,a.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return a}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:s,result:a}=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:s,result:a})}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:s,result:a})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:s}=e;try{const e=await o.getBucket({category:t.category});let a;if(a=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===a)return void s.skipped.push(t.category);if("overwrite"===a)await o.writeBucket({bucket:t}),s.bucketsPulled.push(t.category),s.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},s.mergeDetails[t.category]=r.details}else n=t,s.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=i}catch(e){s.success=!1,s.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:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return a.success=!1,void a.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:s,result:a})}async function pushRemote(e){const t=void 0!==e.isPublic,{namespace:n,packageName:r,overwrite:o=!1,isPublic:s=!1}=e,a=new wi,i=new bi,c={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return c.success=!1,c.errors.push({bucket:r,error:"No taste directory found in project"}),c;try{const e=await a.getBucket({category:r});if(!e)return c.success=!1,c.errors.push({bucket:r,error:`Taste package '${r}' not found in local project`}),c;const l=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!l.valid){c.success=!1;const e=formatValidationIssues({result:l,verbose:!0});return c.errors.push({bucket:r,error:`Validation failed:\n${e}`}),c}if(l.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`);const e=formatValidationIssues({result:l,verbose:!0});console.warn(e+"\n")}const d=await i.downloadPackageToBucket({namespace:n,packageName:r});let u;u=o?"overwrite":d?await promptPushStrategy({packageName:r,namespace:n,localLearningsCount:e.learnings.length,remoteBucket:d}):"merge";const m=t?s:d?.isPublic??!1;if("skip"===u)return c;if("overwrite"===u)await i.writeBucket({bucket:e,namespace:n,isPublic:m}),c.bucketsPushed.push(r),c.overwritten.push(r);else{let t;if(d){const n=mergeLearnings({source:e.learnings,target:d.learnings});t={...e,learnings:n.merged},c.mergeDetails[r]=n.details}else t=e,c.mergeDetails[r]={added:e.learnings.length,updated:0,unchanged:0};await i.writeBucket({bucket:t,namespace:n,isPublic:m}),c.bucketsPushed.push(r)}c.filePaths[r]=`${n}/${r}`}catch(e){c.success=!1,c.errors.push({bucket:r,error:e instanceof Error?e.message:String(e)})}return c}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new wi;break;case"local-global":n=new Ei;break;case"remote-project":case"remote-user":n=new bi;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof Ei||n instanceof bi?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 Ei;break;case"remote-project":case"remote-user":o=new bi;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(!X(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const s=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});X(t)?s.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});X(e)&&s.push({path:e,displayName:"taste.md"});const t=await M.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});X(t)&&s.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===s.length&&r.errors.length>0)return r;if(0===s.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 s){let t=await M.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await M.writeFile(e.path,n,"utf-8"),t=n);const o=validateTasteFile({content:t,filePath:e.displayName}),s=o.issues.filter(e=>"error"===e.severity),a=o.issues.filter(e=>"warning"===e.severity);r.totalErrors+=s.length,r.totalWarnings+=a.length,o.valid||(r.success=!1);const i=formatValidationIssues({result:o});r.filesLinted.push({file:e.displayName,valid:o.valid,errors:s.length,warnings:a.length,formatted:i})}return r}async function open4(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new wi;break;case"local-global":e=new Ei;break;case"remote-project":case"remote-user":e=new bi;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,s=await findCategoryLineNumber({filePath:o,category:t});return await De([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}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 M.readFile(t,"utf-8");if("taste.md"===B.basename(t)&&B.basename(B.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=B.join(K.homedir(),".commandcode","taste",".metadata.json");if(X(e))try{await M.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(open4,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var Si=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 open4(e)}};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 d.select({message:"Select namespace to push to\n",options:r,initialValue:t});return d.isCancel(o)&&(d.cancel("Operation cancelled"),process.exit(0)),o}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new pn({baseUrl:e}),n=await t.get({endpoint:Ge.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}function createTasteCommand(){const e=new c("taste");e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments();const n=new Si;return e.command("push").description("Push taste packages from project to remote or global storage (prompts on conflicts)").argument("[package]","Package name (optional if using --all)").option("--all","Push all packages").option("--remote","Push to remote (default)").option("-g, --global","Push to global storage").addOption(new l("--local","Use local server").hideHelp()).option("--public","Make this package publicly discoverable").option("--overwrite","Overwrite target without prompting (default: interactive merge)").addOption(new l("--staging","Push to staging environment").hideHelp()).action(async(e,r)=>{try{let o;if(r.global||r.remote||(r.remote=!0),r.global&&r.remote&&(console.error(t.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||r.all||(console.error(t.red("Error: Please specify a package name or use --all flag")),console.error(t.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(t.gray(" cmd taste push --all (pushes whole project)")),console.error(t.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&r.all&&(console.error(t.red("Error: Cannot use both package name and --all flag")),process.exit(1)),r.remote)if(r.all)o=await n.push({buckets:[],target:"remote-project",overwrite:r.overwrite,isPublic:r.public});else{let s,a;if(e&&e.includes("/")){const[n,r]=e.split("/");n&&r||(console.error(t.red("Error: Invalid namespace/package format")),console.error(t.gray("Usage: cmd taste push --remote username/packageName")),console.error(t.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),s=n,a=r}else{e||(console.error(t.red("Error: Please specify a package name")),console.error(t.gray("Usage: cmd taste push <namespace>/<package>")),console.error(t.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),a=e;let r;(await n.list({location:"local-project"})).some(e=>e.category===a)||(console.error(t.red(`Error: Taste package '${a}' not found in local project`)),process.exit(1));try{r=await fetchUserNamespaces()}catch(e){throw e}s=r.orgs.length>0?await promptNamespaceSelection(r):r.userName}o=await n.pushRemote({namespace:s,packageName:a,overwrite:r.overwrite,isPublic:r.public})}else{const t="local-global",s=r.all?[]:[e];o=await n.push({buckets:s,target:t,overwrite:r.overwrite})}if(!o.success){for(const e of o.errors){const n=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(t.red(`Error: ${n}`))}process.exit(1)}let s=!1;if(r.all&&o.bucketsPushed.length>0){const e=o.filePaths?.[o.bucketsPushed[0]];if(e)if(r.overwrite)console.log(t.green(`✓ Replaced taste in ${e}`));else if(o.mergeDetails){let n=0,r=0,a=0;for(const e of Object.values(o.mergeDetails))n+=e.added??0,r+=e.updated??0,a+=e.unchanged??0;const i=[];n>0&&i.push(`${n} ${1===n?"learning":"learnings"} added`),r>0&&i.push(`${r} ${1===r?"learning":"learnings"} updated`),a>0&&i.push(`${a} ${1===a?"learning":"learnings"} unchanged`),i.length>0?console.log(t.green(`✓ Pushed taste to ${e} (${i.join(", ")})`)):console.log(t.green(`✓ Pushed taste to ${e}`)),(n>0||r>0)&&a>0&&(s=!0)}else console.log(t.green(`✓ Pushed taste to ${e}`));else console.log(t.green("✓ Pushed taste to remote"))}else if(1===o.bucketsPushed.length){const e=o.bucketsPushed[0],n=o.filePaths?.[e];if(r.overwrite)r.remote&&n?console.log(t.green(`✓ Replaced '${e}' taste package in ${n}`)):(console.log(t.green(`✓ Replaced '${e}' taste package in global`)),n&&console.log(t.gray(` Path: ${n}`)));else if(o.mergeDetails?.[e]){const a=o.mergeDetails[e],i=[];a.added>0&&i.push(`${a.added} ${1===a.added?"learning":"learnings"} added`),a.updated>0&&i.push(`${a.updated} ${1===a.updated?"learning":"learnings"} updated`),a.unchanged>0&&i.push(`${a.unchanged} ${1===a.unchanged?"learning":"learnings"} unchanged`),r.remote&&n?console.log(t.green(`✓ Pushed '${e}' taste package to ${n} (${i.join(", ")})`)):(console.log(t.green(`✓ Pushed '${e}' taste package to global (${i.join(", ")})`)),n&&console.log(t.gray(` Path: ${n}`))),(a.added>0||a.updated>0)&&a.unchanged>0&&(s=!0)}else r.remote&&n?console.log(t.green(`✓ Pushed '${e}' taste package to ${n}`)):(console.log(t.green(`✓ Pushed '${e}' taste package to global`)),n&&console.log(t.gray(` Path: ${n}`)))}else if(o.bucketsPushed.length>0){const e=r.remote?"remote":"global";if(console.log(t.green(`✓ Pushed ${o.bucketsPushed.length} taste packages (${o.bucketsPushed.join(", ")}) to ${e}`)),!r.overwrite&&o.mergeDetails)for(const e of Object.values(o.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){s=!0;break}}s&&console.log(t.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").addOption(new l("--local","Use local server").hideHelp()).option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new l("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,r)=>{try{let o,s;if(r.global||r.remote||(r.remote=!0),r.global&&r.remote&&(console.error(t.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),r.remote&&r.all&&(console.error(t.red("Error: The --all flag is not supported for remote pull")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),r.remote&&!e&&(console.error(t.red("Error: Please provide both namespace and package name")),process.exit(1)),r.remote&&e&&!e.includes("/")&&(console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||r.all||(console.error(t.red("Error: Please specify a package name or use --all flag")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(t.gray(" cmd taste pull <package> -g (from global)")),console.error(t.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&r.all&&(console.error(t.red("Error: Cannot use both package name and --all flag")),process.exit(1)),r.remote){e.includes("/")||(console.error(t.red("Error: Package name must include namespace")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[a,i]=e.split("/");a&&i||(console.error(t.red("Error: Invalid namespace/package format")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),s=a,o=await n.pullRemote({namespace:s,packageName:i,overwrite:r.overwrite})}else{const t="local-global",s=r.all?[]:[e];o=await n.pull({buckets:s,source:t,overwrite:r.overwrite})}const a=r.remote?s?`${s}`:"remote":"global";if(!o.success){for(const e of o.errors){const n=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(t.red(`Error: ${n}`))}process.exit(1)}if(o.skipped&&o.skipped.length>0)for(const e of o.skipped)console.log(t.yellow(`⊘ Skipped '${e}' - kept local version`));let i=!1;if(1===o.bucketsPulled.length){const e=o.bucketsPulled[0],n=o.filePaths?.[e];if(r.overwrite)console.log(t.green(`✓ Replaced '${e}' taste package in project`)),n&&console.log(t.gray(` Saved to: ${n}`));else if(o.mergeDetails?.[e]){const r=o.mergeDetails[e],s=[];r.added>0&&s.push(`${r.added} ${1===r.added?"learning":"learnings"} added`),r.updated>0&&s.push(`${r.updated} ${1===r.updated?"learning":"learnings"} updated`),r.unchanged>0&&s.push(`${r.unchanged} ${1===r.unchanged?"learning":"learnings"} unchanged`),console.log(t.green(`✓ Pulled '${e}' taste package from ${a} (${s.join(", ")})`)),n&&console.log(t.gray(` Saved to: ${n}`)),(r.added>0||r.updated>0)&&r.unchanged>0&&(i=!0)}else console.log(t.green(`✓ Pulled '${e}' taste package from ${a}`)),n&&console.log(t.gray(` Saved to: ${n}`))}else if(o.bucketsPulled.length>0){const e=` (${o.bucketsPulled.join(", ")})`;if(console.log(t.green(`✓ Pulled ${o.bucketsPulled.length} taste packages${e} from ${a}`)),!r.overwrite&&o.mergeDetails)for(const e of Object.values(o.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){i=!0;break}}i&&console.log(t.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("list").option("-g, --global","List global packages").addOption(new l("--local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new l("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let r,o;e.global&&e.remote&&(console.error(t.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(r="remote-project",o="remote"):e.global?(r="local-global",o="global"):(r="local-project",o="project");const s=await n.list({location:r});if(0===s.length)return void console.log(t.yellow(`No taste packages found in ${o}`));let a;console.log(t.hex("#E4CCFF").bold("\nTaste Packages")),a="remote-project"===r?"Stored in your commandcode.ai account":"local-global"===r?"Stored globally in ~/.commandcode/taste":"Stored locally in .commandcode/taste",console.log(t.dim(a+"\n"));let i=0;const c=__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"),l=Math.max(...s.map(c));for(const e of s){i+=e.learningCount;const n=getTimeAgo(e.lastUpdated),r=" ".repeat(l-c(e)+2),o=t.white(e.category),s=e.isPublic?t.green(" [public]"):"",a=e.isPublic&&e.starCount?t.yellow(` ★${e.starCount}`):"",d=e.downloadCount?t.gray(` ↓${e.downloadCount}`):"";console.log(` ${o}${s}${a}${d}${r}${t.dim.gray(`(${e.learningCount} learnings, updated ${n})`)}`)}console.log(t.dim(`\nTotal: ${s.length} packages, ${i} learnings\n`))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.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,r)=>{try{e||r.all||(console.error(t.red("Error: Please specify a package name or use --all flag")),console.error(t.gray("Usage: cmd taste lint <package>")),console.error(t.gray(" cmd taste lint --all")),process.exit(1)),e&&r.all&&(console.error(t.red("Error: Cannot use both package name and --all flag")),process.exit(1));const o=await n.lint({packages:e?[e]:[],target:r.global?"local-global":"local-project"});if(o.errors.length>0){for(const e of o.errors)console.error(t.red(`Error: ${e.error}`));process.exit(1)}for(const e of o.filesLinted)console.log(e.formatted);if(o.filesLinted.length>1)if(console.log(""),0===o.totalErrors&&0===o.totalWarnings)console.log(t.green(`✓ All ${o.filesLinted.length} taste files are valid`));else{const e=[];o.totalErrors>0&&e.push(t.red(`${o.totalErrors} error${o.totalErrors>1?"s":""}`)),o.totalWarnings>0&&e.push(t.yellow(`${o.totalWarnings} warning${o.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${o.filesLinted.length} files`)}o.success||process.exit(1)}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,r)=>{try{const o=r.global?"local-global":"local-project",s=await n.open({package:e,target:o});s.success||(console.error(t.red(s.error)),process.exit(1)),console.log(t.green(`✓ Opened '${e}' taste package from ${r.global?"global":"project"}`))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}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 formatVersion(e,t,n=!1){const r=n?T.bold(T.green(t)):T.white(t);return`${T.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${T.bold(T.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(T.dim(`Run ${T.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(T.dim("Try updating manually:")),console.log(T.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(T.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=de("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${T.green(r.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${T.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=de("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${r.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),showManualUpdateHint(t.latestVersion),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${T.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(promptNamespaceSelection,"promptNamespaceSelection"),__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(checkAction,"checkAction"),__name(performUpdateAction,"performUpdateAction"),__name(updateAction,"updateAction");var Ci=new c("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction),vi=__name((e,t)=>`${r.info} ${e}: ${T.cyan(t)}`,"formatInfoLine"),Ti=__name(e=>T.bold(`${e}:`),"formatSectionHeader"),Ai=__name(e=>T.red(e),"formatError"),Pi=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),xi=__name(e=>["",Ti("User Information"),vi("Name",e.name),vi("Email",e.email),vi("Username",e.userName)],"buildUserOutput"),Ii=__name(e=>["",Ti("Organization"),vi("Name",e.name),vi("Login",e.login)],"buildOrgOutput"),$i=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),Di=__name((e,t)=>{$i(xi(e)),t&&$i(Ii(t)),console.log("")},"displayUserInfo"),Fi=__name(e=>null!==e&&e.length>0,"validateApiKey"),Ri=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=de("Fetching user information...").start();try{const t=await getAuthKey();Fi(t)||(e.fail(Ai('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();Ri(n)||(e.fail(Ai("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),Di(n.user,n.org)}catch(t){e.fail(Ai(`Error: ${Pi(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var Mi=new c("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),await preRun();var Li=createProgram();Li.action(interactiveModeAction),Li.addCommand(oi),Li.addCommand(fi),Li.addCommand(Mi),Li.addCommand(Ci),Li.addCommand(createTasteCommand()),Li.addCommand(yi),Li.addCommand($t),Li.addCommand(Lt),Li.addCommand(Bt),setupCommanderHooks(Li),Li.parse();
2
+ import"dotenv/config";import e from"dedent";import t from"chalk";import n from"log-symbols";import r from"@opentelemetry/sdk-node";import o from"@opentelemetry/exporter-trace-otlp-http";import s from"@opentelemetry/resources";import a from"@opentelemetry/semantic-conventions";import i from"@opentelemetry/sdk-trace-node";import*as c from"fs";import l,{existsSync as d,readFileSync as u,promises as m,constants as g,readdirSync as p,statSync as h,createReadStream as f}from"fs";import*as y from"path";import w,{relative as E,dirname as b,join as k,isAbsolute as S,resolve as C}from"path";import*as v from"os";import T from"os";import A,{z as P}from"zod";import*as x from"fs/promises";import I,{mkdir as $,writeFile as D}from"fs/promises";import{execSync as F,exec as R,spawn as M}from"child_process";import*as O from"crypto";import L from"crypto";import N,{useState as _,useRef as U,useEffect as j,useCallback as B,useMemo as W}from"react";import{Box as z,Text as H,Static as G,render as q,useInput as V,useApp as K,useStdout as J}from"ink";import Y from"picocolors";import Q from"strip-ansi";import Z from"open";import X from"sharp";import{fileURLToPath as ee,pathToFileURL as te}from"url";import{trace as ne,SpanStatusCode as re,context as oe}from"@opentelemetry/api";import{v4 as se}from"uuid";import ae,{mainSymbols as ie}from"figures";import ce from"readline/promises";import{Command as le,Option as de}from"commander";import*as ue from"@clack/prompts";import{cancel as me,select as ge,isCancel as pe,note as he,confirm as fe,password as ye}from"@clack/prompts";import we from"ink-spinner";import*as Ee from"http";import*as be from"net";import ke from"ora";import Se from"@crosscopy/clipboard";import Ce from"gray-matter";import{minimatch as ve}from"minimatch";import{glob as Te}from"glob";import{quote as Ae}from"shell-quote";import{MessageStream as Pe}from"@anthropic-ai/sdk/lib/MessageStream.mjs";import xe from"@sindresorhus/slugify";import{EventEmitter as Ie}from"events";import $e from"strip-json-comments";import*as De from"readline";import Fe from"ink-select-input";import Re from"ignore";import Me from"ink-gradient";import{Marked as Oe}from"marked";import Le from"marked-terminal";import*as Ne from"diff";import{promisify as _e}from"util";import Ue from"semver";import je from"open-editor";import Be from"ink-text-input";import*as We from"process";var ze=Object.defineProperty,__name=(e,t)=>ze(e,"name",{value:t,configurable:!0}),He=process.argv.includes("-d")||process.argv.includes("--debug");He&&(process.env.DEBUG="true"),He||(process.removeAllListeners("warning"),process.on("warning",()=>{}));var Ge="command-code-cli",qe=["apikey","api_key","api-key","token","secret","authorization","auth","password","passwd","credential","auth_key","authkey","access_token","access-token","refresh_token","refresh-token","client_secret","clientsecret","private_key","privatekey","bearer","key"],Ve=["content","body"],Ke="--co",Je="--xco",Ye=`x-${Ke.replace("--","")}-flag`,Qe="x-oauth-token",Ze="x-project-slug",Xe="x-taste-learning",et={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"}}}},tt={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(tt.ALPHA.TASTE),Object.values(tt.BETA.TASTE_PACKAGES),et.ALPHA.GENERATE,et.ALPHA.AGENT.GENERATE,et.ALPHA.WHOAMI,et.ALPHA.NAMESPACES,et.ALPHA.SHARE.CREATE,et.ALPHA.SHARE.DELETE,et.ALPHA.SHARE.APPEND,et.ALPHA.DEVREL_THREAD.CREATE,et.ALPHA.DEVREL_THREAD.DELETE,et.ALPHA.DEVREL_THREAD.UPDATE,et.ALPHA.TASTE.LEARN,et.ALPHA.TASTE.DELETE,et.ALPHA.TASTE.GET,et.ALPHA.TASTE.UPDATE,Object.values(et.BETA.TASTE.PACKAGES),Object.values(tt.INTERNAL.ORGS),Object.values(tt.INTERNAL.USER),Object.values(tt.INTERNAL.TASTE.PACKAGES);var nt={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"local"===e?"http://localhost:3000/settings/api":"staging"===e?"https://staging.commandcode.ai/settings/api":"https://commandcode.ai/settings/api"}Object.values(nt.INTERNAL.PROFILE),__name(getStudioAuthUrl,"getStudioAuthUrl");var rt="anthropic";A.enum(["owner","admin","member"]);var ot="learn-taste",st={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:""}},at=st.SONNET_4_5.id;new Set([].map(e=>e.toLowerCase()));var it,ct=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],lt=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv"),dt=__name(()=>{const e=lt();return"local"===e?"--local":"staging"===e?"--staging":""},"getApiEnvFlag");function getAuthDir(){return w.join(T.homedir(),".commandcode")}function getAuthFile(e){const t=e??lt(),n="local"===t?"auth.local.json":"staging"===t?"auth.staging.json":"auth.json";return w.join(getAuthDir(),n)}function getConfigFile(e){const t=e??lt(),n="local"===t?"config.local.json":"staging"===t?"config.staging.json":"config.json";return w.join(getAuthDir(),n)}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 l.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 F("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return F("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){try{const e=F("git branch -r",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]});return e.includes("origin/main")?"main":e.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=F("git status --porcelain",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();if(!e)return"Working tree clean";const t=e.split("\n"),n=t.filter(e=>e.startsWith(" M")).length,r=t.filter(e=>e.startsWith("A ")).length,o=t.filter(e=>e.startsWith(" D")).length,s=t.filter(e=>e.startsWith("??")).length,a=[];return n>0&&a.push(`M ${n}`),r>0&&a.push(`A ${r}`),o>0&&a.push(`D ${o}`),s>0&&a.push(`?? ${s}`),a.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=F("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository();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("ghostty"===t)return{name:"Ghostty",type:"ghostty",details:{termProgram:t,termProgramVersion:e.TERM_PROGRAM_VERSION}}}if(e.WT_SESSION||e.WT_PROFILE_ID)return{name:"Windows Terminal",type:"windows-terminal",details:{wtSession:e.WT_SESSION,wtProfileId:e.WT_PROFILE_ID}};if(e.ALACRITTY_SOCKET||e.ALACRITTY_WINDOW_ID)return{name:"Alacritty",type:"alacritty",details:{alacrittySocket:e.ALACRITTY_SOCKET,alacrittyWindowId:e.ALACRITTY_WINDOW_ID}};if(e.KITTY_WINDOW_ID||e.KITTY_PID)return{name:"Kitty",type:"kitty",details:{kittyWindowId:e.KITTY_WINDOW_ID,kittyPid:e.KITTY_PID}};if(e.GNOME_TERMINAL_SERVICE||e.VTE_VERSION)return{name:"GNOME Terminal",type:"gnome-terminal",details:{gnomeTerminalService:e.GNOME_TERMINAL_SERVICE,vteVersion:e.VTE_VERSION}};if(e.KONSOLE_VERSION||e.KONSOLE_PROFILE_NAME)return{name:"Konsole",type:"konsole",details:{konsoleVersion:e.KONSOLE_VERSION,konsoleProfile:e.KONSOLE_PROFILE_NAME}};if(e.TMUX)return{name:"tmux",type:"tmux",details:{tmux:e.TMUX,tmuxPane:e.TMUX_PANE}};if(e.ConEmuPID||e.ConEmuBuild)return{name:"ConEmu",type:"conemu",details:{conEmuPid:e.ConEmuPID,conEmuBuild:e.ConEmuBuild}};if(e.SSH_CLIENT||e.SSH_TTY)return{name:"SSH",type:"ssh",details:{sshClient:e.SSH_CLIENT,sshTty:e.SSH_TTY}};if(e.CI){const t=e.GITHUB_ACTIONS?"GitHub Actions":e.GITLAB_CI?"GitLab CI":e.JENKINS_URL?"Jenkins":e.CIRCLECI?"CircleCI":"Unknown CI";return{name:t,type:"ci",details:{ci:e.CI,ciName:t}}}const t=e.TERM||"unknown";return{name:`Unknown Terminal (${t})`,type:"unknown",details:{term:t,colorterm:e.COLORTERM,shell:e.SHELL}}}function getIsTerminalIterm2(){return"iTerm2"===detectTerminal().name}__name(getAuthDir,"getAuthDir"),__name(getAuthFile,"getAuthFile"),__name(getConfigFile,"getConfigFile"),__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"),(e=>{e.OAuth=P.object({type:P.literal("oauth"),refresh:P.string(),access:P.string(),expires:P.number()}),e.ApiKey=P.object({type:P.literal("api"),key:P.string()}),e.Info=P.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const t=__name(()=>w.join(T.homedir(),".commandcode"),"getAuthDir"),n=__name(()=>{const e=lt(),n="local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json";return w.join(t(),n)},"getAuthFile");async function get(e){try{const t=await I.readFile(n(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,r){const o=t(),s=n();await I.mkdir(o,{recursive:!0});let a={};try{const e=await I.readFile(s,"utf-8");a=JSON.parse(e)}catch{}a[e]=r,await I.writeFile(s,JSON.stringify(a,null,2)),await I.chmod(s,384)}async function remove(e){const t=n();try{const n=await I.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await I.unlink(t):(await I.writeFile(t,JSON.stringify(r,null,2)),await I.chmod(t,384))}catch{}}async function list2(){try{const e=await I.readFile(n(),"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")})(it||(it={}));var ut,mt="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/settings/billing";(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 L.randomBytes(32).toString("base64url")}function generateCodeChallenge(e){return L.createHash("sha256").update(e).digest("base64url")}function generateState(){return L.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,s){const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:t,code:e,redirect_uri:r,code_verifier:o,state:s})});if(!a.ok){const e=await a.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:zt.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const i=await a.json();await it.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 it.get("anthropic");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return e.access;try{const r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t,refresh_token:e.refresh})});if(!r.ok)return trackError({error:sanitizeErrorForTelemetry({error:new Error("OAuth token refresh failed"),label:"token_refresh_failed"}),context:{component:zt.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}}),void await it.remove("anthropic");const o=await r.json();return await it.set("anthropic",{type:"oauth",refresh:o.refresh_token,access:o.access_token,expires:Date.now()+1e3*o.expires_in}),o.access_token}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:zt.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}}),void await it.remove("anthropic")}}}async function getValidAccessToken(){const e=await it.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")})(ut||(ut={}));var gt=/\s|[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function isWordBoundary(e){return!e||0===e.length||gt.test(e)}function findPreviousWordBoundary(e,t){if(!e||t<=0)return 0;let n=Math.min(t,e.length);for(;n>0&&isWordBoundary(e[n-1]||"");)n--;for(;n>0&&!isWordBoundary(e[n-1]||"");)n--;return n}function findNextWordBoundary(e,t){if(!e)return 0;if(t>=e.length)return e.length;let n=Math.max(0,t);for(;n<e.length&&isWordBoundary(e[n]||"");)n++;for(;n<e.length&&!isWordBoundary(e[n]||"");)n++;return n}function deleteWordBackwards(e,t){if(!e||t<=0)return{text:e||"",cursor:0};const n=findPreviousWordBoundary(e,t);return{text:e.slice(0,n)+e.slice(t),cursor:n}}function clampCursor(e,t){return Math.max(0,Math.min(e,t))}function findLineStart(e,t){if(!e||t<=0)return 0;for(let n=Math.min(t,e.length)-1;n>=0;n--)if("\n"===e[n])return n+1;return 0}function findLineEnd(e,t){if(!e)return 0;if(t>=e.length)return e.length;for(let n=Math.max(0,t);n<e.length;n++)if("\n"===e[n])return n;return e.length}function moveCursorUp(e,t){if(!e)return 0;const n=findLineStart(e,t);if(0===n)return t;const r=t-n,o=n-1,s=findLineStart(e,o),a=o-s;return s+Math.min(r,a)}function moveCursorDown(e,t){if(!e)return 0;const n=findLineStart(e,t),r=findLineEnd(e,t);if(r===e.length)return t;const o=t-n,s=r+1,a=findLineEnd(e,s)-s;return s+Math.min(o,a)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}__name(isWordBoundary,"isWordBoundary"),__name(findPreviousWordBoundary,"findPreviousWordBoundary"),__name(findNextWordBoundary,"findNextWordBoundary"),__name(deleteWordBackwards,"deleteWordBackwards"),__name(clampCursor,"clampCursor"),__name(findLineStart,"findLineStart"),__name(findLineEnd,"findLineEnd"),__name(moveCursorUp,"moveCursorUp"),__name(moveCursorDown,"moveCursorDown"),__name(insertTextAt,"insertTextAt"),__name(deleteCharBefore,"deleteCharBefore"),__name(deleteCharAt,"deleteCharAt");var pt=new Set(["","b","","",""]),ht=new Set(["","f","","",""]),ft=new Set(["","[1~","[7~","OH"]),yt=new Set(["","[4~","[8~","OF"]),wt=new Set(["[3~"]),Et=new Set(["",""]),bt=/^\x1b\[1;[359]D$/,kt=/^\x1b\[1;[359]C$/;function isWordLeftSequence(e){return!!pt.has(e)||!!bt.test(e)}function isWordRightSequence(e){return!!ht.has(e)||!!kt.test(e)}function isHomeSequence(e){return ft.has(e)}function isEndSequence(e){return yt.has(e)}function isForwardDeleteSequence(e){return wt.has(e)}function isDeleteWordSequence(e){return Et.has(e)}function isCtrlA(e){return 1===e.length&&1===e.charCodeAt(0)}function isCtrlE(e){return 1===e.length&&5===e.charCodeAt(0)}function isCtrlK(e){return 1===e.length&&11===e.charCodeAt(0)}function isCtrlU(e){return 1===e.length&&21===e.charCodeAt(0)}function processWordLeft(e,t){return{value:e,cursor:findPreviousWordBoundary(e,t),handled:!0}}function processWordRight(e,t){return{value:e,cursor:findNextWordBoundary(e,t),handled:!0}}function processLineStart(e,t){return{value:e,cursor:findLineStart(e,t),handled:!0}}function processLineEnd(e,t){return{value:e,cursor:findLineEnd(e,t),handled:!0}}function processDeleteWord(e,t){const n=deleteWordBackwards(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processDeleteToEnd(e,t){const n=findLineEnd(e,t);return{value:e.slice(0,t)+e.slice(n),cursor:t,handled:!0}}function processDeleteToStart(e,t){const n=findLineStart(e,t);return{value:e.slice(0,n)+e.slice(t),cursor:n,handled:!0}}function processForwardDelete(e,t){const n=deleteCharAt(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processBackspace(e,t){const n=deleteCharBefore(e,t);return{value:n.text,cursor:n.cursor,handled:!0}}function processCursorLeft(e,t,n){return n?t<=0?{value:e,cursor:t,handled:!0}:{value:e,cursor:t-1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorRight(e,t,n){return n?t>=e.length?{value:e,cursor:t,handled:!0}:{value:e,cursor:t+1,handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorUp(e,t,n){return n?{value:e,cursor:moveCursorUp(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCursorDown(e,t,n){return n?{value:e,cursor:moveCursorDown(e,t),handled:!0}:{value:e,cursor:t,handled:!0}}function processCharacterInput(e,t,n){const r=n.replace(/[\x00-\x1F\x7F]|\x1b.*/g,"");if(0===r.length)return{value:e,cursor:t,handled:!1};const o=insertTextAt(e,t,r);return{value:o.text,cursor:o.cursor,handled:!0}}function processRawInput(e,t,n){return isWordLeftSequence(e)?processWordLeft(t,n):isWordRightSequence(e)?processWordRight(t,n):isHomeSequence(e)?processLineStart(t,n):isEndSequence(e)?processLineEnd(t,n):isCtrlA(e)?processLineStart(t,n):isCtrlE(e)?processLineEnd(t,n):isDeleteWordSequence(e)?processDeleteWord(t,n):isCtrlK(e)?processDeleteToEnd(t,n):isCtrlU(e)?processDeleteToStart(t,n):isForwardDeleteSequence(e)?processForwardDelete(t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(processWordLeft,"processWordLeft"),__name(processWordRight,"processWordRight"),__name(processLineStart,"processLineStart"),__name(processLineEnd,"processLineEnd"),__name(processDeleteWord,"processDeleteWord"),__name(processDeleteToEnd,"processDeleteToEnd"),__name(processDeleteToStart,"processDeleteToStart"),__name(processForwardDelete,"processForwardDelete"),__name(processBackspace,"processBackspace"),__name(processCursorLeft,"processCursorLeft"),__name(processCursorRight,"processCursorRight"),__name(processCursorUp,"processCursorUp"),__name(processCursorDown,"processCursorDown"),__name(processCharacterInput,"processCharacterInput"),__name(processRawInput,"processRawInput"),__name(isIgnoredKey,"isIgnoredKey"),__name(processInkInput,"processInkInput");var St=!1,Ct=[],vt=null;function startEarlyInputCapture(){St||(St=!0,Ct=[],vt=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&Ct.push(t)},"earlyInputHandler"),process.stdin.on("data",vt))}function stopEarlyInputCapture(){St&&vt&&(process.stdin.off("data",vt),vt=null,St=!1)}function consumeBufferedInput(){const e=Ct.join("");return Ct=[],e}function hasBufferedInput(){return Ct.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}function useCursorState({value:e,focus:t,showCursor:n}){const[r,o]=_((e||"").length),s=U(r);j(()=>{s.current=r},[r]),j(()=>{if(!t)return;if(!n)return;const s=(e||"").length;r>s&&o(s)},[e,t,n,r]);const a=B(e=>{o(e),s.current=e},[]);return{cursor:r,setCursor:a,cursorRef:s}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o}){const s=U(!1);j(()=>{if(!e)return;const a=process.stdin,i=__name(e=>{const s=processRawInput(e.toString(),t.current,n.current);if(!s.handled)return;o(!0);const a=clampCursor(s.cursor,s.value.length);r(s.value,a),setTimeout(()=>o(!1),0)},"handleRawInput");if(a.on("data",i),!s.current&&hasBufferedInput()){s.current=!0;const e=consumeBufferedInput();e&&i(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",i)}},[e,t,n,r,o])}function useInkInputHandler({focus:e,showCursor:t,value:n,cursor:r,isHandledByStdin:o,onUpdate:s,onSubmit:a}){V((e,i)=>{if(o())return;if(isIgnoredKey(e,i))return;if(i.return)return void a?.(n);const c=processInkInput(e,i,n,r,t);if(!c.handled)return;const l=clampCursor(c.cursor,c.value.length);s(c.value,l)},{isActive:e})}function useSyncedRef(e){const t=U(e);return j(()=>{t.current=e},[e]),t}function renderPlaceholder(e,n){return n?0===e.length?t.inverse(" "):t.inverse(e[0])+t.grey(e.slice(1)):t.grey(e)}function renderValue(e,n,r){if(!r)return e;if(0===e.length)return t.inverse(" ");let o="";for(let r=0;r<e.length;r++)r===n?"\n"===e[r]?o+=t.inverse(" ")+"\n":o+=t.inverse(e[r]):o+=e[r];return n===e.length&&(o+=t.inverse(" ")),o}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(Q(e).length<=s)return e;const a=e.split(/(\s+)/);let i="",c=0,l=!0;for(const e of a){const t=Q(e).length;c+t>(l?s:o)&&c>0&&(i+="\n"+r,c=n,l=!1),i+=e,c+=t}return i}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}function createStdinUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t.current&&(n.current(r),t.current=r)}}function createInkUpdateHandler(e,t,n){return(r,o)=>{e(o),r!==t&&n(r)}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:a,onCursorChange:i,prefix:c="",prefixColor:l}){const d=U(!1),u=useSyncedRef(e),m=useSyncedRef(s),{cursor:g,setCursor:p,cursorRef:h}=useCursorState({value:e,focus:n,showCursor:o});N.useEffect(()=>{i?.(g)},[g,i]);const f=B(createStdinUpdateHandler(p,u,m),[p,u,m]),y=B(()=>createInkUpdateHandler(p,e,s),[p,e,s])(),w=B(e=>{d.current=e},[]),E=B(()=>d.current,[]);useRawStdinHandler({focus:n,valueRef:u,cursorRef:h,onUpdate:f,setHandled:w}),useInkInputHandler({focus:n,showCursor:o,value:e,cursor:g,isHandledByStdin:E,onUpdate:y,onSubmit:a});const{stdout:b}=J(),k=b?.columns??80,S=getMaskedValue(e,r),C=wrapWithIndent(__name(()=>{if(!c)return"";if(!l)return c;const e={white:Y.white,green:Y.green,red:Y.red,blue:Y.blue,yellow:Y.yellow,cyan:Y.cyan,magenta:Y.magenta,gray:Y.gray,grey:Y.gray}[l];return e?e(c):c},"getColoredPrefix")()+getDisplayValue(S,t,g,o,n),k,c?.length??0);return N.createElement(H,{wrap:"wrap"},C)}async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=X(n),s=await o.metadata();if(!s.width||!s.height)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=1200;let i,c,{width:l,height:d}=s;(l>a||d>a)&&(l>d?(d=Math.round(d*a/l),l=a):(l=Math.round(l*a/d),d=a)),t.includes("png")&&s.hasAlpha?(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).png({quality:95,compressionLevel:4}).toBuffer(),c="image/png"):(i=await o.resize(l,d,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:95,progressive:!0}).toBuffer(),c="image/jpeg");const u=i.length;return{compressedBase64:i.toString("base64"),mediaType:c,originalSizeBytes:r,compressedSizeBytes:u,compressionRatio:r/u}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}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,o,s=e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"");if(s=s.replace(/\x1B\[201~/g,"").replace(/\[201~/g,""),t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){r=e.slice(0,t.index);const s=e.slice(t.index+t[0].length);if(n){const e=s.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(o=s.slice(0,e.index))}else o=s}}return{isPasteStart:t,isPasteEnd:n,cleanedContent:s,textBeforePaste:r,pastedContent:o}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip"),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue"),__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput"),__name(compressImageForSharing,"compressImageForSharing"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode");var Tt=y.join(v.homedir(),".commandcode","logs"),At=y.join(Tt,"command.log"),Pt={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",default:"-"};function getIcon(e){if(Pt[e])return Pt[e];const t=e.split(":")[0];return Pt[t]?Pt[t]:Pt.default}function formatTime(e){return`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`}function parseMessage(e){const t=e.match(/^\[([^\]]+)\]\s*(.*)/);return t?{category:t[1],text:t[2]}:{category:"",text:e}}__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage");var xt=!1;function showStartup(){if(!xt){xt=!0;try{c.mkdirSync(Tt,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${At}\n════════════════════════════════════════════════════════════════\n\n`;c.appendFileSync(At,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${Pt.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",c.appendFileSync(At,s,"utf-8")}catch{}}}function dlogSection(e){if("true"===process.env.DEBUG){showStartup();try{const t=`\n──── ${e} ${"─".repeat(Math.max(0,50-e.length))}\n`;c.appendFileSync(At,t,"utf-8")}catch{}}}async function loadUserConfig(){try{const e=getConfigFile();return parseJSON(await x.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();c.writeFileSync(t,JSON.stringify(e,null,2)),c.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})}__name(showStartup,"showStartup"),"true"===process.env.DEBUG&&showStartup(),__name(dlog,"dlog"),__name(dlogSection,"dlogSection"),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),__name(isTasteLearningEnabled,"isTasteLearningEnabled"),__name(setTasteLearning,"setTasteLearning");var It=null;async function isOAuthEnforced(){if(null!==It)return It;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),It=!1,!1;if(isInternalTeamFlagPresent())return dlog("[Auth] OAuth enabled via --co flag"),await updateUserConfig({provider:"anthropic",forceOAuth:!0}),It=!0,!0;const e=await loadUserConfig();return(It=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),It}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=getConfigFile();return(parseJSON(c.readFileSync(e,"utf-8"))||{}).model??at}catch{return at}}async function setSelectedModel(e){const{model:t}=e;await updateUserConfig({model:t})}__name(isOAuthEnforced,"isOAuthEnforced"),__name(validateOAuthToken,"validateOAuthToken"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel");var $t=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=_(""),[s,a]=_(null),[i,c]=_(!1),[l,d]=_(null),[u,m]=_(!0),[g,p]=_(!1),[h,f]=_(!1);j(()=>{const{url:e,verifier:t,state:n}=ut.createAuthorizationUrl();a({url:e,verifier:t,state:n})},[]);const y=B(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||h){if(!h||t.isPasteEnd){if(h&&t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}o(e)}}else if(f(!0),t.isPasteEnd){f(!1);const e=await detectClipboardText();if(e){const t=e.split("#")[0].trim();return void o(t)}if(t.cleanedContent){const e=t.cleanedContent.split("#")[0].trim();o(e)}return}},[h]);V((e,n)=>{if(n.escape&&t(),u&&!g)if("y"!==e&&"Y"!==e)"n"!==e&&"N"!==e||t();else{if(!s)return;Z(s.url).then(()=>{p(!0),m(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),p(!0),m(!1)})}});const w=__name(async()=>{if(r.trim()&&s&&!i){c(!0),d(null);try{const t=r.split("#")[0].trim();await ut.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),c(!1),n&&n(t)}}},"handleSubmit");return u&&!g?N.createElement(z,{flexDirection:"column"},N.createElement(z,{marginBottom:1},N.createElement(H,{bold:!0,color:"cyan"},"Anthropic Authentication")),N.createElement(z,{marginBottom:1},N.createElement(H,null,"Open the Anthropic auth page?",N.createElement(H,{dimColor:!0}," (Y/n)")))):N.createElement(z,{flexDirection:"column"},N.createElement(z,{marginBottom:1},N.createElement(H,{bold:!0,color:"cyan"},"Anthropic Authentication")),N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"A browser window should have opened with the Anthropic login page.")),N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"After authorizing, copy the code and paste it below:")),l&&N.createElement(z,{marginBottom:1},N.createElement(H,{color:"red"},"Error: ",l)),N.createElement(z,null,N.createElement(H,null,"Authorization code: "),N.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:y,onSubmit:w,placeholder:"Paste code here..."})),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth"),Dt={"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:$t,checkAuth:__name(async()=>!!await ut.getValidAccessToken(),"checkAuth")}};function getProviderDisplayName(e){if(!e)return"None";const t=Dt[e];return t?.displayName||e}function getProviderConfig(e){return Dt[e]}function isInternalTeamFlagPresent(){return process.argv.includes(Ke)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(Je)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON(c.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(Dt).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}function isInternalTeamDisableOAuthFlagPresent(){return process.argv.includes(Je)}function formatDate(e=new Date){return e.toISOString().split("T")[0]}function parseJSON(e){try{return JSON.parse(e)}catch{return null}}async function getConfiguredProvider(){try{const e=getConfigFile(),t=await I.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();return isInternalTeamDisableOAuthFlagPresent()?(await updateUserConfig({provider:"command-code",forceOAuth:!1}),"command-code"):s||o?(await updateUserConfig({provider:"anthropic",forceOAuth:!0}),"anthropic"):r}catch{return null}}function getIsExpandToolShortcut(e,t){const n=getIsTerminalIterm2();return!(!n||!e.shift||"O"!==t)||!(n||!e.ctrl||"o"!==t)}function formatTime2(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function formatTokens(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function isLocalDevelopmentBuild(){try{const e=process.argv[1];if(!e)return!1;if(e.includes("/usr/local/bin/dmd"))return!0;const t=l.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":lt()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return"xaat-fde9e569-4a3c-4994-aa0d-7a632332d220";case"local":return"xaat-add69148-8f73-4833-921d-bc843285c95f";default:return"xaat-818bfed7-bc54-45bc-8bfa-d1198174064a"}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON(c.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}function getPackageJson(){const e=import.meta.url,t=ee(e),n=b(t);return JSON.parse(u(k(n,"./../package.json"),"utf8"))}__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalTeamFlagPresent,"isInternalTeamFlagPresent"),__name(isInternalTeamDisableFlagPresent,"isInternalTeamDisableFlagPresent"),__name(isInternalTeamFlagEnforced,"isInternalTeamFlagEnforced"),__name(getProviderOptions,"getProviderOptions"),__name(isInternalTeamDisableOAuthFlagPresent,"isInternalTeamDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut"),__name(formatTime2,"formatTime"),__name(formatTokens,"formatTokens"),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild"),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken"),__name(getPackageJson,"getPackageJson");var{NodeSDK:Ft}=r,{OTLPTraceExporter:Rt}=o,{resourceFromAttributes:Mt}=s,{ATTR_SERVICE_NAME:Ot,ATTR_SERVICE_VERSION:Lt}=a,{SimpleSpanProcessor:Nt}=i;function createAxiomExporter(){return new Rt({url:"https://api.axiom.co/v1/traces",headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":"command_code_cli_tracing"}})}function createServiceResource(){const e=getPackageJson(),t=process.execPath.split("/").pop()||"unknown";return Mt({[Ot]:Ge,[Lt]:e.version,"process.executable.name":t,"process.runtime.name":"node","process.runtime.version":process.version,"process.pid":process.pid})}function createTelemetrySDK(){const e=createAxiomExporter(),t=createServiceResource();return new Ft({resource:t,spanProcessors:[new Nt(e)],autoDetectResources:!1})}__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK");var _t=null,Ut=null,jt=null,Bt=null,Wt={};function generateSessionId(){return`sess_${se().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return O.createHash("sha256").update(e).digest("hex").substring(0,12)}function getCliVersion(){try{const e=getPackageJson();if("string"==typeof e.version&&""!==e.version.trim())return e.version}catch{}return"unknown"}function buildSessionAttributes(e){const{sessionId:t,projectPath:n,gitBranch:r,cliVersion:o}=e;return{"session.id":t,"session.start_time":(new Date).toISOString(),"session.project_hash":hashPath(n),"session.branch_hash":r?hashPath(r):"unknown","session.cli_version":o,"session.platform":`${v.platform()}-${v.arch()}`,"session.node_version":process.version}}function startSession(){Wt={},Ut=null,jt=null,_t=generateSessionId(),Bt=Date.now();try{const e=ne.getTracer(Ge),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:_t,projectPath:n,gitBranch:r,cliVersion:t});Ut=e.startSpan("session:cli",{attributes:o}),jt=Ut.spanContext(),Ut.end()}catch{Ut=null,jt=null}return _t}function getTraceId(){return jt?jt.traceId:null}function getSessionContext(){return jt?ne.setSpanContext(oe.active(),jt):oe.active()}function endSession(e={}){const{status:t="success"}=e;if(jt&&Bt){const e=ne.getTracer(Ge),n=Date.now()-Bt,r=ne.setSpanContext(oe.active(),jt),o=e.startSpan("session:end",{attributes:{"session.id":_t||"unknown","session.duration_ms":n,"session.end_time":(new Date).toISOString(),"session.status":t,...Wt}},r);"error"===t?o.setStatus({code:re.ERROR}):o.setStatus({code:re.OK}),o.end()}Ut=null,jt=null,_t=null,Bt=null,Wt={}}function setSpanStatus(e,t){"error"===t?e.setStatus({code:re.ERROR}):e.setStatus({code:re.OK})}function createSpan(e){const{name:t,attributes:n}=e,r=ne.getTracer(Ge),o=getSessionContext();return r.startSpan(t,{attributes:n},o)}function endSpan(e){const{span:t,status:n="success"}=e;setSpanStatus(t,n),t.end()}function recordError(e){const{span:t,error:n,additionalAttributes:r}=e;if(t.recordException(n),t.setStatus({code:re.ERROR,message:n.message}),t.setAttribute("error.type",n.name),t.setAttribute("error.message",n.message),n.stack&&t.setAttribute("error.stack",n.stack),r)for(const[e,n]of Object.entries(r))void 0!==n&&t.setAttribute(e,n)}function isSecretKey(e){const t=e.toLowerCase();return qe.some(e=>t.includes(e))}function isContentKey(e){const t=e.toLowerCase();return Ve.some(e=>t.includes(e))}function safeStringify(e){try{return JSON.stringify(e)}catch{return"[Unserializable]"}}function truncateString(e){return e.length<=200?e:`${e.substring(0,197)}...`}function normalizeError(e){return e instanceof Error?e:new Error(String(e))}function sanitizeErrorForTelemetry(e){const{error:t,label:n="error"}=e,r=new Error(n);return r.name=t.name||"Error",r}function sanitizeValue(e){const{value:t,key:n,visited:r}=e;if(isContentKey(n)||isSecretKey(n))return"[redacted]";if(null==t)return t;if("string"==typeof t)return t.length>200?truncateString(t):t;if("number"==typeof t||"boolean"==typeof t)return t;if("object"==typeof t){if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map((e,t)=>sanitizeValue({value:e,key:String(t),visited:r}));const e={};for(const[n,o]of Object.entries(t))e[n]=sanitizeValue({value:o,key:n,visited:r});return e}return"[Unsupported]"}function sanitizeParams(e){const t=new WeakSet;t.add(e);const n={};for(const[r,o]of Object.entries(e))n[r]=sanitizeValue({value:o,key:r,visited:t});return n}function sanitizeEndpoint(e){return e.split("?")[0]}function createTrackingHandle(e){const{span:t,startTime:n,durationAttr:r,statusAttr:o}=e;return{span:t,end:__name(e=>{const s=Date.now()-n;if(t.setAttribute(r,s),"status"in e)t.setAttribute(o,e.status),e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r,errorBody:o}=e;if(t.setAttribute("http.status_code",n),o){const e="string"==typeof o?o:safeStringify(o);t.setAttribute("http.response_body",e.substring(0,1e3))}r?(recordError({span:t,error:r}),endSpan({span:t,status:"error"})):endSpan({span:t,status:n>=400?"error":"success"})}},"end")}}function trackToolStart(e){const{toolName:t,params:n}=e;return createTrackingHandle({span:createSpan({name:`tool:${t}`,attributes:{"tool.name":t,"tool.params":safeStringify(n?sanitizeParams(n):{})}}),startTime:Date.now(),durationAttr:"tool.duration_ms",statusAttr:"tool.status"})}function trackError(e){const{error:t,context:n}=e,r=normalizeError(t),{component:o,heading:s,code:a,...i}=n,c={"error.type":r.name,"error.message":r.message,"error.component":o,"error.heading":s};void 0!==a&&(c["error.code"]=String(a));for(const[e,t]of Object.entries(i))null!=t&&(c[e]="object"==typeof t?safeStringify(t):String(t));const l=createSpan({name:`error:${r.name}`,attributes:c});recordError({span:l,error:r}),l.end()}function trackAPICallStart(e){const{method:t,endpoint:n}=e,r=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${r}`,attributes:{"http.method":t,"http.url":r}}),startTime:Date.now(),durationAttr:"http.duration_ms",statusAttr:"http.status"})}function getSupportId(){const e=getTraceId();return e?`req_${e}`:"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,nodeVersion:s,platform:a,arch:i}=e,c={"whoami.node_version":s,"whoami.platform":a,"whoami.arch":i,"whoami.os":`${a}-${i}`};t&&(c["whoami.user_name"]=t),n&&(c["whoami.user_id"]=n),r&&(c["whoami.org_login"]=r),o&&(c["whoami.org_id"]=o),endSpan({span:createSpan({name:"whoami",attributes:c}),status:"success"})}__name(generateSessionId,"generateSessionId"),__name(hashPath,"hashPath"),__name(getCliVersion,"getCliVersion"),__name(buildSessionAttributes,"buildSessionAttributes"),__name(startSession,"startSession"),__name(getTraceId,"getTraceId"),__name(getSessionContext,"getSessionContext"),__name(endSession,"endSession"),__name(setSpanStatus,"setSpanStatus"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError"),__name(isSecretKey,"isSecretKey"),__name(isContentKey,"isContentKey"),__name(safeStringify,"safeStringify"),__name(truncateString,"truncateString"),__name(normalizeError,"normalizeError"),__name(sanitizeErrorForTelemetry,"sanitizeErrorForTelemetry"),__name(sanitizeValue,"sanitizeValue"),__name(sanitizeParams,"sanitizeParams"),__name(sanitizeEndpoint,"sanitizeEndpoint"),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(trackError,"trackError"),__name(trackAPICallStart,"trackAPICallStart"),__name(getSupportId,"getSupportId"),__name(systemInfo,"systemInfo");var zt={AUTH_FLOW:"auth-flow",ANTHROPIC_OAUTH:"anthropic-oauth",ANTHROPIC_CLIENT:"anthropic-client",UNHANDLED_REJECTION:"unhandled-rejection",UNCAUGHT_EXCEPTION:"uncaught-exception",SESSION_MANAGER:"session-manager",UPDATE_COMMAND:"update-command",LEARN_TASTE_COMMAND:"learn-taste-command",LEARNING_AGENT:"learning-agent",TASTE_REMOTE_STORAGE:"taste-remote-storage",CHECKPOINT_MANAGER:"checkpoint-manager",FILE_HISTORY:"file-history",API_REQUEST:"api-request",CONTEXT_ENGINE:"context-engine",CLI_ERROR_HANDLER:"cli-error-handler"},Ht=null,Gt=!1;function initTelemetry(){if(Gt)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return(Ht=createTelemetrySDK()).start(),Gt=!0,!0}catch{return Ht=null,Gt=!1,!1}}async function shutdownTelemetry(){if(Ht&&Gt)try{endSession(),await Ht.shutdown()}catch{}finally{Ht=null,Gt=!1}}function shutdownTelemetrySync(){if(Gt)try{endSession()}catch{}}function isTelemetryInitialized(){return Gt}__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized");var{red:qt,yellow:Vt,dim:Kt}=t,Jt=__name(e=>{const{heading:t="ERROR: ",error:r,displayError:o=!0,exit:s=!0,skipTelemetry:a=!1}=e;if(r){if(a||trackError({error:sanitizeErrorForTelemetry({error:r,label:"cli_error"}),context:{component:zt.CLI_ERROR_HANDLER,heading:t}}),console.log(),o){if(console.log(`${n.error} ${qt(t)}`),console.log(`${n.error} ${qt("ERROR →")} ${r.name}`),console.log(`${n.info} ${qt("REASON →")} ${r.message}`),console.log(`${n.info} ${qt("ERROR STACK ↓ \n")} ${r.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${n.info} ${Kt(`Request ID: ${e}`)}`),console.log(`${Kt(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${n.warning} ${Vt(t)}\n`);if(!s)return!1;process.exit(0)}},"handleError");function handleUnhandledErrors(){process.on("unhandledRejection",t=>{const n=t instanceof Error?t:new Error(String(t));trackError({error:sanitizeErrorForTelemetry({error:n,label:"unhandled_rejection"}),context:{component:zt.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),Jt({heading:e`CRITICAL: Unhandled Promise Rejection!
3
+ This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:n,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})}),process.on("uncaughtException",t=>{trackError({error:sanitizeErrorForTelemetry({error:t,label:"uncaught_exception"}),context:{component:zt.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),Jt({heading:e`CRITICAL: Uncaught Exception!
4
+ This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:t,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}async function findAvailablePort(e=5959,t=10){for(let n=0;n<t;n++){const t=e+n;if(await checkPortAvailable(t))return t}throw new Error(`No available port found after ${t} attempts starting from port ${e}`)}async function checkPortAvailable(e){return new Promise(t=>{const n=be.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}__name(handleUnhandledErrors,"handleUnhandledErrors"),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable");var Yt=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}};function createAuthServer(e,t){let n,r;const o=new Promise((e,t)=>{n=e,r=t}),s=Ee.createServer((e,o)=>{const a=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],i=e.headers.origin||"",c=a.includes(i)?i:a[0];if(o.setHeader("Access-Control-Allow-Origin",c),o.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type"),o.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return o.writeHead(204),void o.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return o.writeHead(404),void o.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return o.writeHead(405),void o.end(JSON.stringify(e))}let l="";e.on("data",t=>{l+=t.toString(),l.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(l);if(e.error){const t=e,n={success:!0};return o.writeHead(200),o.end(JSON.stringify(n)),"access_denied"===t.error?r(new Yt(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void s.close()}const a=e;if(!(a.apiKey&&a.state&&a.userId&&a.userName&&a.keyName)){const e={success:!1,error:"Missing required fields"};return o.writeHead(400),void o.end(JSON.stringify(e))}if(a.state!==t){const e={success:!1,error:"Invalid state token"};return o.writeHead(403),void o.end(JSON.stringify(e))}const i={success:!0};o.writeHead(200),o.end(JSON.stringify(i)),n(a),s.close()}catch{const e={success:!1,error:"Invalid JSON"};o.writeHead(400),o.end(JSON.stringify(e))}}),e.on("error",()=>{o.writeHead(500),o.end(JSON.stringify({success:!1,error:"Request error"}))})});return s.on("error",e=>{r(e)}),s.listen(e,"127.0.0.1"),{server:s,waitForCallback:o}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}function generateStateToken(){return O.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await Z(e),!0}catch(e){return console.error("[CLI Auth] Failed to open browser:",e instanceof Error?e.message:"Unknown error"),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"browser_open_failed"}),context:{component:zt.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(lt()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer"),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl");var Qt=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}};async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await x.mkdir(t,{recursive:!0,mode:448});const r=JSON.stringify({apiKey:e.apiKey,userId:e.userId,userName:e.userName,keyName:e.keyName,authenticatedAt:e.authenticatedAt},null,2);await x.writeFile(n,r,{mode:384}),await x.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await x.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}function getApiBaseUrl(){const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"http://localhost:9090":t?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials"),__name(getApiBaseUrl,"getApiBaseUrl");var Zt=12e4;async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${et.ALPHA.WHOAMI}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});return 401===n.status?{valid:!1,error:"invalid_key"}:n.ok?{valid:!0,user:await n.json()}:(process.env.DEBUG&&console.error(`API key validation failed with status ${n.status}`),{valid:!1,error:"server_error"})}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"apikey_validation_network_error"}),context:{component:zt.AUTH_FLOW,heading:"API key validation network error"}}),process.env.DEBUG&&console.error("API key validation network error:",e),{valid:!1,error:"network_error"}}}function sanitizeApiKey(e){const t=String.fromCharCode(27),n=e.replaceAll(t+"[200~","").replaceAll(t+"[201~","").replaceAll("[200~","").replaceAll("[201~","");return Array.from(n).filter(e=>{const t=e.charCodeAt(0);return t>31&&127!==t}).join("").trim()}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:o=Zt}=e,[s,a]=_("initializing"),[i,c]=_("Starting authentication..."),[l,d]=_(""),[u,m]=_(null),g=U(null),p=U(!1),h=U(!1),f=U(null),y=U(t),w=U(n),E=U(r);j(()=>{y.current=t,w.current=n,E.current=r});const b=B(()=>{f.current&&(clearTimeout(f.current),f.current=null),g.current&&(stopServer(g.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),g.current=null)},[]),k=B(()=>{h.current||(h.current=!0,p.current=!0,b(),E.current())},[b]),S=B((e,t)=>{h.current||(h.current=!0,b(),y.current(e,t))},[b]),C=B((e,t)=>{h.current||(h.current=!0,b(),w.current(e,t))},[b]),v=B(async e=>{const t=sanitizeApiKey(e);if(!t)return;a("validating"),c("Validating API key...");const n=await validateApiKey(t);if(p.current)return;if(h.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return a("invalid_key"),c(e),void(f.current=setTimeout(()=>{p.current||h.current||(a("manual_entry"),c("Paste a valid API key below.")),f.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(h.current)return;await storeCredentials(e),a("success"),S(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:zt.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),c("Failed to save API key. Please try again."),a("manual_entry")}},[S]);return j(()=>{let e=!0;return __name(async()=>{if(!p.current)try{const t=await findAvailablePort(5959,10);if(!e||p.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);m(r);const{server:s,waitForCallback:i}=createAuthServer(t,n);if(g.current=s,!e||p.current)return void await stopServer(s);a("waiting_browser"),c("Opening browser for authentication...");const l=await openBrowser(r);if(!e||p.current)return;if(!l)return b(),c("Could not open browser. Paste your API key below."),void a("manual_entry");c("Complete login in your browser...");const d=new Promise((e,t)=>{setTimeout(()=>{t(new Qt("TIMEOUT","Browser authentication timed out"))},o)});try{const t=await Promise.race([i,d]);if(!e||p.current)return;if(h.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(h.current)return;if(await storeCredentials(n),!e||p.current||h.current)return;a("browser_success"),S(n,"browser")}catch(t){if(h.current)return;if(!e||p.current)return;if(t instanceof Yt)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:zt.AUTH_FLOW,heading:"Authorization denied by user"}}),a("denied"),void C("denied","Authorization denied by user.");b(),t instanceof Qt&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:zt.AUTH_FLOW,heading:"Browser auth timed out"}}),c("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:zt.AUTH_FLOW,heading:"Browser auth failed"}}),c("Browser auth failed. Paste your API key below.")),a("manual_entry")}}catch(t){if(h.current)return;if(!e||p.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:zt.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),b(),a("manual_entry"),c("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,b()}},[o,S,C,b]),{authState:s,statusMessage:i,browserUrl:u,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:v,cancel:k,hasCompleted:h.current}}function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){switch(e){case"waiting_browser":return"Authorize in browser, or paste API key here";case"invalid_key":return"That key was invalid. Try again.";default:return"Paste your API key and press Enter"}}function getAuthUrlLabel(e){return"waiting_browser"===e?"Authenticating via:":"Get your API key from:"}__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow"),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel");var Xt=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:o,handleApiKeySubmit:s})=>{const a=__name(()=>{switch(e){case"initializing":case"waiting_browser":case"validating":default:return N.createElement(we,{type:"dots"});case"browser_success":case"success":return N.createElement(H,{color:"green"},ae.tick);case"denied":case"invalid_key":return N.createElement(H,{color:"red"},ae.cross);case"manual_entry":return N.createElement(H,{color:"yellow"},ae.arrowDown);case"error":return N.createElement(H,{color:"red"},ae.warning)}},"getStatusIcon"),i=__name(()=>getAuthStatusColor(e),"getStatusColor");if("browser_success"===e||"success"===e||"denied"===e)return null;const c="initializing"===e||"waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,l=n&&("waiting_browser"===e||"manual_entry"===e);return N.createElement(z,{flexDirection:"column",paddingY:1},N.createElement(z,{marginBottom:1},N.createElement(z,{marginRight:1},a()),N.createElement(H,{color:i()},t)),c&&N.createElement(z,{flexDirection:"column"},N.createElement(z,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?"yellow":"gray",paddingX:1},N.createElement(H,{dimColor:!0},"API Key: "),N.createElement(z,{flexGrow:1},N.createElement(TextInput,{value:r,onChange:o,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},getAuthHelpText(e))),l&&N.createElement(z,{marginTop:1,flexDirection:"column"},N.createElement(H,{dimColor:!0},getAuthUrlLabel(e)),N.createElement(H,{color:"cyan",dimColor:!0},n||getStudioAuthUrl(lt())))),"validating"===e&&N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"initializing"===e||"invalid_key"===e)&&N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Ctrl+C to cancel")))},"AuthFlowUI"),en=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a,cancel:i}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return V((e,t)=>{t.ctrl&&"c"===e&&i()}),N.createElement(Xt,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:o,setApiKeyInput:s,handleApiKeySubmit:a})},"LoginWithApiKey");function heading({text:e,sub:t,dim:n,green:r}){const o=t?` ${t}`:"";return r?`${Y.bgGreen(Y.black(` ${e} `))}${o}`:n?`${Y.bgBlack(Y.white(` ${e} `))}${o}`:`${Y.bold(Y.bgCyan(Y.black(` ${e} `)))}${o}`}async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=ut.createAuthorizationUrl(),r=await fe({message:"Open the Anthropic auth page?"});if(pe(r))return{success:!1,error:"Anthropic authentication cancelled"};!0===r?(await Z(e),console.log(),console.log(Y.yellow(" Copy your authorization code from the opened page and paste it here.")),console.log()):(console.log(),console.log(Y.dim(" Open this URL in your browser:")),console.log(),console.log(Y.cyan(` ${e}`)),console.log(),console.log(Y.yellow(" Copy your authorization code and paste it below.")),console.log());const o=await ye({message:"Paste your authorization code:",mask:"*"});if(pe(o))return{success:!1,error:"No API key provided"};if(!o.trim())return{success:!1,error:"No authorization code provided"};const s=o.split("#")[0].trim();return await ut.exchangeCodeForTokens(s,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}__name(heading,"heading"),__name(performAnthropicAuth,"performAnthropicAuth");var tn=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},nn=class extends Error{static{__name(this,"AuthorizationDeniedError")}constructor(e){super(e),this.name="AuthorizationDeniedError"}};async function readAuthFile(e){try{const t=getAuthFile(e),n=await I.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async function getAuthKey(e){const t=await readAuthFile(e);return t&&t.apiKey||null}async function checkAuthStatus(e){const t=await readAuthFile(e);return t&&t.apiKey?{authenticated:!0,apiKey:t.apiKey,userName:t.userName}:{authenticated:!1,apiKey:null}}async function statusAction(){const e=ke("Checking authentication status...").start();try{const t=lt(),n=await checkAuthStatus(t);n.error&&(e.fail(Y.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(e.fail(Y.red("Not authenticated")),console.log(""),console.log(`${Y.dim("Run")} ${Y.cyan("cmd auth login")} ${Y.dim("to authenticate.")}`),console.log(""),process.exit(1)),e.succeed("Authentication verified"),console.log(""),console.log(`${Y.green(ae.tick)} ${Y.bold("Authenticated")} with ${Y.cyan("Command Code")}`),n.userName&&console.log(`${Y.dim("Logged in as")} ${Y.cyan(n.userName)}`),console.log(""),process.exit(0)}catch(t){e.fail(Y.red(`Status check failed: ${t instanceof Error?t.message:"Unknown error"}`)),process.exit(1)}}__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(checkAuthStatus,"checkAuthStatus"),__name(statusAction,"statusAction");var rn=new le("status").description("Show authentication status").allowUnknownOption().allowExcessArguments().action(statusAction),on=__name(({message:e})=>N.createElement(N.Fragment,null,N.createElement(H,{color:"cyan"},N.createElement(we,{type:"dots"})),N.createElement(H,null," ",e)),"LoadingIndicator"),sn=__name(({message:e})=>N.createElement(N.Fragment,null,N.createElement(H,{color:"green"},ae.tick),N.createElement(H,null," ",e)),"SuccessIndicator"),an=__name(({children:e})=>N.createElement(z,{flexDirection:"column"},N.createElement(H,null," "),N.createElement(z,null,e)),"StatusContainer");function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:o=!0}){const[s,a]=_("loading"),[i,c]=_(null);return j(()=>{n().then(e=>{c(e),a(o?"success":"done")})},[n,o]),j(()=>{if("done"===s&&null!==i&&r(i),"success"===s&&null!==i){const e=setTimeout(()=>r(i),100);return()=>clearTimeout(e)}},[s,i,r]),"done"===s?null:N.createElement(an,null,"loading"===s?N.createElement(on,{message:e}):N.createElement(sn,{message:t}))}async function checkExistingAuth(e){const t=await checkAuthStatus(e);return t.authenticated?{isAuthenticated:!0,userName:t.userName}:{isAuthenticated:!1}}function getAuthFileName(e){return"local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json"}function isGenericUserName(e){return!e||"API Key"===e}function isGenericUserNameForOutro(e){return isGenericUserName(e)||"Manual API Key"===e}function formatUserDisplay(e,t=!1){return(t?isGenericUserNameForOutro(e):isGenericUserName(e))?t?" successfully":"":` as ${Y.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${Y.green(ae.tick)} ${Y.bold("Already logged in")}${t}`,"",`${Y.dim("Run")} ${Y.cyan("cmd")} ${Y.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${Y.green(ae.tick)} ${Y.bold("Logged in")}${n}`,"",`${Y.dim("API key stored in")} ${Y.cyan(`~/.commandcode/${t}`)}`,`${Y.dim("Run")} ${Y.cyan("cmd")} ${Y.dim("to get started.")}`].join("\n")}function isLoginSuccess(e){return e.success}function isLoginDenied(e){return"denied"===e.reason}function isLoginCancelled(e){return"cancelled"===e.reason}function createLoginError(e){return isLoginDenied(e)?new nn(e.message):isLoginCancelled(e)?new tn(e.message):new Error(e.message)}function processLoginResult(e){return isLoginSuccess(e)?{success:!0,userName:e.config?.userName}:{success:!1,error:createLoginError(e)}}function needsProviderSelection(e){return e.length>1}function getDefaultProvider(e){return e[0]?.value??""}function isAnthropicProvider(e){return"anthropic"===e}function isUserCancellation(e){return e instanceof tn||e instanceof nn}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),ue.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await ge({message:"Select provider",options:e});if(pe(t))throw me(`${ae.cross} No provider selected.`),new tn("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){me(`${ae.cross} ${e}`)}function showAnthropicAuthNote(){he("Command Code authentication complete. Now authenticating with Anthropic...")}function printMessage(e){console.log(""),console.log(e),console.log("")}function renderTaskWithSpinner(e,t,n,r=!0){return new Promise(o=>{const s=__name(e=>{a(),o(e)},"handleComplete"),{unmount:a}=q(N.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:s,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=q(N.createElement(en,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__name(isGenericUserName,"isGenericUserName"),__name(isGenericUserNameForOutro,"isGenericUserNameForOutro"),__name(formatUserDisplay,"formatUserDisplay"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(isLoginSuccess,"isLoginSuccess"),__name(isLoginDenied,"isLoginDenied"),__name(isLoginCancelled,"isLoginCancelled"),__name(createLoginError,"createLoginError"),__name(processLoginResult,"processLoginResult"),__name(needsProviderSelection,"needsProviderSelection"),__name(getDefaultProvider,"getDefaultProvider"),__name(isAnthropicProvider,"isAnthropicProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage,"getErrorMessage"),__name(showAuthIntro,"showAuthIntro"),__name(promptProviderSelection,"promptProviderSelection"),__name(selectProvider,"selectProvider"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(showAnthropicAuthNote,"showAnthropicAuthNote"),__name(printMessage,"printMessage"),__name(renderTaskWithSpinner,"renderTaskWithSpinner"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow");var cn=__name(({env:e,onComplete:t})=>{const[n,r]=_("checking"),[o,s]=_(null);return j(()=>{checkExistingAuth(e).then(e=>{s(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),j(()=>{if("checking"!==n&&null!==o){const e=setTimeout(()=>t(o),100);return()=>clearTimeout(e)}},[n,o,t]),N.createElement(an,null,"checking"===n&&N.createElement(on,{message:"Checking authentication status..."}),"logged_in"===n&&N.createElement(sn,{message:"Authenticated"}),"not_logged_in"===n&&N.createElement(sn,{message:"Ready to log in"}))},"AuthCheckSpinner");async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=q(N.createElement(cn,{env:e,onComplete:e=>{n(),t(e)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function saveConfigWithSpinner(e){await renderTaskWithSpinner("Saving configuration...","Configuration saved",()=>updateUserConfig({provider:e}),!0)}async function executeLoginFlow(){const e=processLoginResult(await runLoginWithApiKeyFlow());if(!e.success)throw showLoginCancelMessage(e.error.message),e.error;return e.userName}async function handleAnthropicAuth(e){isAnthropicProvider(e)&&(showAnthropicAuthNote(),await performAnthropicAuth())}async function finalizeLogin(e,t,n){await saveConfigWithSpinner(e),printMessage(buildSuccessMessage(t,getAuthFileName(n)))}async function runLogin(){const e=lt(),t=await checkAuthWithSpinner(e);if(t.isAuthenticated)return printMessage(buildAlreadyLoggedInMessage(t.userName)),!0;showAuthIntro();const n=await executeLoginFlow();let r="command-code";return isInternalTeamFlagEnforced()&&(r=await selectProvider(),await handleAnthropicAuth(r)),await finalizeLogin(r,n,e),!0}async function loginAction(){try{await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${ae.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleAnthropicAuth,"handleAnthropicAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction");var ln=new le("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction);async function safeRemoveFile(e,t){try{return await I.unlink(e),{existed:!0}}catch(e){return"ENOENT"===e.code?{existed:!1}:{existed:!0,warning:`Could not remove ${t}: ${e.message}`}}}function collectWarnings(...e){return e.map(e=>e.warning).filter(e=>void 0!==e)}async function performLogout(){try{const e=await safeRemoveFile(getAuthFile(),"auth file"),t=collectWarnings(e);return{success:!0,wasAuthenticated:e.existed,warnings:t}}catch(e){return{success:!1,wasAuthenticated:!1,warnings:[],error:e instanceof Error?e.message:"Unknown error"}}}__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout");var dn=__name(()=>N.createElement(N.Fragment,null,N.createElement(H,{color:"cyan"},N.createElement(we,{type:"dots"})),N.createElement(H,null," Logging out...")),"LoadingIndicator"),un=__name(()=>N.createElement(N.Fragment,null,N.createElement(H,{color:"green"},ae.tick),N.createElement(H,null," Logged out")),"SuccessIndicator"),mn=__name(({errorMessage:e})=>N.createElement(N.Fragment,null,N.createElement(H,{color:"red"},ae.cross),N.createElement(H,{color:"red"}," Logout failed: ",e)),"ErrorIndicator"),gn=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return N.createElement(dn,null);case"success":return N.createElement(un,null);case"error":return N.createElement(mn,{errorMessage:t})}},"StatusDisplay"),pn=__name(({onComplete:e})=>{const[t,n]=_("loading"),[r,o]=_(""),[s,a]=_(null);return j(()=>{performLogout().then(e=>{a(e),e.success?n("success"):(o(e.error||"Unknown error"),n("error"))})},[]),j(()=>{if(("success"===t||"error"===t)&&s){const t=setTimeout(()=>e(s),100);return()=>clearTimeout(t)}},[t,s,e]),N.createElement(z,{flexDirection:"column"},N.createElement(H,null," "),N.createElement(z,null,N.createElement(gn,{status:t,errorMessage:r})))},"LogoutSpinner");function printWarnings(e){e.length>0&&(console.warn(Y.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(Y.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=q(N.createElement(pn,{onComplete:n=>{t(),e(n)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction");var hn=new le("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction);new le("auth").description("Manage authentication with Command Code").addCommand(ln).addCommand(hn).addCommand(rn);var fn="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",yn="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n";function getMaxLineWidth(e){return Math.max(...e.split("\n").map(e=>e.length))}__name(getMaxLineWidth,"getMaxLineWidth");var wn=getMaxLineWidth(fn),En=getMaxLineWidth(yn),bn=wn+1,kn=En+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var Sn=__name(e=>{const t=e??getTerminalWidth();return t>=bn?fn:t>=kn?yn:Cn},"getResponsiveCommandLogo"),Cn="⌘ CMD\n",vn=__name(e=>{const t=e.trim().toLowerCase();return""===t||"y"===t||"yes"===t},"isAffirmative"),Tn=__name(e=>{console.log(t.white(Sn())),console.log(""),console.log(`${ae.warning} Authentication required to use Command Code.`),console.log("")},"showUnauthBanner"),An=__name(async e=>{const t=ce.createInterface({input:process.stdin,output:process.stdout});try{const n=await t.question(e);return t.close(),{answer:n,cancelled:!1}}catch{return t.close(),{answer:"",cancelled:!0}}},"promptYesNo"),Pn=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.log(""),console.log(`${ae.cross} Authentication failed. Please try again with: cmd login`),!1)}catch{return!1}},"attemptLogin"),xn=__name(()=>{console.log(""),console.log(`${ae.info} You can authenticate later by running: cmd login`)},"showDeferredMessage"),In=__name(()=>{console.log(""),console.log(`${ae.info} Authentication cancelled. You can authenticate later with: cmd login`)},"showCancelledMessage");async function checkAuthAndPromptLogin(){try{if(await getAuthKey())return!0;Tn(dt());const{answer:e,cancelled:n}=await An(`Would you like to sign in now? ${t.dim("(y/n)")}: `);return n?(In(),!1):vn(e)?(console.log(""),Pn()):(xn(),!1)}catch(e){return console.error("Error checking authentication:",e),!1}}__name(checkAuthAndPromptLogin,"checkAuthAndPromptLogin");var $n=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(!w.isAbsolute(e)&&!this.isWindowsAbsolutePath(e))return e;try{const t=w.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=w.basename(e);return w.dirname(e),this.isUserPath(e)?`<user-home>/${w.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))}},Dn=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 Fn({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Rn(e,o,n,r);case 401:return new Mn(e,o,n,r);case 403:return new On(e,o,n,r);case 404:return new Ln(e,o,n,r);case 409:return new Nn(e,o,n,r);case 422:return new _n(e,o,n,r);case 429:return new Un(e,o,n,r);default:return e>=500?new jn(e,o,n,r):new _APIError(e,o,n,r)}}},Fn=class extends Dn{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)}},Rn=class extends Dn{static{__name(this,"BadRequestError")}status=400},Mn=class extends Dn{static{__name(this,"AuthenticationError")}status=401},On=class extends Dn{static{__name(this,"PermissionDeniedError")}status=403},Ln=class extends Dn{static{__name(this,"NotFoundError")}status=404},Nn=class extends Dn{static{__name(this,"ConflictError")}status=409},_n=class extends Dn{static{__name(this,"UnprocessableEntityError")}status=422},Un=class extends Dn{static{__name(this,"RateLimitError")}status=429},jn=class extends Dn{static{__name(this,"InternalServerError")}},Bn=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=await this.buildHeaders({headers:e.headers}),o=trackAPICallStart({method:e.method,endpoint:t});let s;try{s=await this.makeRequest({url:n,options:e,headers:r})}catch(e){const t=new Fn({cause:e instanceof Error?e:void 0});throw o.end({statusCode:0,error:t}),t}if(!s.ok){const{error:e}=await this.handleErrorResponse({response:s});throw o.end({statusCode:s.status,error:e}),e}return o.end({statusCode:s.status}),e.stream?s.body:s.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e}){const t=await getAuthKey();return{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},...e}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,o=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const s=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return o&&clearTimeout(o),s}catch(e){throw o&&clearTimeout(o),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};return e.headers.forEach((e,t)=>{n[t]=e}),{error:Dn.generate(e.status,t,e.statusText,n),errorBody:t}}async post(e){return this.send({...e,method:"POST"})}async get(e){return this.send({...e,method:"GET"})}async put(e){return this.send({...e,method:"PUT"})}async delete(e){return this.send({...e,method:"DELETE"})}},Wn=P.object({name:P.string().min(1,"Skill name is required").max(64,"Skill name must be 64 characters or less").regex(/^[a-z0-9-]+$/,"Skill name must contain only lowercase letters, numbers, and hyphens").refine(e=>!e.startsWith("-")&&!e.endsWith("-"),"Skill name cannot start or end with a hyphen").refine(e=>!e.includes("--"),"Skill name cannot contain consecutive hyphens"),description:P.string().min(1,"Skill description is required").max(1024,"Skill description must be 1024 characters or less"),license:P.string().optional(),compatibility:P.array(P.string()).optional(),metadata:P.record(P.string(),P.any()).optional(),"allowed-tools":P.array(P.string()).optional()});function getPersonalSkillsDir(){return w.join(T.homedir(),".commandcode","skills")}function getProjectSkillsDir(){return w.join(process.cwd(),".commandcode","skills")}async function loadSkillSummariesFromDirectory(e){const{dir:t}=e;try{await I.access(t);const e=(await I.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory());return(await Promise.all(e.map(async e=>{try{const n=w.join(t,e.name,"SKILL.md");await I.access(n);const r=await I.readFile(n,"utf-8"),{data:o}=Ce(r),s=Wn.parse(o);return{name:s.name,description:s.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=w.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)}P.object({name:P.string(),description:P.string(),license:P.string().optional(),compatibility:P.array(P.string()).optional(),metadata:P.record(P.string(),P.any()).optional(),"allowed-tools":P.array(P.string()).optional(),content:P.string(),filePath:P.string()}),P.object({name:P.string(),description:P.string(),filePath:P.string()}),__name(getPersonalSkillsDir,"getPersonalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries"),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML"),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath");var zn=P.object({absolutePath:P.string().describe("The absolute path to the file to read"),offset:P.number().optional().describe("Optional line number to start reading from (0-based index)"),limit:P.number().optional().describe("Optional number of lines to read")});P.object({content:P.union([P.string(),P.instanceof(Buffer)]),contentType:P.enum(["text","binary"]),fileType:P.string(),size:P.number(),linesRead:P.number().optional()});var Hn=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(!y.isAbsolute(t)&&!isWindowsAbsolutePath(t))throw new Hn("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=y.normalize(t);try{await x.access(o,c.constants.F_OK|c.constants.R_OK)}catch{throw new Hn(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await x.stat(o)).isFile())throw new Hn("Path does not point to a file","NOT_A_FILE");const s=getFileType(o),a=isBinaryFile(s);if(void 0!==n&&void 0===r||void 0===n&&void 0!==r)throw new Hn("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==n&&n<0)throw new Hn("Offset must be >= 0","INVALID_OFFSET");if(void 0!==r&&r<=0)throw new Hn("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await x.readFile(o);return{fileType:s,content:e,size:e.length,contentType:"binary"}}if(void 0!==n&&void 0!==r){const e=await readTextFileLines(o,n,r);return{fileType:s,contentType:"text",content:e.content,size:e.content.length,linesRead:e.linesRead}}{const e=await x.readFile(o,"utf8");return{content:e,fileType:s,contentType:"text",size:e.length}}}catch(e){if(e instanceof Hn)throw e;throw new Hn(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}__name(readFileContent,"readFileContent");var Gn={".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=y.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",...Gn}[t]||"unknown"}function isBinaryFile(e){return Object.values(Gn).includes(e)}async function readTextFileLines(e,t,n){const r=(await x.readFile(e,"utf8")).split(/\r?\n/),o=t,s=Math.min(o+n,r.length),a=r.slice(o,s);return{content:a.join("\n"),linesRead:a.length}}async function processFileReferences(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=y.isAbsolute(o)?o:y.resolve(process.cwd(),o),s=await readFileContent({absolutePath:e});if("binary"===s.contentType)continue;const a=String(s.content),i=y.relative(process.cwd(),e),c=1e5;if(a.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:a});const l=`{${i}: ${a}}`;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=`{${y.relative(process.cwd(),e.resolvedPath)}: ${e.content}}`;n=n.replace(e.token,t)}return n}__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines"),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent");var qn="read_file",Vn="edit_file",Kn="write_file",Jn="read_directory",Yn="read_multiple_files",Qn="grep",Zn="shell_command",Xn="think",er="todo_write",tr="ask_user_question",nr="kill_shell",rr="web_search",or="web_fetch",sr=__name(e=>e===rr,"isWebSearchTool");function toRelativePath(e){const t=global.COMMAND_CODE_CWD||process.cwd(),n=process.env.HOME||process.env.USERPROFILE||"",r=y.relative(t,e);return r.startsWith("..")?n&&e.startsWith(n)?e.replace(n,"~"):e:""===r?y.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=>y.isAbsolute(e)?toRelativePath(e):e),t=t.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),t}__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText");var ar=P.object({id:P.string(),timestamp:P.number(),type:P.literal("image"),source:P.object({type:P.enum(["base64","url"]),media_type:P.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:P.string()})}),ir=P.object({id:P.string(),timestamp:P.number(),input:P.string(),output:P.string().optional(),metadata:P.record(P.string(),P.any()).optional(),images:P.array(ar).optional().default([])}),cr=ir.extend({role:P.literal("user")}),lr=ir.extend({role:P.literal("assistant")}),dr=ir.extend({role:P.literal("tool"),name:P.string()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),ur=ir.extend({role:P.literal("bash"),command:P.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),mr=ir.extend({role:P.literal("system")}),gr=ir.extend({role:P.literal("error")}),pr=ir.extend({role:P.literal("info")}),hr=ir.extend({role:P.literal("taste-onboarding")}),fr=ir.extend({role:P.literal("command-result"),hasError:P.boolean().optional(),details:P.string().optional()}),yr=P.discriminatedUnion("role",[cr,lr,dr,ur,mr,gr,pr,hr,fr]),wr=__name((e,t)=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),Er=__name(e=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e}),"createInfoEntry"),br=__name(e=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),kr=__name((e,t,n)=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),Sr=__name(e=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),Cr=__name(e=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e}),"createSystemEntry"),vr=__name(e=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),Tr=__name(()=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),Ar=__name((e,t=!1,n)=>yr.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),Pr=__name(({name:e,input:t})=>{const n=Date.now();return yr.parse({id:crypto.randomUUID(),timestamp:n,role:"tool",name:e,input:t,output:void 0,metadata:{isAgent:!0,status:"running",startTime:n,tokensUsed:0}})},"createAgentToolEntry"),xr=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return yr.parse(n)},"updateEntryWithOutput"),Ir=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),$r=__name(e=>e.output?.startsWith("Error:")??!1,"isErrorEntry"),Dr=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),Fr=["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…"],Rr=__name(()=>Fr[Math.floor(Math.random()*Fr.length)],"getRandomLLMStatus"),Mr=__name(e=>{switch(e){case qn:return"Read";case Vn:return"Edit";case Kn:return"Write";case Jn:return"List";case Yn:return"Read Multiple";case Qn:return"Search";case Zn:return"Shell";case er:return"Todos";case Xn:return"Thinking…";case rr:return"Web Search";case or:return"Web Fetch";case tr:return"Question";case"explore":return"Explore";case nr:return"Kill Shell";default:return e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}},"getToolDisplayName"),Or=__name((e,t)=>{try{switch(e){case qn:case Kn:const e=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(e);case Vn:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Jn:return toRelativePath(t.path||"directory");case Qn:const n=t.path||"files";return`"${t.pattern}" in ${toRelativePath(n)}`;case Zn: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 er:let r;try{r="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=Lr(r);return`${e?e.length:0} items`}catch{return"items"}case Xn:return t.content||"planning";case Yn:const o=t.include||[];return Array.isArray(o)?o.join(", "):"multiple files";case rr:return t.query||"search";case or:return t.url||"fetch";case tr:return"User answered questions";case nr:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";default:{let e=t?.messages||[];if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return JSON.stringify(t||{})}if(Array.isArray(e)&&e.length>0&&e[0]&&"object"==typeof e[0]&&"content"in e[0]){const t=e[0].content;if("string"==typeof t){const e=t.trim(),n=e.indexOf("."),r=n>0?e.slice(0,n):e;return r.length>80?r.slice(0,80)+"...":r}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),Lr=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput");function formatOutput(e){const t=[];if(void 0!==e.linesRead)t.push(`Read ${e.linesRead} lines`);else if("binary"===e.contentType)t.push(`Binary file: ${e.size} bytes`);else{const n=e.content?String(e.content).split("\n").length:0;t.push(`Read ${n} lines`)}return"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}__name(formatOutput,"formatOutput");var Nr={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=zn.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`${ae.cross} Error: ${e.message}`:`${ae.cross} Error: Unknown error occurred while reading file`}},"execute")},_r=P.object({filePath:P.string().describe("The absolute path to the file to edit"),oldValue:P.string().describe("The text to replace"),newValue:P.string().describe("The new text to insert"),replacementCount:P.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:P.boolean().optional().describe("Whether to replace all occurrences (default: false)")});P.object({path:P.string(),replacementsCount:P.number(),oldContent:P.string(),newContent:P.string()}),P.object({name:P.string(),message:P.string(),code:P.string().optional()});var Ur=P.object({backupFileName:P.string().nullable(),version:P.number().int().positive(),backupTime:P.string().datetime()}),jr=P.object({messageId:P.string().uuid(),trackedFileBackups:P.record(P.string(),Ur),timestamp:P.string().datetime()});P.object({type:P.literal("file-history-snapshot"),messageId:P.string().uuid(),snapshot:jr,isSnapshotUpdate:P.boolean()}),P.object({maxFileSize:P.number().int().positive().default(10485760),retentionDays:P.number().int().positive().default(30)});var Br=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`${L.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 w.join(T.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:t}=e;return w.join(getCommandCodeBasePath(),"file-history",t)}function getBackupFilePath(e){const{sessionId:t,backupFileName:n}=e;return w.join(getFileHistoryPath({sessionId:t}),n)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await I.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 I.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await I.writeFile(r,n);const e=await I.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 I.rename(r,t)}catch(e){try{await I.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await I.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await I.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function truncateString2(e){const{text:t,maxLength:n}=e;return t.length<=n?t:n<=3?t.slice(0,n):t.slice(0,n-3)+"..."}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60),a=Math.floor(s/24);return a>0?`${a}d ago`:s>0?`${s}h ago`:o>0?`${o}m ago`:"just now"}function getFileName(e){const{filePath:t}=e;return w.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(truncateString2,"truncateString"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod");var Wr={maxFileSize:10485760,retentionDays:30},zr=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Wr,...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 I.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,o=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const s=getBackupFilePath({sessionId:this.sessionId,backupFileName:o});await atomicWriteFile({filePath:s,content:e});const a={backupFileName:o,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,a),this.trackedState.versions.set(t,n),{success:!0,backup:a,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:zt.FILE_HISTORY,heading:"File backup failed"}}),{success:!1,backup:null,skipped:!0,skipReason:"read_error"}}}async restoreFile(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName)return void(await fileExists({filePath:t})&&await I.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new Br(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:zt.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const o=await I.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 I.access(t,I.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 I.readdir(n);for(const o of e)if(!o.endsWith(".tmp")&&!t.has(o))try{await I.unlink(`${n}/${o}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await I.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}},Hr=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new zr({sessionId:t,config:r}),this.sessionStore=n||null,this.snapshots=[],this.config={maxFileSize:r?.maxFileSize||10485760,retentionDays:r?.retentionDays||30}}getFileHistoryManager(){return this.fileHistoryManager}setSessionStore(e){const{sessionStore:t}=e;this.sessionStore=t}async backupFile(e){const{filePath:t}=e,n=await this.fileHistoryManager.backupFile({filePath:t,sessionId:this.fileHistoryManager.getSessionId()});if(n.success&&this.snapshots.length>0){const e=this.snapshots[this.snapshots.length-1];e.trackedFileBackups=this.fileHistoryManager.getTrackedFileBackups(),this.sessionStore&&this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0}).catch(()=>{})}return{success:n.success,backup:n.backup}}async createSnapshot(e){const{messageId:t}=e,n={messageId:t,trackedFileBackups:{},timestamp:getCurrentTimestamp()};return this.snapshots.push(n),this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:n,isUpdate:!1}),n}async updateCurrentSnapshot(){if(0===this.snapshots.length)return;const e=this.snapshots[this.snapshots.length-1],t=this.fileHistoryManager.getTrackedFileBackups(),n=this.snapshots.length>1?this.snapshots[this.snapshots.length-2]:null,r=n?.trackedFileBackups||{},o={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(o[e]=n)}e.trackedFileBackups=o,this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0})}listCheckpoints(){const e=[];for(let t=0;t<this.snapshots.length;t++){const n=this.snapshots[t];t>0&&this.snapshots[t-1];let r="";if(this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:n.messageId}),t=this.sessionStore.getMessageAtIndex({index:e});t&&(r=truncateString2({text:t.content,maxLength:100}))}const o=Object.keys(n.trackedFileBackups);let s=null;if(o.length>0){const e=o[0];n.trackedFileBackups[e]&&(s={additions:0,deletions:0,fileName:getFileName({filePath:e})})}e.push({messageId:n.messageId,timestamp:n.timestamp,userPrompt:r,fileCount:Object.keys(n.trackedFileBackups).length,filesModified:o,codeChanges:s})}return e.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())}getSnapshot(e){const{messageId:t}=e;return this.snapshots.find(e=>e.messageId===t)||null}async restore(e){const{messageId:t,mode:n}=e;if(!this.getSnapshot({messageId:t}))return{success:!1,error:"Snapshot not found",filesRestored:0,filesDeleted:0,messagesRemoved:0};const r=this.snapshots.findIndex(e=>e.messageId===t);let o=0,s=0,a=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:zt.CHECKPOINT_MANAGER,heading:"Checkpoint restore verification failed","checkpoint.failures":t.length}}),{success:!1,error:`Restore verification failed:\n${t.join("\n")}`,filesRestored:0,filesDeleted:0,messagesRemoved:0};for(const t of e)await this.fileHistoryManager.restoreFile({filePath:t.filePath,backup:t.backup}),null===t.backup.backupFileName?s++:o++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(a=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const i=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&i.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&i.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:i}),{success:!0,filesRestored:o,filesDeleted:s,messagesRemoved:a}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}},Gr=null;function initializeCheckpointService(e){const{sessionId:t}=e;return Gr=new Hr({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return Gr?Gr.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:s=1}=e;if(!t)throw createFileEditError("filePath is required","INVALID_PATH");if(!y.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&&s<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await m.access(t,g.F_OK|g.R_OK|g.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${t}`,"FILE_ACCESS_ERROR")}let a;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");a=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const i=(a.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=s,c>i)throw createFileEditError(`Expected ${c} replacements, but only found ${i} occurrences`,"INSUFFICIENT_MATCHES");let d=0;if(o||c===i)l=a.split(n).join(r),d=i;else{l=a;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 m.writeFile(t,l,"utf-8"),{path:t,replacementsCount:d,oldContent:a,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 qr={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=_r.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`${ae.cross} Error: ${e.message}`:`${ae.cross} Error: Unknown error occurred while editing file`}},"execute")},Vr=P.object({path:P.string().describe("The absolute path to the directory to read"),exclude:P.array(P.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:P.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")});P.object({files:P.array(P.string()),directories:P.array(P.string())});var Kr=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(!y.isAbsolute(t))throw new Kr("Path must be absolute, not relative","INVALID_PATH");try{if(!(await x.stat(t)).isDirectory())throw new Kr("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Kr)throw e;throw new Kr(`Directory does not exist or is not accessible: ${t}`,"DIRECTORY_ACCESS_ERROR")}try{const e=await x.readdir(t);let o=[];r&&(o=await loadGitIgnorePatterns(t));const s=[...n,...o],a=[],i=[];for(const n of e){if(shouldIgnoreEntry(n,s))continue;const e=y.join(t,n);try{const t=await x.stat(e);t.isDirectory()?i.push(n):t.isFile()&&a.push(n)}catch(t){console.warn(`Warning: Could not access ${e}`)}}return{files:a.sort(),directories:i.sort()}}catch(e){if(e instanceof Kr)throw e;throw new Kr(`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=y.resolve(e);const r=await findGitRoot(e);for(;n&&isWithinGitRoot(n,r);){const e=y.join(n,".gitignore");try{const n=(await x.readFile(e,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));t.push(...n)}catch(e){}const r=y.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=y.resolve(e);for(;;){try{const e=y.join(t,".git");if((await x.stat(e)).isDirectory())return t}catch{}const e=y.dirname(t);if(e===t)throw new Error("Not in a git repository");t=e}}function isWithinGitRoot(e,t){const n=y.resolve(e),r=y.resolve(t);return"win32"===process.platform?n.toLowerCase().startsWith(r.toLowerCase()):n.startsWith(r)}function shouldIgnoreEntry(e,t){for(const n of t)if(ve(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 Jr={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=Vr.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`${ae.cross} Error: ${e.message}`:`${ae.cross} Error: Unknown error occurred while reading directory`}},"execute")},Yr=P.object({filePath:P.string().describe("The absolute path where the file should be written"),content:P.string().describe("The content to write to the file")});async function writeFile2({filePath:e,content:t}){if(!S(e))throw new Error(`Invalid file path: '${e}'. Only absolute paths are supported.`);try{const n=b(e);return d(n)||await $(n,{recursive:!0}),await backupFileBeforeEdit({filePath:e}),await D(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}`}P.object({success:P.boolean(),message:P.string(),path:P.string().optional()}),__name(writeFile2,"writeFile"),__name(formatOutput4,"formatOutput");var Qr={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=Yr.parse(e),n=await writeFile2(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")},Zr=P.object({include:P.array(P.string()).describe("Array of glob patterns to include files"),exclude:P.array(P.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:P.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:P.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:P.string().optional().describe("Base directory for relative paths. Default: current working directory")}),Xr=P.object({filePath:P.string(),content:P.string(),fileType:P.string(),size:P.number()});P.object({content:P.string(),filesRead:P.array(P.string()),errors:P.array(P.object({file:P.string(),error:P.string()})),fileDetails:P.array(Xr)});var eo=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}},to=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"];async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const o=new Set;for(const s of e)try{(await Te(s,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>o.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${s}": ${e}`)}return Array.from(o).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:t,exclude:n=[],gitIgnore:r=!0,defaultExclude:o=!0,targetDirectory:s=process.cwd()}=e;if(!t||0===t.length)throw new eo("At least one include pattern must be provided","NO_PATTERNS");const a=w.resolve(s),i={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...n];o&&e.push(...to);const s=await findMatchingFiles({include:t,exclude:e,gitIgnore:r,targetDirectory:a});for(const e of s)try{const t=w.resolve(a,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 eo)throw e;throw new eo(`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 no={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=Zr.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`${ae.cross} Error: ${e.message}`:`${ae.cross} Error: Unknown error occurred while reading multiple files`}},"execute")},ro=P.object({pattern:P.string().min(1,"Pattern is required"),include:P.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},P.array(P.string()).optional()),directory:P.string().optional()}),oo=1e5,so=5e4;function execCommand({args:e,command:t}){return new Promise((n,r)=>{const o=M(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let s="",a="";o.stdout?.on("data",e=>{try{const t=e.toString();if(s.length+t.length>oo)return a="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",void o.kill("SIGTERM");s+=t}catch(e){a+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,o.kill("SIGTERM")}}),o.stderr?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>so)return void(a+="\n[Error output truncated: too large]");a+=t}catch(e){a+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),o.on("close",e=>{0===e?n(s):1!==e||a?r(new Error(a||`Command failed with exit code ${e}`)):n("")}),o.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,o]=t;return{file:n,line:parseInt(r,10),column:1,content:o.trim(),match:o.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",o=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)o.splice(-1,0,"--glob",e);o.splice(-1,0,"--glob","!node_modules/**"),o.splice(-1,0,"--glob","!.git/**"),o.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:o,command:"rg"})}catch(s){if(!(s instanceof Error&&s.message.includes("ENOENT")))throw s;if(r="grep",o=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)o.splice(-1,0,"--include",e);o.splice(-1,0,"--exclude-dir=node_modules"),o.splice(-1,0,"--exclude-dir=.git"),o.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:o,command:"grep"})}if(!e.trim())return[];const s=e.trim().split("\n"),a=[];for(const e of s){const t=parseGrepLine(e);t&&a.push(t)}return a}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,o=Object.keys(t).length;n.push(`Found ${r} matches in ${o} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory"),__name(formatGrepResults,"formatGrepResults");var ao={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=ro.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`${ae.cross} Error: ${e.message}`:`${ae.cross} Error: Unknown error occurred while searching files`}},"execute")},io=P.object({pattern:P.string().min(1,"Pattern is required"),path:P.string().optional()}),co=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 co("Pattern parameter is required","INVALID_PATTERN");try{const e=w.resolve(process.cwd(),n),r=process.cwd(),o=r.endsWith(w.sep)?r:r+w.sep;if(e!==r&&!e.startsWith(o))throw new co("Search path must be within the current working directory","INVALID_PATH");const s=await Te(t,{cwd:e,ignore:ct,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),a=await Promise.all(s.map(async t=>{const n=w.join(e,t);try{return{file:t,mtime:(await I.stat(n)).mtimeMs}}catch{return{file:t,mtime:0}}}));return a.sort((e,t)=>t.mtime-e.mtime),{files:a.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof co)throw e;if(e instanceof Error)throw new co(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new co("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 lo={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=io.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`${ae.cross} Error: ${e.message}`:`${ae.cross} Error: Unknown error occurred while finding files`}},"execute")},uo=P.object({command:P.string().min(1,"Command cannot be empty"),args:P.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},P.array(P.string()).optional()),directory:P.string().optional(),timeout:P.preprocess(e=>"string"==typeof e?parseInt(e,10):e,P.number().optional())}),mo=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,o,s,a){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=o,this.stderr=s,this.duration=a}};async function executeShellCommand(e){const{command:t,args:n=[],directory:r,timeout:o=3e4}=e,s=Date.now();if(!t.trim())throw new mo("Command cannot be empty","EMPTY_COMMAND");let a;if(r){if(y.isAbsolute(r))throw new mo("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");a=y.resolve(process.cwd(),r)}else a=process.cwd();try{if(!(await I.stat(a)).isDirectory())throw new mo(`Path is not a directory: ${r}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof mo)throw e;throw new mo(`Directory does not exist or is not accessible: ${r||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:a,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((r,a)=>{let i="",c="",l=!1;const d=n.length>0?Ae([t,...n]):t,u=setTimeout(()=>{if(!l){m.kill("SIGTERM");const e=Date.now()-s;a(new mo(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",i,c,e))}},o),m=M(d,[],e);m.stdout?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>oo)return c="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void m.kill("SIGTERM");i+=t}catch(e){c+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,m.kill("SIGTERM")}}),m.stderr?.on("data",e=>{try{const t=e.toString();if(c.length+t.length>so)return void(c+="\n[Error output truncated: too large]");c+=t}catch(e){c+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),m.on("close",(e,t)=>{l=!0,clearTimeout(u);const n=Date.now()-s;0===e?r({stdout:i.trim(),stderr:c.trim(),exitCode:e,signal:t,duration:n}):a(new mo(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,t,i.trim(),c.trim(),n))}),m.on("error",e=>{l=!0,clearTimeout(u);const t=Date.now()-s;a(new mo(`Failed to start command: ${e.message}`,"START_FAILED",null,null,i.trim(),c.trim(),t))})})}catch(e){if(e instanceof mo)throw e;throw new mo(`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 go={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=uo.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`${ae.cross} Error: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`${ae.cross} Error: ${e.message}`}return`${ae.cross} Error: Unknown error occurred while executing command`}},"execute")};async function think(e){const{thought:t}=e;return`${t}`}__name(think,"think");var po={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 ho={name:"todo_write",description:"Create and manage a structured task list. Use this to track progress, organize complex tasks, and show thoroughness to the user. Create todos when tasks require multiple steps, are non-trivial, or when explicitly requested.",input_schema:{type:"object",properties:{todos:{type:"array",description:"The updated todo list",items:{type:"object",properties:{content:{type:"string",minLength:1,description:"The todo item content"},status:{type:"string",enum:["pending","in_progress","completed"],description:"The status of the todo item"},id:{type:"string",description:"Unique identifier for the todo item"}},required:["content","status","id"]}}},required:["todos"]},execute:todoWrite};async function askUserQuestion(e,t){if(!e.questions||0===e.questions.length)return JSON.stringify({error:"No questions provided"});for(let t=0;t<e.questions.length;t++){const n=e.questions[t];if(!n.question?.trim()||!n.header?.trim()||!n.options)return JSON.stringify({error:`Question ${t+1} is missing required fields (question, header, options)`});if(n.options.length<2||n.options.length>4)return JSON.stringify({error:`Question ${t+1} must have 2-4 options`});for(const e of n.options)if(!e.label?.trim()||!e.description?.trim())return JSON.stringify({error:`Question ${t+1} has an option with missing label or description`});if(n.header.length>12)return JSON.stringify({error:`Question ${t+1} header exceeds maximum length of 12 characters`})}if(!t?.onQuestionRequest)return JSON.stringify({error:"Question request callback not available"});if(t.abortSignal?.aborted)return JSON.stringify({error:"Interrupted by user"});try{const n=await t.onQuestionRequest(e);return t.abortSignal?.aborted?JSON.stringify({error:"Interrupted by user"}):JSON.stringify(n)}catch(e){return e instanceof Error?JSON.stringify({error:e.message}):JSON.stringify({error:"Failed to get user response"})}}function isErrorResponse(e){return"error"in e&&"string"==typeof e.error}function formatOutput6(e){const{result:t,params:n}=e;if(isErrorResponse(t))return`Error: ${t.error}`;if(!t.answers||0===t.answers.length)return"User declined to answer questions";const r=t.answers.filter(e=>e.selectedOptions&&Array.isArray(e.selectedOptions)&&e.selectedOptions.length>0);if(0===r.length)return"User declined to answer questions";const o=[];return r.forEach(e=>{let t=`Question ${e.questionIndex+1}`;n?.questions?.[e.questionIndex]&&(t=n.questions[e.questionIndex].question||t);const r=e.selectedOptions.join(", ");o.push(`${t} → ${r}`)}),o.join("\n")}__name(askUserQuestion,"askUserQuestion"),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput");var fo={name:"ask_user_question",description:'Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select "Type something" to provide custom text input\n- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label\n- Use multiSelect: true to allow multiple answers to be selected for a question',acceptsCallbacks:!0,input_schema:{type:"object",properties:{questions:{type:"array",description:"Questions to ask the user",items:{type:"object",properties:{question:{type:"string",description:"The complete question to ask the user. Should be clear, specific, and end with a question mark."},header:{type:"string",description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",description:'The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Type something" option, that will be provided automatically.',items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options"]}}},required:["questions"]},execute:__name(async(e,t)=>{const n=await askUserQuestion(e,{onQuestionRequest:t?.onQuestionRequest,abortSignal:t?.abortSignal});try{return formatOutput6({result:JSON.parse(n),params:e})}catch{return n}},"execute")},yo=P.object({port:P.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:P.number().int().positive().optional()}).refine(e=>void 0!==e.port&&void 0===e.pid||void 0===e.port&&void 0!==e.pid,{message:"Exactly one of port or pid must be provided"}),wo=class extends Error{static{__name(this,"KillshellError")}code;pid;port;constructor(e,t,n,r){super(e),this.name="KillshellError",this.code=t,this.pid=n,this.port=r}};function isUnixLike(){const e=process.platform;return"darwin"===e||"linux"===e}function isWindows(){return"win32"===process.platform}async function executeCommand(e,t){return new Promise((n,r)=>{const o=M(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let s="",a="";o.stdout?.on("data",e=>{s+=e.toString()}),o.stderr?.on("data",e=>{a+=e.toString()}),o.on("close",e=>{0===e?n(s.trim()):r(new Error(a.trim()||s.trim()))}),o.on("error",e=>{r(e)})})}async function findPidByPort(e){try{if(isUnixLike()){const t=(await executeCommand("lsof",["-ti",`:${e}`,"-sTCP:LISTEN"])).trim().split("\n")[0];if(!t||!/^\d+$/.test(t))return null;const n=parseInt(t,10);return isNaN(n)?null:n}if(isWindows()){const t=(await executeCommand("netstat",["-ano"])).split("\n");for(const n of t){const t=n.trim();if(!t)continue;const r=t.split(/\s+/);if(r.length<5)continue;if("LISTENING"!==r[3])continue;const o=r[1].match(/:(\d+)$/);if(!o)continue;const s=parseInt(o[1],10);if(isNaN(s)||s!==e)continue;const a=parseInt(r[r.length-1],10);if(!isNaN(a))return a}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new wo(`No process found listening on port ${e.port}`,"NO_PROCESS_FOUND",void 0,e.port);t=r}else void 0!==e.pid&&(t=e.pid);if(!t)throw new wo("Unable to determine target process","INVALID_TARGET");const r=await getProcessName(t);try{await killProcess(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new wo(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}function formatKillshellResult(e){const t=[];return t.push(`${ae.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}__name(isUnixLike,"isUnixLike"),__name(isWindows,"isWindows"),__name(executeCommand,"executeCommand"),__name(findPidByPort,"findPidByPort"),__name(getProcessName,"getProcessName"),__name(isProcessAlive,"isProcessAlive"),__name(waitForProcessTermination,"waitForProcessTermination"),__name(killProcess,"killProcess"),__name(executeKillshell,"executeKillshell"),__name(formatKillshellResult,"formatKillshellResult");var Eo={name:"kill_shell",description:"Terminates processes by port number or PID, useful for freeing occupied ports or stopping stuck development servers. Attempts graceful termination first (SIGTERM/taskkill), then forces if needed. Use with caution - terminating system processes may cause instability.",acceptsCallbacks:!0,input_schema:{type:"object",properties:{port:{type:"number",description:"Port number (1-65535) to free by terminating the listening process. Automatically finds and kills the process using this port."},pid:{type:"number",description:"Process ID to terminate directly. Use when you know the exact PID to kill."}},required:[]},execute:__name(async(e,t)=>{try{const n=yo.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?`${ae.cross} Permission denied: Process termination was not approved`:formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`${ae.cross} Error: ${e.message}`:`${ae.cross} Error: Unknown error occurred while killing process`}},"execute")},bo=["explore","plan","review","general"],ko=[{name:"explore",description:"Use this for codebase exploration, search, or understanding tasks that require multiple file operations",tools:"glob, grep, read_file, read_directory, read_multiple_files, think",systemPrompt:'You are a codebase explorer. Your prompt will specify depth level and what information is needed.\n\nTOOLS AVAILABLE:\n- glob: Find files by patterns\n- grep: Search code for keywords/patterns\n- read_file: Read specific files\n- read_directory: List directory contents\n- read_multiple_files: Read many files efficiently\n- think: Reason through findings\n\nDEPTH LEVELS:\n- quick: 1-2 files, answer the specific question only\n- medium: 3-5 files, understand the main component and context\n- thorough: 10+ files, comprehensive understanding\n\nINSTRUCTIONS:\n1. Look for "Depth: [level]" in the prompt (usually on line 2)\n2. Identify exactly what information is needed (specified in the prompt)\n3. Use only the file operations needed to get that information\n4. Stop when you have the requested information\n\nIf no depth level specified, default to "quick".\n\nRESPONSE FORMAT:\n- Provide exactly what was requested\n- Include relevant file paths and code sections\n- Match your depth to the specified level\n- Stop when done - don\'t over-explore',location:"personal",filePath:"__builtin__"}];function isReservedAgentName(e){return!!e&&bo.includes(e.toLowerCase())}function getRootAgentDir(){return w.join(T.homedir(),".commandcode","agents")}function getLocalAgentDir(){return w.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,t){try{const n=(await I.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=w.join(e,n),o=await I.readFile(r,"utf-8"),{data:s,content:a}=Ce(o),i=s.name||n.replace(".md","");if(isReservedAgentName(i))return null;let c=s.tools||"";return"*"!==c&&'"*"'!==c||(c="*"),{name:i,description:s.description||"",tools:c,systemPrompt:a.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(isReservedAgentName,"isReservedAgentName"),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents");var So=2e5;function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(1.1*t));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=1.1*estimateTextTokens(JSON.stringify(n.input)));else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/3.5;const n=.1*e.split(/\s+/).length;return Math.max(0,Math.ceil(t-n))}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>25e3}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?(estimateTokens(e),"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."):e}function calculateUsageFromResponse(e){return(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.output_tokens||0)}function sleep(e){const{delay:t,signal:n}=e;return new Promise((e,r)=>{if(n?.aborted)return r(new Error("Interrupted by user"));const o=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(o),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(function getOversizedOutputError(e,t){return"Output too large (max 25,000 tokens allowed). Try using grep or ripgrep with more specific patterns to filter results."},"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse"),__name(sleep,"sleep");var Co=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${ae.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${ae.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${ae.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${ae.warning} ${e}`)}debug(e){dlog(`[${this.prefix}] ${e}`)}};function getEnterpriseMemoryPath(){switch(v.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return y.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const e=v.homedir();return y.join(e,".commandcode","AGENTS.md")}function getProjectMemoryPaths(e){return[y.join(e,"AGENTS.md"),y.join(e,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:d(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(d(n)){t.push({type:"project",path:n,exists:!0,description:"Team-shared project instructions"});break}t.find(e=>"project"===e.type)||t.push({type:"project",path:e[0],exists:!1,description:"Team-shared project instructions"})}const o=getUserMemoryPath();return t.push({type:"user",path:o,exists:d(o),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return d(e)&&h(e).isFile()?await x.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=[],s=e.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),a=Array.from(s.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let i=s;for(const e of a){const o=e[1];let s=o;o.startsWith("~/")?s=y.join(v.homedir(),o.slice(2)):y.isAbsolute(o)||(s=y.resolve(y.dirname(t),o));const a=await loadMemoryFile(s);if(a){const t=await processImports(a,s,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(d(r)){const e=await loadMemoryFile(r);if(e){const t=await processImports(e,r);n.set(r,t)}}const o=getUserMemoryPath();if(d(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);n.set(o,t)}}const s=[y.join(e,"AGENTS.md"),y.join(e,".commandcode","AGENTS.md")];for(const e of s)if(d(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=y.isAbsolute(r)?y.dirname(r):y.dirname(y.resolve(e,r));if(t.startsWith(e)&&t!==e){const r=[];let o=t;for(;o.startsWith(e)&&o!==e;)r.push(o),o=y.dirname(o);for(const e of r.reverse()){const t=[y.join(e,"AGENTS.md"),y.join(e,".commandcode","AGENTS.md")];for(const e of t)if(d(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=y.dirname(e);return d(n)||await x.mkdir(n,{recursive:!0}),d(e)||await x.writeFile(e,"# AGENTS.md\n\n","utf-8"),new Promise((n,r)=>{const o=M(t,[e],{stdio:"inherit",shell:!0});o.on("exit",e=>{0===e?n():r(new Error(`Editor exited with code ${e}`))}),o.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),r(e)})})}async function initProjectMemory(e){const t=y.join(e,"AGENTS.md");return d(t)||await x.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(),s=getUserMemoryPath(),a=[y.join(t,"AGENTS.md"),y.join(t,".commandcode","AGENTS.md")];n.has(o)&&r.push(`# Memory from: ${o}\n\n${n.get(o)}`),n.has(s)&&r.push(`# Memory from: ${s}\n\n${n.get(s)}`);for(const e of a)if(n.has(e)){r.push(`# Memory from: ${e}\n\n${n.get(e)}`);break}for(const[e,t]of n)e===o||e===s||a.includes(e)||r.push(`# Memory from: ${e}\n\n${t}`);return r.join("\n\n---\n\n")}catch(e){return null}}__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 vo=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return w.join(T.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return xe(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const t=_SessionManager.getCurrentProjectDirName();this.projectPath=w.join(_SessionManager.getProjectsBasePath(),t),this.sessionFilePath=w.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=F("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await I.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"project_init_failed"}),context:{component:zt.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await I.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{if(0===e.length)return;const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),o={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,...t?.metadata||{}}};r.push(JSON.stringify(o)),this.lastMessageId=e}await I.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=w.join(this.projectPath,`${t}.jsonl`);try{const e=(await I.readFile(n,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let r=0;for(const n of e)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){r++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:r,totalLines:e.length}}catch(e){return console.error("Error loading messages:",e),{messages:[],corruptedLines:0,totalLines:0}}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),o=crypto.randomUUID();if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n&&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=Or(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=Or(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=w.join(this.projectPath,`${t}.jsonl`);try{const e=(await I.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=w.join(e,t);try{return(await I.stat(n)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),t=_SessionManager.getCurrentProjectDirName(),n=w.join(e,t);try{return await I.mkdir(n,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),t=w.join(_SessionManager.getProjectsBasePath(),e);try{try{await I.access(t)}catch{return[]}const e=(await I.readdir(t)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),n=[];for(const r of e){const e=r.replace(".jsonl",""),o=w.join(t,r);try{const r=await I.stat(o),s=(await I.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(s.length>0){let o="",a="";const i=JSON.parse(s[0]);i.gitBranch&&(a=i.gitBranch);for(const e of s){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}n.push({id:e,createdAt:r.birthtime.toISOString(),lastModified:r.mtime.toISOString(),firstMessage:o||"No messages",messageCount:s.length,projectPath:t,gitBranch:a||"-"})}}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=w.join(this.projectPath,`${this.sessionId}.share.json`);try{await I.writeFile(t,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=w.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await I.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=w.join(this.projectPath,`${this.sessionId}.share.json`);try{await I.unlink(e)}catch(e){}}getCheckpointsFilePath(){return w.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 I.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const o=n.findIndex(e=>e.messageId===t.messageId);-1!==o?n[o]=e:n.push(e);const s=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await I.writeFile(r,s)}else await I.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 I.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 I.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),o=e.findIndex(e=>e.messageId===t);if(-1===o)return;const s=(n?e.slice(0,o):e.slice(0,o+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await I.writeFile(r,s)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let o="";if("string"==typeof r.message.content)o=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(o+=e.text);return{messageId:r.meta.messageId||crypto.randomUUID(),content:o}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return r.length>0&&await this.saveMessages(r),r}},To=new Co("AgentExecutor");function agentToTool(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=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,a)=>{let i=null;const c=Date.now();let l=null;try{let d=getAvailableTools(e,{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}),u=Date.now();const m=10,g=[];if(a?.onFeedUpdate){const n=Or(e.name,t);i=Pr({name:e.name,input:n}),a.onFeedUpdate(i)}l=setInterval(()=>{if(a?.onFeedUpdate&&i){const e=Date.now(),t=Math.floor((e-c)/1e3);i={...i,metadata:{...i.metadata,elapsedSeconds:t}},a.onFeedUpdate(i)}},1e3);const p=await getConfiguredProvider(),h=await isOAuthEnforced();let f;p===rt&&(f=await ut.getValidAccessToken(),validateOAuthToken({token:f,provider:p}));const w=getApiBaseUrl(),E=new Bn({baseUrl:w});let b=0;const k=[];let S=t?.messages;if("string"==typeof S)try{S=JSON.parse(S)}catch(e){S=[]}if(Array.isArray(S)&&S.length>0)for(const e of S)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&k.push({role:"user",content:t})}const C={stream:!0,messages:k,max_tokens:64e3,system:e.systemPrompt,temperature:.3,tools:d,model:`anthropic:${getConfiguredModel()}`},v=await isTasteLearningEnabled(),T={[Ze]:vo.getCurrentProjectDirName(),[Xe]:v.toString(),[Ye]:h.toString()};f&&(T[Qe]=`Bearer ${f}`);const A=getEnvironmentContext(),P=await getMemoryContent([]),x=crypto.randomUUID();let I="",$=!0;const D=__name(()=>{To.debug("[Agent] Abort signal triggered, stopping immediately"),$=!1,l&&(clearInterval(l),l=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",D);try{for(;$;){if(a?.abortSignal?.aborted)throw To.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const e=await callAPIWithRetry({request:E,body:{mode:"custom-agent",config:A,memory:P,threadId:x,params:{...C,messages:k}},headers:T,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{b+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&i&&t-u>=m){const e=Math.floor((t-c)/1e3);i={...i,metadata:{...i.metadata,tokensUsed:b,elapsedSeconds:e}},a.onFeedUpdate(i),u=t}},"onTextDelta")});e.usage&&(b=calculateUsageFromResponse(e.usage));const t=e.content.filter(e=>"tool_use"===e.type);if(I=e.content.filter(e=>"server_tool_use"===e.type).length>0?processServerToolBlocks(e,a):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&&k.push({role:"assistant",content:t}),$=!1;break}const n=e.content.filter(e=>"text"!==e.type||e.text.trim().length>0);n.length>0&&k.push({role:"assistant",content:n});const r=[],o=new Set;let s=!1;for(const e of t){if(a?.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)&&a?.onPermissionRequest){if(l&&(clearInterval(l),l=null),!await a.onPermissionRequest(e.name,t)){To.debug(`Permission denied for tool: ${e.name}`),s=!0;break}l=setInterval(()=>{if(a?.onFeedUpdate&&i){const e=Date.now(),t=Math.floor((e-c)/1e3);i={...i,metadata:{...i.metadata,elapsedSeconds:t}},a.onFeedUpdate(i)}},1e3)}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(!y.isAbsolute(t)){const o=y.resolve(process.cwd(),t);n[e]=o,r=!0,To.debug(`Converted '${e}': '${t}' -> '${o}'`)}}"paths"in n&&Array.isArray(n.paths)&&(n.paths=n.paths.map(e=>"string"!=typeof e||y.isAbsolute(e)?e:(r=!0,y.resolve(process.cwd(),e)))),r?(t=n,To.debug(`Resolved input for ${e.name}: ${Or(e.name,t)}`)):To.debug(`No path resolution needed for ${e.name}: ${Or(e.name,t)}`)}if(a?.onFeedUpdate&&i){const n=Or(e.name,t);g.push({name:e.name,input:n}),g.length>3&&g.shift();const r=Date.now(),o=Math.floor((r-c)/1e3);i={...i,metadata:{isAgent:!0,status:"running",startTime:c,tokensUsed:b,elapsedSeconds:o,recentTools:[...g]}},To.debug(`Updating agent with recentTools (${g.length} tools): ${JSON.stringify(g)}`),a.onFeedUpdate(i)}const n=await executeTool(e.name,t,{abortSignal:a?.abortSignal});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const d=checkToolOutputTokensLimit(n,e.name);if(r.push({type:"tool_result",tool_use_id:e.id,content:d}),o.add(e.id),a?.onFeedUpdate&&i){const e=Date.now(),t=Math.floor((e-c)/1e3);i={...i,metadata:{isAgent:!0,status:"running",startTime:c,tokensUsed:b,elapsedSeconds:t,recentTools:[...g]}},a.onFeedUpdate(i)}To.debug(`Tool executed successfully: ${e.name}`)}catch(t){const n=t instanceof Error?t.message:"Unknown error";r.push({type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}),o.add(e.id),To.error(`Tool execution failed: ${e.name} - ${n}`)}}if(s){const e=k[k.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:k.pop()}$=!1;break}const d=[...r];k.push({role:"user",content:d})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",D)}if(l&&(clearInterval(l),l=null),a?.onFeedUpdate&&i){const e=Date.now(),t=(e-c)/1e3;i={...i,output:I||"DONE",metadata:{isAgent:!0,status:"done",startTime:c,endTime:e,tokensUsed:b,elapsedSeconds:t}},a.onFeedUpdate(i)}return I||"DONE"}catch(e){if(l&&(clearInterval(l),l=null),a?.onFeedUpdate&&i){const t=Date.now(),n=(t-c)/1e3,r=e instanceof Error?e.message:"Unknown error",o="Interrupted by user"===r||a?.abortSignal?.aborted;i={...i,output:r,metadata:{isAgent:!0,status:o?"interrupted":"error",startTime:c,endTime:t,tokensUsed:i?.metadata?.tokensUsed||0,elapsedSeconds:n}},a.onFeedUpdate(i)}throw e}},"execute")}}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:o,displayNameToToolName:s}=t;let a=[];if("*"===e.tools)a=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=s[e];if(!t&&o.has(e)&&(t=e),t){const e=o.get(t);if(e)a.push(e);else{const e=r.find(e=>e.name===t);e&&a.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=s[t];if(!e&&o.has(t)&&(e=t),e){const t=o.get(e);if(t)a.push(t);else{const t=r.find(t=>t.name===e);t&&a.push(t)}}}return a}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:o,onTextDelta:s}=e;let a=null;for(let e=0;e<5;e++){if(o?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:et.ALPHA.GENERATE,signal:o,headers:r}),a=Pe.fromReadableStream(e);s&&a.on("text",s);let i=null;a.on("error",e=>{i="AbortError"===e.name||o?.aborted?new Error("Interrupted by user"):e});const c=await a.finalMessage();if(i)throw i;return c}catch(t){if(a=t,o?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,o))throw formatAPIError(t,o);if(!isRetryableError(t)||4===e)throw formatAPIError(t,o);const n=200*Math.pow(2,e);To.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:o})}}throw a||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof Rn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof On||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 Rn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof On||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=Or(r.name,r.input),n=sr(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 Ao=new Map,Po=null;function initializeAgentManager(e){Po=e}async function loadAgentTools(){if(!Po)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Ao.clear();for(const e of ko){const t=agentToTool(e,Po);Ao.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Po);Ao.set(t.name,t)}}async function getAgentTools(){return 0===Ao.size&&await loadAgentTools(),Array.from(Ao.values())}async function getAgentTool(e){return 0===Ao.size&&await loadAgentTools(),Ao.get(e)}function isPathInTasteDirectory(e){const{filePath:t,projectRoot:n}=e,r=y.join(n,".commandcode","taste"),o=y.normalize(y.resolve(n,t)),s=y.normalize(r);return o.startsWith(s)}function getTasteFileInfo(e){const t=y.normalize(y.resolve(e)),n=y.normalize(y.join(process.cwd(),".commandcode","taste")),r=y.normalize(y.join(v.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 s=y.relative(o,t).split(y.sep);return 1===s.length?{isTaste:!0}:2===s.length?{isTaste:!0,category:s[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 xo=[Nr,qr,Jr,Qr,no,ao,lo,go,po,ho,fo,Eo],Io=[{type:"web_search_20250305",name:"web_search",max_uses:5},{type:"web_fetch_20250910",name:"web_fetch"}],$o=new Map(xo.map(e=>[e.name,e])),Do=new Set([...xo.map(e=>e.name),...Io.map(e=>e.name)]);function isAgentTool(e){return!Do.has(e)}async function executeTool(e,t,n){let r=$o.get(e);if(r||(r=await getAgentTool(e)),!r){const t=await getAgentTools(),n=[...Array.from($o.keys()),...t.map(e=>e.name)];throw new Error(`Tool "${e}" not found. Available tools: ${n.join(", ")}`)}if(("write_file"===e||"edit_file"===e)&&!0!==n?.allowTasteWrite){const e=t.filePath,n=isPathInTasteDirectory({filePath:e,projectRoot:process.cwd()});if(e&&n)throw new Error("Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system.".replace("Error: ",""))}const o=trackToolStart({toolName:e});try{let s;return s=(!$o.has(e)||!0===r.acceptsCallbacks)&&n?await r.execute(t,n):await r.execute(t),o.end({status:"success"}),s}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw o.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return o.end({status:"error",error:t}),`Error: ${e.message}`}return o.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(){return[...xo.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})),...Io]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase");var Fo={};xo.forEach(e=>{Fo[e.name]=toPascalCase(e.name)}),Io.forEach(e=>{Fo[e.name]=toPascalCase(e.name)});var Ro={};Object.entries(Fo).forEach(([e,t])=>{Ro[t]=e}),initializeAgentManager({clientTools:xo,serverTools:Io,toolsMap:$o,displayNameToToolName:Ro});var Mo=new class extends Ie{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;get observerHasRun(){return this._observerHasRun}markObserverRun(){this._observerHasRun=!0}get importHasStarted(){return this._importHasStarted}markImportStarted(){this._importHasStarted=!0}get learningComplete(){return this._learningComplete}markLearningComplete(){this._learningComplete=!0,this.emit("learning-complete")}addEvent(e){const{type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d}=e,u={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:o,label:s,sessionCount:a,promptCount:i,learningCount:c,categories:l,storage:d};this.events.unshift(u),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",u)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}};function extractLearningWithConfidence(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)\.\s+Confidence:\s*(\d+\.?\d*)/);return n?{text:n[1].trim(),confidence:parseFloat(n[2])}:null}function extractLearnings(e){const{text:t}=e;return t.split("\n").filter(e=>e.trim().startsWith("-")).map(e=>extractLearningWithConfidence({line:e})).filter(Boolean)}function compareLearnings(e){const{oldText:t,newText:n}=e,r=extractLearnings({text:t}),o=extractLearnings({text:n}),s=new Map(r.map(e=>[e.text,e.confidence])),a=[],i=[],c=[];return o.forEach(e=>{const t=s.get(e.text);void 0===t?a.push(e):e.confidence>t?i.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&c.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:a,upgraded:i,downgraded:c}}__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings");var Oo=new Co("LearningAgent"),Lo=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=3;request;projectRoot;tasteDir;sessionId;abortSignal;constructor(e){this.request=e.request,this.sessionId=e.sessionId,this.projectRoot=e.projectRoot,this.tasteDir=y.join(e.projectRoot,".commandcode","taste")}updateRequest(e){this.request=e}setAbortSignal(e){this.abortSignal=e}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)return this.pendingMessages=t,{success:!0};if(0===t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length)return{success:!0};this.isProcessing=!0;try{for(await this.runLearningLoop({messages:t}),this.lastProcessedMessageIndex=t.length-1;null!==this.pendingMessages;){const e=this.pendingMessages;this.pendingMessages=null,e.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length>0&&(await this.runLearningLoop({messages:e}),this.lastProcessedMessageIndex=e.length-1)}return{success:!0}}catch(e){const n=e instanceof Error?e.message:String(e);return dlog(`[LearningAgent] ERROR: ${n}`),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learning_pass_failed"}),context:{component:zt.LEARNING_AGENT,heading:"Learning pass failed"}}),Mo.addEvent({type:"error",message:"learning pass failed",details:n}),this.lastProcessedMessageIndex=t.length-1,{success:!1}}finally{this.isProcessing=!1}}async runLearningLoop(e){const{messages:t}=e,n=["analyzing deltas","computing embeddings","updating weights","refining patterns","processing signals","extracting features","tuning parameters","optimizing priors"],r=n[Math.floor(Math.random()*n.length)];Mo.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const o=await this.getTasteStructure(),s=t.length-this.lastProcessedMessageIndex-1,a=Math.max(20,s),i=Math.max(0,t.length-a),c=t.slice(i);let l=0,d=!1;dlog(`[LearningAgent] analyzing ${s} new messages for patterns`);const u=[{role:"user",content:`Current taste structure:\n${o}\n\nRecent conversation:\n${JSON.stringify(c,null,2)}`}];for(;l<this.maxTurns;){const e=await this.callLearningAPI({conversation:u}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.name).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),u.push({role:"assistant",content:e.content}),u.push({role:"user",content:n}),l++}l>=this.maxTurns&&Oo.warn("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Mo.addEvent({type:"no_learnings",message:"no changes to taste"}),Mo.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let o="",s="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(s=String(e.filePath||e.file_path||""),s)try{o=await c.promises.readFile(s,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const a=await executeTool(e.name,t,{allowTasteWrite:!0});let i="";if(("write_file"===e.name||"edit_file"===e.name)&&s)try{i=await c.promises.readFile(s,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){r=!0;const e=s.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:o,newText:i});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{Mo.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Mo.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Mo.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:a})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content:t instanceof Error?t.message:String(t)})}return{results:n,learningsFound:r}}validateTastePath(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(y.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 s=y.normalize(o);if(s.startsWith(".."))throw new Error(`Security: ${t} path traversal attempt detected. Attempted: ${o}`);const a=y.join(this.tasteDir,s);if(!y.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 s="write_file"===t||"edit_file"===t;if(y.isAbsolute(e)&&e.startsWith(this.tasteDir))if(s){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(y.isAbsolute(e))throw new Error(`Invalid path: Absolute path outside taste directory: ${e}`);const t=y.normalize(e);if(t.startsWith(".."))throw new Error(`Security: Path traversal attempt detected: ${e}`);if(n=t.startsWith(".commandcode/taste")||t.startsWith(".commandcode"+y.sep+"taste")?t.replace(/^\.commandcode[/\\]taste/,this.tasteDir):y.join(this.tasteDir,t),n=y.normalize(n),!n.startsWith(this.tasteDir))throw new Error(`Security: Resolved path escapes taste directory: ${e} -> ${n}`);if(s&&!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(!c.existsSync(this.tasteDir)){c.mkdirSync(this.tasteDir,{recursive:!0});const e=y.join(this.tasteDir,"taste.md");c.writeFileSync(e,"","utf-8")}}async reorganizeIfNeeded(){const e=y.join(this.tasteDir,"taste.md");if(!c.existsSync(e))return!1;const t=c.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=y.join(this.tasteDir,t),o=y.join(n,"taste.md");c.mkdirSync(n,{recursive:!0}),Mo.addEvent({type:"refactored",message:`moved: ${e.name} package`,details:`moved to ${t}/taste.md`});const s=`# ${e.name}\n${e.learnings.join("\n")}\n`;c.writeFileSync(o,s,"utf-8");const a=`# ${e.name}\nSee [${t}/taste.md](${t}/taste.md)\n`;r=r.replace(e.fullSection,a)}return c.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 c.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=c.readdirSync(t,{withFileTypes:!0});let o="";for(let e=0;e<r.length;e++){const s=r[e],a=e===r.length-1,i=a?"└── ":"├── ";if(s.isDirectory()){o+=`${n}${i}${s.name}/\n`;const e=n+(a?" ":"│ ");o+=await this.buildTree({dir:y.join(t,s.name),prefix:e})}else if("taste.md"===s.name){const e=(c.readFileSync(y.join(t,s.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${n}${i}${s.name} (${e} learnings)\n`}else o+=`${n}${i}${s.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===rt&&(o=await ut.getValidAccessToken(),validateOAuthToken({token:o,provider:n}));const s={[Ze]:vo.getCurrentProjectDirName(),[Ye]:r.toString()};o&&(s[Qe]=`Bearer ${o}`);const a=await this.getTasteTools(),i=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (model: ${i})`);const c={conversation:t,tools:a,model:i,threadId:this.sessionId};let l=0,d=null;for(;l<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:et.ALPHA.TASTE.LEARN,body:c,headers:s,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}catch(e){if(d=e instanceof Error?e:new Error(String(e)),l++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${d.message}`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_client_error"}),context:{component:zt.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),d;if(l>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:d,label:"learning_api_max_retries"}),context:{component:zt.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":l}}),d;const n=1e3*Math.pow(2,l);dlog(`[LearningAgent] retrying API call (${l}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw d||new Error("API call failed")}static async isInitialized(e){const{projectRoot:t}=e,n=y.join(t,".commandcode","taste");return c.existsSync(n)}};async function getTasteContent(){try{const e=process.cwd(),t=y.join(e,".commandcode","taste","taste.md");if(!d(t))return null;const n=await x.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 No=new Co("ContextEngine"),_o=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;callbacks;sessionManager;abortController=null;requestInterrupted=!1;contextTokensUsed=0;currentInteractionTokens=0;syncQueue=Promise.resolve();lastFileContexts=[];learningAgent;checkpointManager;constructor(e,t){const n=getApiBaseUrl();this.request=new Bn({baseUrl:n}),this.callbacks=e,this.sessionManager=new vo(t),this.learningAgent=new Lo({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Bn({baseUrl:e}),this.learningAgent.updateRequest(this.request)}createSessionStoreAdapter(){return{saveSnapshot:__name(async e=>{await this.sessionManager.saveSnapshot(e)},"saveSnapshot"),loadSnapshots:__name(async()=>this.sessionManager.loadSnapshots(),"loadSnapshots"),deleteSnapshotsAfter:__name(async e=>{await this.sessionManager.deleteSnapshotsAfter(e)},"deleteSnapshotsAfter"),getMessageAtIndex:__name(e=>this.sessionManager.getMessageAtIndex({index:e.index,messages:this.messages}),"getMessageAtIndex"),getMessageIndexById:__name(e=>this.sessionManager.getMessageIndexById({messageId:e.messageId,messages:this.messages}),"getMessageIndexById"),truncateMessagesAtIndex:__name(async e=>{const t=await this.sessionManager.truncateMessagesAtIndex({index:e.index,messages:this.messages});this.messages=t},"truncateMessagesAtIndex"),getMessageCount:__name(()=>this.sessionManager.getMessageCount({messages:this.messages}),"getMessageCount")}}setupCheckpointSessionStore(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),this.checkpointManager.runCleanup().catch(()=>{})}async interrupt(e=!1){if(this.requestInterrupted=!0,this.abortController){this.abortController.abort(),this.abortController=null,No.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)){const n=t.message.content.filter(e=>"tool_use"===e.type),r=[];if(n.length>0){const e=n.map(e=>({type:"tool_result",tool_use_id:e.id,content:"Interrupted by user",is_error:!0}));r.push(...e),No.debug(`Added tool_result blocks for ${e.length} interrupted tool calls`)}e&&r.push({type:"text",text:"Interrupted by user"}),r.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:r}))}if(e){const e=wr("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>No.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=wr(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 s=[];t&&t.length>0&&t.forEach(e=>{s.push({type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}})}),n.trim()&&s.push({type:"text",text:n});const a={role:"user",content:s},i=crypto.randomUUID(),c=this.createMessageWithMeta(a,{messageId:i});return this.addMessageAndSync(c),this.checkpointManager.createSnapshot({messageId:i}).catch(e=>No.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,o).catch(e=>No.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){No.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}async processMessages(){let e="";this.requestInterrupted=!1,this.abortController=new AbortController,this.learningAgent.setAbortSignal(this.abortController.signal);let t=!1;for(;;)try{this.checkIfInterrupted(),t||(this.initializeInteractionTokens(),t=!0);const{body:n,headers:r}=await this.prepareAPICall(),o=await this.callAPIWithRetry({body:n,headers:r});this.checkIfInterrupted(),this.updateContextUsage(o);const s=o.content.filter(e=>"tool_use"===e.type),a=o.content.filter(e=>"server_tool_use"===e.type);if(e=a.length>0?this.processServerToolBlocks(o):o.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===s.length){const t=o.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===a.length){const t=br(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>No.error(`Failed to save messages: ${e}`))}if(0!==a.length&&this.sessionManager.saveMessages(this.messages).catch(e=>No.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=wr(n);this.callbacks.onFeedUpdate(e)}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t})),this.sessionManager.saveMessages(this.messages).catch(e=>No.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=br(e);this.callbacks.onFeedUpdate(t)}const c=await this.executeToolBlocks({toolBlocks:s}),{toolResults:l,executedToolIds:d,permissionDenied:u}=c;if(u){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}const m=[...l];if(this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){m.push({type:"text",text:t});const e=wr(t);this.callbacks.onFeedUpdate(e)}}this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:m})),this.sessionManager.saveMessages(this.messages).catch(e=>No.error(`Failed to save messages: ${e}`))}catch(e){throw this.isNonRetryableError(e)&&No.debug("Request interrupted or insufficient credits"),this.formatAPIError(e)}return this.abortController=null,e}getHistory(){return[...this.messages]}async loadSession(e){const{messages:t,corruptedLines:n,totalLines:r}=await this.sessionManager.loadMessages(e);this.messages=t;try{await this.loadCheckpoints()}catch(t){No.error(`Failed to load checkpoints for session ${e}: ${t}`)}const o=this.sessionManager.reconstructFeedFromMessages(t);return No.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:o,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.messages.map(e=>e.message)}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}isRequestInProgress(){return null!==this.abortController}async compactConversation({preserveCurrentInteraction:e=!1}={preserveCurrentInteraction:!1}){const t=this.messages.length,n=this.contextTokensUsed;let r=-1;if(e)for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("user"===t.message.role){const n=t.message.content;if(!Array.isArray(n)){r=e;break}if(!n.some(e=>"tool_result"===e.type)){r=e;break}}}let o=0;const s=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],a=n.message.role;if(e&&t>=r&&-1!==r)s.push(n);else{if("user"===a){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool_result"===e.type)){o+=estimateTokens(n.message);continue}s.push(n)}else s.push(n)}else if("assistant"===a){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool_use"===e.type);for(const e of t)o+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?s.push({...n,message:{...n.message,content:r}}):o+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&s.push(n)}"user"!==a&&"assistant"!==a&&(o+=estimateTokens(n.message))}}this.messages=s,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,n-o);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:So}),{messagesRemoved:t-s.length,tokensSaved:o}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){}}))}async syncMessageToShare(e,t){try{const n=$n.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:et.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.requestInterrupted||this.abortController?.signal.aborted)throw new Error("Interrupted by user")}initializeInteractionTokens(){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message)}async prepareAPICall(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(t),t===rt&&(r=await ut.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o={tools:e,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},s={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:o,threadId:this.sessionManager.getSessionId()};No.debug(`calling API (${o.model}, ${this.messages.length} msgs, ${e.length} tools)`);const a=await isTasteLearningEnabled(),i={[Ze]:vo.getCurrentProjectDirName(),[Xe]:a.toString(),[Ye]:n.toString()};return r&&(i[Qe]=`Bearer ${r}`),{body:s,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:et.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers}),n=Pe.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.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(e))throw trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"non_retryable_api_error"}),context:{component:zt.CONTEXT_ENGINE,heading:"Non-retryable API error",code:e?.status||e?.statusCode}}),this.formatAPIError(e);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:zt.CONTEXT_ENGINE,code:e?.status||e?.statusCode,"retry.attempts":10}}),this.formatAPIError(e);const r=Math.min(n,10),o=100*Math.pow(2,r),s=Math.max(o,1e3),a=Math.min(s,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:a,signal:this.abortController?.signal})}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.requestInterrupted||this.abortController?.signal.aborted||e instanceof Rn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof Mn||401===e?.status||e instanceof On||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.requestInterrupted||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 On||403===e?.status)return e;if(e instanceof Mn||401===e?.status)return new Error('Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');const r=getSupportId();let o="Error: ";return e.message?e.message.includes("Invalid 'Authorization' header")?o+='Authentication failed. Run "cmd login" to sign in again.':(o+='Something went wrong. Type "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==r&&(o+=`\nRequest ID: ${r}`)):e.toString?o+=e.toString():o+="Unknown error occurred",new Error(o)}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 s=await this.executeSingleTool(o);t.push({type:"tool_result",tool_use_id:o.id,content:s}),n.add(o.id),isAgentTool(o.name)||this.showToolSuccess(o,s)}catch(e){const r=e instanceof Error?e.message:"Unknown error";"Interrupted by user"===r&&isAgentTool(o.name)?n.add(o.id):(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,onQuestionRequest:this.callbacks.onQuestionRequest,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=Or(e.name,e.input),n={..."edit_file"===e.name?e.input:{},permissionDenied:!0},r=kr(e.name,t,n),o=xr(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=Or(e.name,r),s=kr(e.name,o,n),a=xr(s,t);this.callbacks.onFeedUpdate(a)}showToolError(e,t){const n=Or(e.name,e.input),r="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,o=kr(e.name,n,r),s=xr(o,Ir(t));this.callbacks.onFeedUpdate(s)}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=br(t.trim());this.callbacks.onFeedUpdate(e),t=""}const e=Or(n.name,n.input),r=kr(n.name,e),o=sr(n.name)?"Found 10 results":"Content fetched",s=xr(r,o);this.callbacks.onFeedUpdate(s)}if(t.trim()){const e=br(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:So}),this.checkAndCompactIfNeeded()}async checkAndCompactIfNeeded(){const e=Math.floor(17e4);if(this.contextTokensUsed>e){No.debug(`Context tokens (${this.contextTokensUsed}) exceeded threshold (${e}), triggering automatic compaction`);try{const e=await this.compactConversation({preserveCurrentInteraction:!0});No.debug(`Automatic compaction completed: removed ${e.messagesRemoved} messages, saved ${e.tokensSaved} tokens`)}catch(e){No.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 s=await this.checkpointManager.restore({messageId:t,mode:n});return!s.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-o),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:So})),s}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots()}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}},Uo=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:o=process.env}=t;return new Promise(t=>{const s=M("/bin/bash",["-c",e],{cwd:r,env:{...o},stdio:["pipe","pipe","pipe"]});let a="",i="",c=null;n>0&&(c=setTimeout(()=>{s.kill("SIGTERM"),t({stdout:a,stderr:i+(i?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),s.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>oo)return i="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void s.kill("SIGTERM");a+=t}catch(e){i+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,s.kill("SIGTERM")}}),s.stderr?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>so)return void(i+="\n[Error output truncated: too large]");i+=t}catch(e){i+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),s.on("close",n=>{c&&clearTimeout(c),t({stdout:a.trim(),stderr:i.trim(),exitCode:n??0,command:e})}),s.on("error",n=>{c&&clearTimeout(c),t({stdout:a,stderr:i+`\n[Error: ${n.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),jo=__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"),Bo=__name(()=>{const[e,t]=_({isExecuting:!1,currentCommand:null});return{executeBash:B(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Uo(e,{timeout:3e4,cwd:process.cwd()}),o=jo(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]=xr(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]=xr(r,`Error: ${o}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution"),Wo=class extends Ie{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,t){super(),this.projectRoot=e,this.configPath=t||w.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 I.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=w.relative(this.projectRoot,e.filePath);return`${e.action}:${t}`}isTrustedPath(e){const t=w.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=w.join(this.projectRoot,".commandcode"),t=w.join(e,"settings.local.json");try{await I.mkdir(e,{recursive:!0});let n={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await I.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 I.writeFile(t,JSON.stringify(n,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const t=w.join(this.projectRoot,".commandcode"),n=w.join(t,"settings.local.json"),r=`Bash(${e.split(" ")[0]}:*)`;try{let e;await I.mkdir(t,{recursive:!0});try{const t=await I.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 I.writeFile(n,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},zo=__name((e={})=>{const[t,n]=_(null),[r,o]=_(null),[s,a]=_(!1);return j(()=>{const t=e.projectRoot||process.cwd(),r=new Wo(t);return r.on("permission-request",(t,n)=>{o(t),a(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{o(t),a(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:B(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:B(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:B(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),o(null),a(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),o(null),a(!1)}},[t]),clearSessionPermissions:B(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:B(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:B((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:B(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:s,service:t}},"usePermissions");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 Ho=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole");function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",o=!1,s="";for(let e=0;e<t.length;e++){const a=t[e];'"'!==a&&"'"!==a||o?a===s&&o?(o=!1,s=""):" "!==a||o?r+=a:(r.trim()&&n.push(r.trim()),r=""):(o=!0,s=a)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const o=n.substring(0,r),s=n.substring(r+1).trim();return{commandName:o,rawArguments:s,positionalArgs:parsePositionalArguments({input:s})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let o=t;return o=o.replace(/\$ARGUMENTS/g,n),o=o.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:o}}function loadCustomCommands(){const e=[],t=w.join(process.cwd(),".commandcode","commands"),n=w.join(T.homedir(),".commandcode","commands");function loadCommandsFromDirectory(t,n,r=""){if(l.existsSync(t))try{const o=l.readdirSync(t,{withFileTypes:!0});for(const s of o){const o=w.join(t,s.name);if(s.isDirectory())loadCommandsFromDirectory(o,n,r?`${r}/${s.name}`:s.name);else if(s.isFile()&&s.name.endsWith(".md")){const t=w.basename(s.name,".md"),a=l.readFileSync(o,"utf-8").trim();e.push({name:t,source:n,content:a,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}function isDirectoryEmpty(){try{return 0===p(process.cwd()).length}catch{return!1}}async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Bn({baseUrl:e});return await t.get({endpoint:et.ALPHA.WHOAMI})}__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),__name(isDirectoryEmpty,"isDirectoryEmpty"),__name(getAuthenticatedEntity,"getAuthenticatedEntity");var Go=["Code","Code - Insiders","VSCodium","Cursor"],qo="Code",Vo={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},Ko=__name(e=>te(e).href,"formatPathForTerminal"),Jo=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),Yo=__name(({home:e,configSegments:t,variant:n})=>y.join(e,...t,n,"User","keybindings.json"),"buildKeybindingsPath"),Qo=__name(({home:e,configSegments:t,variants:n})=>{for(const r of n){const n=Yo({home:e,configSegments:t,variant:r});if(c.existsSync(y.dirname(n)))return r}return null},"findExistingVariant"),Zo=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Xo(t.when)},"isTerminalShiftEnterBinding"),Xo=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),es=__name(e=>{const t=$e(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),ts=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),ns=__name(({error:e,content:t})=>{const n=e.message;return ts(t)&&(n.includes("Expected double-quoted property name")||n.includes("Unexpected token")||n.includes("is not valid JSON"))?"Invalid JSON: trailing comma detected. Remove the comma before the closing bracket.":n.includes("Expected")&&n.includes(",")&&n.includes("or")?"Invalid JSON: missing comma between elements.":n.includes("Unterminated string")||n.includes("Bad string")?"Invalid JSON: unterminated string. Check for missing closing quotes.":"Invalid JSON syntax. Please check the file format."},"formatJsonParseError"),rs=__name(e=>{let t="",n=!1,r=!1;for(let o=0;o<e.length;o++){const s=e[o];if(n)t+=s,r?r=!1:"\\"===s?r=!0:'"'===s&&(n=!1);else if('"'!==s){if(","===s){let t=o+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=s}else n=!0,t+=s}return t},"removeTrailingCommas"),os=__name(e=>{try{const t=$e(e),n=rs(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:ns({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),ss=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:Ko(t)}),"createSuccessResult"),as=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:Ko(t)}),"createErrorResult"),is=__name(()=>{const e=v.homedir(),t=v.platform();if(process.env.VSCODE_PORTABLE)return y.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const n=Jo(t);if(!n)return Yo({home:e,configSegments:[".config"],variant:qo});const r=Qo({home:e,configSegments:n,variants:Go});return Yo({home:e,configSegments:n,variant:r??qo})},"getVSCodeKeybindingsPath"),cs=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)Zo(n)&&(n.command===Vo.command&&n.args?.text===Vo.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),ls=__name(e=>{try{if(!c.existsSync(e)){const t=y.dirname(e);return c.existsSync(t)||c.mkdirSync(t,{recursive:!0}),{rawContent:"",keybindings:[]}}const t=c.readFileSync(e,"utf-8");if(es(t))return{rawContent:t,keybindings:[]};const n=os(t.trim());return n.success?Array.isArray(n.data)?{rawContent:t,keybindings:n.data}:as({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:e}):as({message:`Failed to parse existing VSCode key bindings: ${n.error}`,keybindingsPath:e})}catch(t){const n=t instanceof Error?t.message:"Unknown error";return as({message:`Failed to read keybindings file: ${n}`,keybindingsPath:e})}},"readKeybindingsFile"),ds=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(Vo,null,2);if(es(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return as({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const o=e.lastIndexOf("}",r);return-1===o?as({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,o+1)+",\n"+n+e.substring(o+1)},"generateNewContent");function setupVSCodeTerminal(){const e=is();try{const t=ls(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,o=cs(r);if(o.hasConflicting)return as({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(o.hasCompatible)return ss({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const s=ds({rawContent:n,keybindingsPath:e});return"string"!=typeof s?s:(c.writeFileSync(e,s,"utf-8"),ss({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return as({message:`Failed to configure VSCode key binding: ${t instanceof Error?t.message:"Unknown error"}`,keybindingsPath:e})}}function isVSCodeTerminal(){return"vscode"===process.env.TERM_PROGRAM}__name(setupVSCodeTerminal,"setupVSCodeTerminal"),__name(isVSCodeTerminal,"isVSCodeTerminal");var us={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return us[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(e=process.cwd()){const t=xe(e);return y.join(T.homedir(),".commandcode","projects",t)}function getGlobalProjectSettingsPath(e=process.cwd()){return y.join(getGlobalProjectSettingsDir(e),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await x.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(e,t=process.cwd()){try{const n=getGlobalProjectSettingsPath(t),r=y.dirname(n);await x.mkdir(r,{recursive:!0}),await x.writeFile(n,JSON.stringify(e,null,2))}catch(e){const t=e instanceof Error?e.message:String(e);dlog("Error saving global project settings:",e),Mo.addEvent({type:"error",message:`Failed to save global project settings: ${t}`})}}async function loadLocalProjectSettings(e=process.cwd()){try{const t=y.join(e,".commandcode","settings.local.json"),n=await x.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function loadMergedProjectSettings(e=process.cwd()){try{const t=mergeSettings(await loadGlobalProjectSettings(e),await loadLocalProjectSettings(e)),n=t.tasteOnboarding,r=n?.learnedSessions?.["claude-code"]?.length||0;return dlog(`[Config] project settings loaded (taste: ${n?.completed?"complete":n?.skipped?"skipped":"pending"}, learned: ${r} sessions)`),t}catch(e){return dlog("[Settings] error loading",e),{}}}function mergeSettings(e,t){const n={...e};return t.tasteOnboarding&&(n.tasteOnboarding={...e.tasteOnboarding,...t.tasteOnboarding},(e.tasteOnboarding?.learnedSessions||t.tasteOnboarding?.learnedSessions)&&(n.tasteOnboarding.learnedSessions={...e.tasteOnboarding?.learnedSessions,...t.tasteOnboarding?.learnedSessions})),n}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName,"getProjectDirName"),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings");var ms=y.join(v.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=f(e,{encoding:"utf8"}),n=De.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(e,t){const n=[];try{await x.access(e)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const r=await x.readdir(e);for(const o of r){if(!/^\d{4}$/.test(o))continue;const r=y.join(e,o);if(!(await x.stat(r)).isDirectory())continue;const s=await x.readdir(r);for(const e of s){if(!/^\d{2}$/.test(e))continue;const s=y.join(r,e);if(!(await x.stat(s)).isDirectory())continue;const a=await x.readdir(s);for(const r of a){if(!/^\d{2}$/.test(r))continue;const a=y.join(s,r);if(!(await x.stat(a)).isDirectory())continue;t?.({phase:"scanning",totalFiles:n.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${e}/${r}`});const i=(await x.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(e=>y.join(a,e));n.push(...i)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return n}async function processFilesInBatches(e,t,n=10,r){const o=[];for(let s=0;s<e.length;s+=n){const a=e.slice(s,s+n),i=await Promise.all(a.map(t));for(const e of i)null!==e&&o.push(e);r?.(Math.min(s+n,e.length),e.length)}return o}async function findCodexSessions(e,t,n=0){const r=e||process.cwd(),o=[];dlog(`[Codex] scanning for project: ${r}`);const s=await findAllSessionFiles(ms,t);if(0===s.length)return dlog("[Codex] no session files found"),t?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${s.length} session files to scan`),t?.({phase:"reading",totalFiles:s.length,processedFiles:0,matchedSessions:0});let a=0;const i=await processFilesInBatches(s,async e=>{const t=await readSessionMeta(e);if(!t)return null;if(t.cwd===r)try{const n=await x.stat(e),r=y.basename(e,".jsonl");return{id:t.id||r,filePath:e,createdAt:new Date(t.timestamp||n.birthtime),lastModified:n.mtime,messageCount:0,agent:"codex",projectDir:t.cwd}}catch{return null}return null},10,(e,n)=>{a=o.length,t?.({phase:"reading",totalFiles:n,processedFiles:e,matchedSessions:a})});o.push(...i);const c=n>0?o.slice(0,n):o;return dlog(`[Codex] matched ${c.length} sessions for project`),t?.({phase:"complete",totalFiles:s.length,processedFiles:s.length,matchedSessions:c.length}),c.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await x.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=!0===e?.demoShown;if(isOnboardingDone(e))return dlog("[Onboarding] "+(e?.skipped?"user skipped":"already completed")),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!0,agentSessions:[],demoShown:t};const n=await findNewSessions(e?.learnedSessions||{}),r=(n["claude-code"]?.length||0)+(n.codex?.length||0);return r>0?(dlog(`[Onboarding] found ${r} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:r,hasTasteContent:!0,agentSessions:buildAgentSessionsList(n),demoShown:t}):t?(dlog("[Onboarding] no new sessions to learn from"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t}):(dlog("[Onboarding] first time user, will show demo"),{shouldTrigger:!0,reason:"no_sessions",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:t})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[],demoShown:!1}}}async function getSessionFilesFromDir(e){try{return(await x.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(e){const t={},n=e["claude-code"]||[],r=e.codex||[];try{const e=y.join(v.homedir(),".claude","projects");await x.access(e);const r=getProjectDirName(process.cwd()),o=(await x.readdir(e)).filter(e=>e===r);for(const r of o){const o=y.join(e,r);if((await x.stat(o)).isDirectory()){const e=await getSessionFilesFromDir(o);e.length>0&&(t["claude-code"]=e.filter(e=>!n.includes(e)))}}dlog(`[Sessions] claude-code: ${t["claude-code"]?.length||0} new, ${n.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(t.codex=e.filter(e=>!r.includes(e)));dlog(`[Sessions] codex: ${t.codex?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}return t}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0,await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function markDemoShown(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.demoShown=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:o}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),o(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(markDemoShown,"markDemoShown"),__name(triggerTasteOnboarding,"triggerTasteOnboarding");var gs="# Taste (Continuously Learned by CommandCode.ai)",ps=/^(\s*)# Taste \(Continuously Learned by CommandCode\)/;function migrateHeader(e){const{content:t}=e;return ps.test(t)?t.replace(ps,`$1${gs}`):t}__name(migrateHeader,"migrateHeader");var hs=class{static{__name(this,"TasteManager")}static async initializeProject(){const e=process.cwd(),t=y.join(e,".commandcode","taste");await x.mkdir(t,{recursive:!0});const n=y.join(t,"taste.md");try{await x.access(n);const e=await x.readFile(n,"utf-8"),t=migrateHeader({content:e});t!==e&&await x.writeFile(n,t,"utf-8")}catch{await x.writeFile(n,gs+"\n\n")}}static async isInitialized(){const e=process.cwd(),t=y.join(e,".commandcode","taste");try{return await x.access(t),!0}catch{return!1}}},fs=__name(()=>w.join(T.homedir(),".commandcode","agents"),"getRootAgentDir"),ys=__name(()=>w.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),ws=__name(({config:e,onSaveComplete:t,viewOnly:n=!1})=>{const[r,o]=_("idle"),[s,a]=_(""),i=[...xo.map(e=>e.name),...Io.map(e=>e.name)],c=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void a("Agent configuration is incomplete");o("saving");try{const n="personal"===e.location?fs():ys();await I.mkdir(n,{recursive:!0});const r=`${e.agentType}.md`,o=w.join(n,r),s=Array.from(e.selectedTools).map(e=>Fo[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===i.length?'"*"':JSON.stringify(s),c=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await I.writeFile(o,c,"utf-8"),t(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");V((e,t)=>{n||!t.return||"idle"!==r&&"error"!==r||c()});const l=Array.from(e.selectedTools).map(e=>Fo[e]||e).join(", "),d="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return N.createElement(z,{flexDirection:"column",gap:1},N.createElement(z,{flexDirection:"column"},N.createElement(z,{gap:1},N.createElement(H,{color:"white",bold:!0},"Name:"),N.createElement(H,{color:"gray"},e.agentType)),N.createElement(z,{gap:1},N.createElement(H,{color:"white",bold:!0},"Location:"),N.createElement(H,{color:"gray"},d)),N.createElement(z,{gap:1},N.createElement(H,{color:"white",bold:!0},"Tools:"),N.createElement(H,{color:"gray"},0===e.selectedTools.size?"None":e.selectedTools.size===i.length?"*":l))),N.createElement(z,{gap:1},N.createElement(H,{color:"white",bold:!0},"Description"),N.createElement(H,{color:"gray"},"(Tells ","Command Code"," when to use this agent):")),N.createElement(H,{color:"gray"},e.ccToolDefinition),N.createElement(z,{gap:1},N.createElement(H,{color:"white",bold:!0},"System Prompt:")),N.createElement(H,{color:"gray"},e.sysPrompt),!n&&N.createElement(z,{marginTop:1},"idle"===r&&N.createElement(z,{gap:1},N.createElement(H,{color:"green",dimColor:!0},"Press"),N.createElement(H,{color:"green",bold:!0},"Enter"),N.createElement(H,{color:"green",dimColor:!0},"to save • Esc to cancel")),"saving"===r&&N.createElement(H,{color:"yellow"},"Saving agent..."),"saved"===r&&N.createElement(H,{color:"green"},"✓ ",s),"error"===r&&N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"red"},"✗ Error: ",s),N.createElement(H,{color:"gray"},"Press Enter to retry"))))},"AgentSummary"),Es=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=_("menu"),a=[...xo.map(e=>e.name),...Io.map(e=>e.name)];let i=new Set;if("*"===e.tools||'"*"'===e.tools)i=new Set(a);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>Ro[e]||e);i=new Set(t)}const c={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:i},l=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect");if(V((e,n)=>{n.escape&&("menu"===o?t():s("menu")),n.return&&"view"===o&&s("menu")}),"view"===o)return N.createElement(z,{flexDirection:"column"},N.createElement(ws,{config:c,onSaveComplete:()=>s("menu"),viewOnly:!0}),N.createElement(z,{marginTop:1},N.createElement(H,{color:"gray"},"Press Enter to go back")));if("edit"===o)return N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"yellow"},"Edit functionality coming soon..."),N.createElement(H,{color:"gray"},"Press Esc to go back"));if("delete"===o){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],o=__name(async r=>{if("confirm-delete"===r.value)try{await I.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return N.createElement(z,{flexDirection:"column",gap:1},N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"red"},"Delete agent"),N.createElement(H,{color:"gray"},"Are you sure you want to delete the agent ",e.name,"?")),N.createElement(z,null,N.createElement(Fe,{items:r,onSelect:o,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>N.createElement(H,{color:e?"white":"gray"},` ${t}`)})))}return N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"white",bold:!0},e.name),N.createElement(z,{marginTop:1},N.createElement(Fe,{items:l,onSelect:d,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:"white"},e?">":" "),itemComponent:({isSelected:e,label:t})=>N.createElement(H,{color:e?"white":"gray"},` ${t}`)})),N.createElement(z,{marginTop:1},N.createElement(H,{color:"gray"},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails"),bs=__name(({handleSelect:e,createdAgentName:t})=>{const[n,r]=_([]),[o,s]=_([]),[a,i]=_([]),[c,l]=_(!0),[d,u]=_(!1),[m,g]=_(null),[p,h]=_(!1),f=__name(()=>w.join(T.homedir(),".commandcode","agents"),"getRootAgentDir"),y=__name(()=>w.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),E=__name(async(e,t)=>{try{u(!1);const n=(await I.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(n.map(async n=>{try{const r=w.join(e,n),o=await I.readFile(r,"utf-8"),{data:s,content:a}=Ce(o);let i=s.tools||"";return"*"!==i&&'"*"'!==i||(i="*"),{name:s.name||n.replace(".md",""),description:s.description||"",tools:i,sysPrompt:a.trim(),location:t,filePath:r}}catch(e){return console.error(`Error loading agent from ${n}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");j(()=>{__name(async()=>{l(!0);const[e,t]=await Promise.all([E(f(),"personal"),E(y(),"project")]),n=ko.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));r(e),s(t),i(n),l(!1)},"loadAgents")()},[d]);const b=[{label:"Create new agent",value:"create_new_agent"}];n.forEach(e=>{b.push({label:e.name,value:e.filePath})}),o.forEach(e=>{b.push({label:e.name,value:e.filePath})});const k=n.length+o.length,S=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...n,...o].find(e=>e.filePath===t.value);e&&(g(e),h(!0))}},"handleAgentSelect");if(c)return N.createElement(H,{color:"gray"},"Loading agents...");if(p&&m){const e=m.filePath.startsWith("__builtin__:");return N.createElement(Es,{agent:m,onBack:()=>{h(!1),g(null)},setRevalidateAgent:u,isReadOnly:e})}const C=__name(({isSelected:e,label:t})=>{const r=b.find(e=>e.label===t),s=r?.value||"",a=n[0]?.filePath===s,i=o[0]?.filePath===s;return N.createElement(z,{flexDirection:"column"},a&&n.length>0&&N.createElement(z,{marginTop:1},N.createElement(H,{color:"gray",bold:!0},"User agents")),i&&o.length>0&&N.createElement(z,{marginTop:1},N.createElement(H,{color:"gray",bold:!0},"Project agents")),N.createElement(z,null,N.createElement(H,{color:"white"},e?">":" "),N.createElement(H,{color:e?"white":"gray"}," ",t)))},"CustomItemComponent");return N.createElement(z,{flexDirection:"column"},N.createElement(z,{marginBottom:1},N.createElement(H,{color:"white",bold:!0},"Agents"),k>0?N.createElement(H,{color:"gray"}," ","(",k," agent",k>1?"s":"",")"):N.createElement(H,{color:"gray"}," (No custom agents)")),t&&N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(H,{color:"green",dimColor:!0},"Created agent: ",t)),N.createElement(Fe,{items:b,onSelect:S,indicatorComponent:()=>null,itemComponent:C}),a.length>0&&N.createElement(z,{flexDirection:"column",marginTop:1},N.createElement(H,{color:"gray",bold:!0},"Default agents"),a.map(e=>N.createElement(H,{key:e.filePath,color:"gray"}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),N.createElement(z,{flexDirection:"column",marginTop:1},N.createElement(H,{color:"gray"},"Create specialized subagents that Command Code can delegate to."),N.createElement(H,{color:"gray"},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents"),ks=__name(({onSelect:e})=>N.createElement(Fe,{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})=>N.createElement(H,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>N.createElement(H,{color:e?"white":"gray"},` ${t}`)}),"LocationSelector"),Ss=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:a,onAgentTypeSubmit:i,onSysPromptSubmit:c,onCCToolDefinitionSubmit:l})=>{const[d,u]=_(!1),[m,g]=_(!1),p=B(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(u(!0),t.isPasteEnd){u(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),h=B(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||m){if(!m||t.isPasteEnd){if(m&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}a(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?a(e):t.cleanedContent&&a(t.cleanedContent))}},[m,a]);return"agentType"===e?N.createElement(N.Fragment,null,N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"white"},"Enter a unique identifier for your agent:"),t&&(Object.values(Fo).some(e=>xe(e)===xe(t))||Object.keys(Fo).some(e=>xe(e)===xe(t)))&&N.createElement(H,{color:"red"},"⚠ This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(xe(t))&&N.createElement(H,{color:"red"},"⚠ This name is reserved. Reserved names:"," ",bo.join(", "))),N.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=xe(t);Object.values(Fo).some(t=>xe(t)===e)||Object.keys(Fo).some(t=>xe(t)===e)||isReservedAgentName(e)||i()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?N.createElement(N.Fragment,null,N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"white"},"Enter the system prompt for your agent:"),N.createElement(H,{color:"gray"},"Be comprehensive for best results.")),N.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&c()},onChange:p,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?N.createElement(N.Fragment,null,N.createElement(H,{color:"white"},"When should ","Command Code"," use this agent?"),N.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&l()},onChange:h,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow"),Cs=__name(({onSelect:e})=>N.createElement(Fe,{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})=>N.createElement(H,{color:e?"white":"gray"},e?">":" "),itemComponent:({isSelected:e,label:t})=>N.createElement(H,{color:e?"white":"gray"},` ${t}`)}),"MethodSelector"),vs=["·","○","◇","☆","✧","☆","◇","○","⌘"],Ts=[8,5,4,4,4,4,4,5,20],As=[5,4,4,4,4,4,5],Ps=__name(e=>{const t=e%88;let n=0;for(let e=0;e<Ts.length;e++)if(n+=Ts[e],t<n)return vs[e];const r=t-58;n=0;for(let e=0;e<As.length;e++)if(n+=As[e],r<n)return vs[7-e];return vs[0]},"getWaveSymbol"),xs=["#8A6BA3","#B799E6","#E4CCFF","#FFFFFF","#E4CCFF","#B799E6","#8A6BA3"];function ShimmerText({text:e}){const[t,n]=_(0);j(()=>{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<xs.length?xs[n]:"#B799E6"},"getCharColor");return N.createElement(H,null,e.split("").map((e,t)=>N.createElement(H,{key:t,color:r(t)},e)))}function CMDIcon(){const[e,t]=_(0);return j(()=>{const e=setInterval(()=>{t(e=>(e+1)%88)},15);return()=>clearInterval(e)},[]),N.createElement(H,{color:"#E4CCFF",bold:!0},Ps(e)+" ")}__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon");var Is=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=_(0),s=getTerminalWidth();function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}j(()=>{if(r===n)return;const e=n-r,t=Math.max(1,Math.ceil(Math.abs(e)/20)),s=e>0?t:-t,a=setInterval(()=>{o(e=>{const t=e+s;return s>0&&t>=n||s<0&&t<=n?n:t})},30);return()=>clearInterval(a)},[n,r]),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");const a=s>70,i=s>40&&s<=70;return N.createElement(z,{width:s,height:1,paddingLeft:0,marginLeft:0},N.createElement(CMDIcon,null),N.createElement(z,{marginRight:1},N.createElement(ShimmerText,{text:e})),a?N.createElement(N.Fragment,null,N.createElement(z,{columnGap:1},N.createElement(H,{dimColor:!0},`(${formatTime3(t)}`),N.createElement(H,{dimColor:!0},"•"),N.createElement(H,{color:"gray"},ae.arrowDown),N.createElement(H,{dimColor:!0},`${formatToken(Math.round(r))}`),N.createElement(H,{dimColor:!0},"•"),N.createElement(z,{columnGap:1},N.createElement(H,{bold:!0,color:"gray"},"esc"),N.createElement(H,{dimColor:!0},"to interrupt)")))):i?N.createElement(z,{columnGap:1},N.createElement(H,{dimColor:!0},`(${formatToken(Math.round(r))})`)):N.createElement(N.Fragment,null))},"Status"),$s=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,a]=_(!1),[i,c]=_(0),l=B(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(a(!0),n.isPasteEnd){a(!1);const e=await detectClipboardText();return void(e?(c(e=>e+1),t(e)):n.cleanedContent&&(c(e=>e+1),t(n.cleanedContent)))}},[s,t]);return N.createElement(z,{flexDirection:"column"},r?N.createElement(z,null,N.createElement(CMDIcon,null),N.createElement(H,{color:"white"},"Generating agent from description...")):N.createElement(TextInput,{key:i,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:l,onSubmit:()=>{0!==e.trim().length&&n()}}),o&&N.createElement(z,{marginTop:1},N.createElement(H,{color:"red"},`${ie.warning} ${o}`)))},"RecommendedFlow"),Ds=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=_(!1),[a,i]=_(0),c=W(()=>[...xo.map(e=>e.name),...Io.map(e=>e.name)],[]),l=W(()=>[{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=W(()=>{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]":"[ ]"} ${Fo[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 V((e,c)=>{if(c.upArrow)i(e=>{const t=e-1;return t<0?m.length-1:t});else if(c.downArrow)i(e=>{const t=e+1;return t>=m.length?0:t});else if(c.return||" "===e){const e=m[a];if(e){const a=d[e.value];if(!a)return;"continue"===a.type?r():"toggle"===a.type?(s(!o),i(0)):"category"===a.type?n(a.value):"tool"===a.type&&t(a.value)}}}),N.createElement(z,{flexDirection:"column"},u.map((e,t)=>{const n=m.findIndex(t=>t.value===e.value),r=-1!==n&&n===a;if("divider"===e.type)return N.createElement(z,{key:`divider-${t}`},N.createElement(H,{color:"gray"}," ",e.label));if("spacer"===e.type)return N.createElement(z,{key:`spacer-${t}`,height:1});if("label"===e.type)return N.createElement(z,{key:`label-${t}`},N.createElement(H,{color:"gray"}," ",e.label));const o="continue"===e.type;return N.createElement(z,{key:`item-${t}`},N.createElement(H,{color:r?"white":"gray",bold:o&&r},r?">":" "," ",e.label))}),N.createElement(z,{marginTop:1},e.size===c.length&&N.createElement(H,{color:"gray"},"All tools selected"),e.size>0&&e.size<c.length&&N.createElement(H,{color:"gray"},e.size," tools selected"),0===e.size&&N.createElement(H,{color:"gray"},"No tools selected")))},"ToolsSelector"),Fs=__name(({onComplete:e})=>{const[t,n]=_("location"),[r,o]=_(!1),[s,a]=_(null),[i,c]=_("agentType"),l=W(()=>[...xo.map(e=>e.name),...Io.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(l)}),"getInitialConfig"),[u,m]=_(d()),g=__name(t=>{n("location"),c("agentType"),m(d()),e(t)},"resetToDefaults"),p=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===u.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===i)return"Agent type (identifier)";if("sysPrompt"===i)return"System prompt";if("ccToolDefinition"===i)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),h=__name(e=>{m({...u,location:e}),n("method")},"handleLocationSelect"),f=__name(e=>{m({...u,method:e}),n("configuration")},"handleMethodSelect"),y=__name(async()=>{try{a(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===rt&&(r=await ut.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const s={[Ye]:t.toString()};r&&(s[Qe]=`Bearer ${r}`);const i=getApiBaseUrl(),c=new Bn({baseUrl:i}),l=await c.post({headers:s,endpoint:et.ALPHA.AGENT.GENERATE,body:{description:u.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});m({...u,agentType:xe(l.agentName),sysPrompt:l.systemPrompt,ccToolDefinition:l.toolDescription}),n("tools")}catch(e){e instanceof Rn&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?a(mt):a("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),w=__name(()=>{m({...u,agentType:xe(u.agentType)}),c("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{c("ccToolDefinition")},"handleManualSysPromptSubmit"),b=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),S=__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 N.createElement(z,{flexDirection:"column",gap:1},N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"white",bold:!0},"Create new agent"),N.createElement(H,{color:"gray"},p())),N.createElement(z,null,"location"===t&&N.createElement(ks,{onSelect:h}),"method"===t&&N.createElement(Cs,{onSelect:f}),"configuration"===t&&"recommended"===u.method&&N.createElement($s,{description:u.recommendedMethodDescription,onChange:e=>m({...u,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:y}),"configuration"===t&&"manual"===u.method&&N.createElement(z,{flexDirection:"column",gap:1},N.createElement(Ss,{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&&N.createElement(Ds,{selectedTools:u.selectedTools,onToggleTool:S,onToggleCategory:C,onComplete:k}),"summary"===t&&N.createElement(ws,{config:u,onSaveComplete:g})))},"AgentNew"),Rs=__name(({onCancel:e})=>{const[t,n]=_(null),[r,o]=_(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return V((t,n)=>{n.escape&&e()}),N.createElement(z,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:"gray",borderStyle:"single",flexDirection:"column"},null===t&&N.createElement(bs,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&N.createElement(Fs,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig"),Ms=__name(({messages:e})=>0===e.length?null:N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(z,{marginBottom:0},N.createElement(H,{color:"#D97706",dimColor:!0},"Queued (",e.length,")")),e.map((e,t)=>N.createElement(z,{key:t},N.createElement(H,{dimColor:!0},ie.pointerSmall," "),N.createElement(H,{dimColor:!0},e.length>80?`${e.substring(0,80)}...`:e)))),"QueuedMessages");function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedImages:n,detectedContent:r,setInput:o,setDetectedImages:s,setDetectedContent:a,incrementInputKey:i}=e,c=U(!1),l=U(""),d=U(null),u=U(""),m=B(async(e,t)=>{let c=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectClipboardImage();if(l){const e=`[Image#${n.length+1}]`;return s(e=>[...e,l]),o(t+e),void i()}let d=c;if(!d.trim()){const e=await detectClipboardText();d=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(d){if(d.length>300){const e=`[Text#${r.length+1}]`;a(e=>[...e,d]),o(t+e)}else o(t+d);i()}},[n.length,r.length,s,a,o,i]),g=B(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(c.current){const e=l.current,t=u.current;l.current="",u.current="",c.current=!1,d.current=null,e&&await m(e,t)}},500)},[m]);return{handlePaste:B(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return c.current&&(c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)),await m(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!c.current)return c.current=!0,u.current=n.textBeforePaste??t,l.current=n.pastedContent??n.cleanedContent,g(),!0;if(c.current&&!n.isPasteEnd)return void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current)),g(),!0;if(c.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?l.current=n.pastedContent:n.cleanedContent&&(l.current=accumulateDelta(n.cleanedContent,l.current,u.current));const e=l.current,t=u.current;return l.current="",u.current="",c.current=!1,await m(e,t),!0}return!(!n.isPasteEnd||n.isPasteStart||c.current)},[t,m,g]),resetPasteState:B(()=>{c.current=!1,l.current="",u.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:B(()=>c.current,[])}}__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste");var Os=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear (reset, new)",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.COMPACT="/compact",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.TERMINAL_SETUP="/terminal-setup",e))(Os||{}),Ls=[{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/memory",description:"Manage Command Code memory"},{command:"/resume",description:"Resume a past conversation"},{command:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{command:"/clear (reset, new)",description:"Clear the conversation history"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/agents",description:"Manage agent configurations"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/model",description:"Switch between Command Code models"},{command:"/compact",description:"Compact the conversation history"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/exit",description:"Exit the REPL"},{command:"/help",description:"Show available shortcuts"},{command:"/terminal-setup",description:"Setup VSCode keybindings"}];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 Ns=__name(({onSelectCommand:e,onClose:t,searchQuery:n=""})=>{const[r,o]=_(0),[s,a]=_(0),{stdout:i}=J(),c=i?.columns??80,l=Math.max(20,c-22-2-1-2),d=W(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...Ls.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!n)return e;const t=n.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let o=0;return n.startsWith("/"+t)?o+=100:n.includes(t)&&(o+=50),r.includes(t)&&(o+=25),{...e,score:o}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[n]),u=W(()=>{const e=s,t=Math.min(e+8,d.length);return d.slice(e,t)},[d,s]);return j(()=>{o(0),a(0)},[n]),V((n,i)=>{if(i.escape)t();else if(i.upArrow)o(e=>{const t=Math.max(0,e-1);return t<s&&a(t),t});else if(i.downArrow)o(e=>{const t=Math.min(d.length-1,e+1);return t>=s+8&&a(Math.max(0,t-8+1)),t});else if(i.return){const t=d[r];return void(t&&e(t.command))}}),0===d.length?N.createElement(z,{flexDirection:"column",paddingLeft:2},N.createElement(H,{color:"dim"},"No commands found")):(d.length,N.createElement(z,{flexDirection:"column",paddingLeft:1},N.createElement(z,{columnGap:2},N.createElement(z,{flexDirection:"column",width:22},u.map((e,t)=>{const n=s+t;return N.createElement(H,{key:n,color:r===n?"white":"dim",wrap:"truncate"},e.command)})),N.createElement(z,{flexDirection:"column"},u.map((e,t)=>{const n=s+t;return N.createElement(H,{key:n,color:r===n?"white":"dim",wrap:"truncate"},truncateText({text:e.description,maxWidth:l}))})))))},"CommandMenu"),_s=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?"red":e>=70?"yellow":"dim","getColor"),o=`context: ${n}% left before auto-compact`;return N.createElement(z,{paddingRight:1},N.createElement(H,{color:r(t)},o))},"ContextUsage");function loadGitignore(e){const t=Re(),n=k(e,".gitignore");if(d(n))try{const e=u(n,"utf8");t.add(e)}catch{}return t.add(".git"),t}__name(loadGitignore,"loadGitignore");var Us=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[r,o]=_(process.cwd()),[s,a]=_([]),[i,c]=_(0),[l,d]=_(0),u=n.trim()?15:10,m=B((e,t=process.cwd())=>{if(!e.trim())return[];const n=loadGitignore(t);if(e.endsWith("/")){const r=k(t,e);try{const e=p(r),o=[];return e.forEach(e=>{const s=k(r,e);try{const e=h(s),r=E(t,s);if(n.ignores(r))return;o.push({name:r,path:s,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()||"",s=k(t,r.join("/"));try{const e=p(s),r=[],a=o.toLowerCase();return e.forEach(e=>{const i=e.toLowerCase();if(!o||i.includes(a)){const o=k(s,e);try{const e=h(o),s=E(t,o);if(n.ignores(s))return;r.push({name:s,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(),s=__name((e,a=0)=>{if(!(a>8))try{p(e).forEach(i=>{const c=k(e,i);try{const e=h(c),l=E(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&&s(c,a+1)}catch(e){}})}catch(e){}},"searchRecursively");return s(t),r.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),s=n===o,a=r===o;if(s&&!a)return-1;if(!s&&a)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=B(e=>{try{const t=p(e),n=[],r=process.cwd(),o=loadGitignore(r);"/"!==e&&n.push({name:"..",path:b(e),isDirectory:!0}),t.forEach(t=>{const s=k(e,t);try{const e=h(s),a=E(r,s);if(o.ignores(a))return;n.push({name:t,path:s,isDirectory:e.isDirectory()})}catch{}}),n.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),a(n),c(0),d(0)}catch{}},[]);j(()=>{if(n.trim()){const e=m(n);a(e),c(0),d(0)}else g(r)},[r,g,n,m]),V((r,a)=>{if(a.escape)t();else if(a.upArrow)c(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t});else if(a.downArrow)c(e=>{const t=Math.min(s.length-1,e+1);return t>=l+u&&d(t-u+1),t});else{if(a.rightArrow){const e=s[i];if(!e)return;return void(e.isDirectory&&!n.trim()&&o(C(e.path)))}if(a.return){const t=s[i];if(!t)return;return void e(t.path)}}});const f=s.slice(l,l+u);return N.createElement(z,{flexDirection:"column",paddingLeft:1},N.createElement(z,{marginBottom:1,flexDirection:"column"},N.createElement(H,{color:"dim"},n.trim()?`Searching for: "${n}"`:`Files: ${r}`),N.createElement(H,{color:"dim"},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===f.length?N.createElement(H,{color:"dim"},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):f.map((e,t)=>{const n=l+t,r=e.name,o=n===i;return N.createElement(H,{key:e.path,color:o?"green":"dim"},e.isDirectory?`${r}/`:r)}))},"FileList"),js=__name(()=>{const[e,t]=_("continuous learning"),n=U([]),r=U(0),o=U(null),s=U(!1);j(()=>{const e=__name(e=>"analyzing"===e.type?(s.current=!0,n.current=[],r.current=0,o.current&&(clearTimeout(o.current),o.current=null),void t(e.message)):s.current&&"analyzed"!==e.type?void n.current.push(e):"analyzed"===e.type?(s.current=!1,void(n.current.length>0?(r.current=0,a()):t("continuous learning"))):void 0,"handleNewEvent"),a=__name(()=>{if(r.current>=n.current.length)return t("continuous learning"),void(n.current=[]);const e=n.current[r.current];t(e.message);const s="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;o.current=setTimeout(()=>{r.current++,a()},s)},"cycleThroughNextEvent");return Mo.on("new-event",e),()=>{Mo.off("new-event",e),o.current&&clearTimeout(o.current)}},[]);const a=9+e.length+19>100;let i=e;if(a){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 N.createElement(z,null,!a&&N.createElement(H,{color:"green"},"● taste: "),N.createElement(H,null,i),!a&&N.createElement(H,{dimColor:!0}," (ctrl+t to expand)"))},"LearningFeedMini"),Bs=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=_([]),[o,s]=_(0),[a,i]=_(!0);j(()=>{c()},[]);const c=__name(async()=>{i(!0);const e=await vo.listSessions();r(e.slice(0,30)),i(!1)},"loadSessions");if(V((r,a)=>{a.escape?t():a.upArrow?s(e=>Math.max(0,e-1)):a.downArrow?s(e=>Math.min(n.length-1,e+1)):a.return&&n.length>0&&o<n.length&&e(n[o].id)}),a)return N.createElement(z,{flexDirection:"column",paddingLeft:2},N.createElement(H,{color:"gray"},"Loading sessions..."));if(0===n.length)return N.createElement(z,{flexDirection:"column",paddingLeft:2},N.createElement(H,{color:"gray"},"No previous sessions found"),N.createElement(H,{color:"dim",dimColor:!0},"Press ESC to go back"));const l=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),d=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");return N.createElement(z,{flexDirection:"column",paddingLeft:1,width:"100%"},N.createElement(H,{color:"cyan",bold:!0},"Resume Session"),N.createElement(H,{color:"dim",dimColor:!0},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),N.createElement(z,{marginTop:1}),N.createElement(z,{columnGap:2,marginBottom:1},N.createElement(z,{width:5},N.createElement(H,{color:"gray"}," ")),N.createElement(z,{width:13},N.createElement(H,{color:"gray"},"Modified")),N.createElement(z,{width:20},N.createElement(H,{color:"gray"},"Git Branch")),N.createElement(z,{width:11},N.createElement(H,{color:"gray"},"# Messages")),N.createElement(z,null,N.createElement(H,{color:"gray"},"Summary"))),N.createElement(z,{columnGap:2},N.createElement(z,{flexDirection:"column",width:5},n.map((e,t)=>N.createElement(H,{key:`sel-${t}`,color:o===t?"white":"gray"},o===t?`${ie.pointer} ${t+1}.`:` ${t+1}.`))),N.createElement(z,{flexDirection:"column",width:13},n.map((e,t)=>N.createElement(H,{key:`mod-${e.id}`,color:o===t?"white":"gray"},l(e.lastModified)))),N.createElement(z,{flexDirection:"column",width:20},n.map((e,t)=>N.createElement(H,{key:`branch-${e.id}`,color:o===t?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-"))),N.createElement(z,{flexDirection:"column",width:11},n.map((e,t)=>N.createElement(H,{key:`msg-${e.id}`,color:o===t?"white":"gray"},e.messageCount))),N.createElement(z,{flexDirection:"column"},n.map((e,t)=>N.createElement(H,{key:`summary-${e.id}`,color:o===t?"white":"gray"},d(e.firstMessage))))))},"SessionsResumeTable"),Ws=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],zs=["","","[118;5u"];function isNewlineShortcutKey(e){const{inputChar:t,key:n,isPasting:r}=e;return!r&&(!(!n.return||!n.shift)||!(!n.ctrl||!n.return)||!(!n.ctrl||"j"!==t)||!("\r"!==t||n.return||n.ctrl||n.shift||n.meta)||Ws.includes(t))}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(isNewlineShortcutKey,"isNewlineShortcutKey"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var Hs=__name(()=>N.createElement(z,{flexDirection:"column",paddingLeft:1},N.createElement(H,{color:"dim",bold:!0},"Available Shortcuts:"),N.createElement(z,{columnGap:4},N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"dim"},"! for bash mode"),N.createElement(H,{color:"dim"},"/ for commands"),N.createElement(H,{color:"dim"},"@ for file paths"),N.createElement(H,{color:"dim"},"shift + tab to toggle auto-accept")),N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"dim"},"double tap esc to clear input"),N.createElement(H,{color:"dim"},"ctrl + j / shift + ⏎ for newline"),N.createElement(H,{color:"dim"},"ctrl + z to suspend")))),"ShortcutMenu"),Gs=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:s,setShowFileList:a,fileSearchQuery:i,setFileSearchQuery:c,onCommand:l,contextUsage:d,tasteLearning:u=!1,tasteUsage:m=!1,shareInfo:g,showShareNotification:p,unshareNotificationMessage:h,tasteNotificationMessage:f,updateStatus:y,updateFailedInfo:w,currentProvider:b,showProviderInfo:k,autoAcceptMode:S=!1,onToggleAutoAccept:C,hintMessage:v,historyManager:T,pendingExitKey:A=null,onOverlayVisibilityChange:P,onDoubleEscapeEmpty:x})=>{const[I,$]=_(0),[D,F]=_(!1),[R,M]=_(!1),[O,L]=_(!1),[G,q]=_(!1),[K,J]=_(""),[Y,Q]=_(!1),[Z,X]=_(0),[ee,te]=_([]),[ne,re]=_([]),[oe,se]=_(""),ae=U(!1),ce=U(!1),[le,de]=_(-1),[ue,me]=_(""),ge=U(0),{handlePaste:pe,resetPasteState:he,isPasting:fe}=useBracketedPaste({input:e,detectedImages:ne,detectedContent:ee,setInput:n,setDetectedImages:re,setDetectedContent:te,incrementInputKey:__name(()=>$(e=>e+1),"incrementInputKey")});j(()=>{const e=s||G||Y;P?.(e)},[s,G,Y,P]);const ye=B(()=>{n(""),M(!1),q(!1),J(""),Q(!1),te([]),re([]),se(""),he(),de(-1),me(""),$(e=>e+1)},[n,he]);V(async(t,r)=>{if(r.upArrow){if(s||G||Y)return;const t=e.indexOf("\n"),r=-1===t||ge.current<=t;if(0!==e.length&&-1===le&&!r)return;const o=T?.count()??0;if(0===o)return;-1===le&&me(e);const a=Math.min(le+1,o-1);return void(a!==le&&(de(a),n(T?.getAt(a)||""),$(e=>e+1)))}if(r.downArrow){if(s||G||Y)return;if(-1===le)return;const t=e.lastIndexOf("\n");if(!(-1===t||ge.current>t))return;const r=le-1;return de(r),n(-1===r?ue:T?.getAt(r)||""),void $(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return;if(getIsExpandToolShortcut(r,t))return ae.current=!0,n(e),$(e=>e+1),void setTimeout(()=>{ae.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:fe()}))return ce.current=!0,ae.current=!0,n(e+"\n"),$(e=>e+1),void setTimeout(()=>{ce.current=!1,ae.current=!1},0);if(r.meta&&r.backspace)return void ye();if(r.meta&&"w"===t)return ae.current=!0,void ye();const o=r.ctrl&&"v"===t||zs.includes(t),a=r.meta&&"v"===t;if(o||a){if(o&&"darwin"===process.platform){const t=e,r=await detectClipboardImage();if(r){const e=`[Image#${ne.length+1}]`;re(e=>[...e,r]),n(t+e),$(e=>e+1)}return void(ae.current=!0)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return L(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(r.escape){if(G)return;if(Y)return Q(!1),n(oe),void $(e=>e+1);const t=Date.now();return t-Z<500?(e.length>0?ye():x?.(),X(0)):X(t),F(!1),void M(!1)}D&&(r.backspace||r.delete)&&0===e.length&&F(!1)}});const we=B(async t=>{if(await pe(t))return;if(ae.current)return void(ae.current=!1);-1!==le&&de(-1);const r=1===t.length,o=t.slice(-1);if(r){if("?"===o&&!D)return F(!0),n(""),void $(e=>e+1);if("!"===o&&!R)return F(!1),M(!0),n(""),void $(e=>e+1)}if("/"!==o||G||"/"!==t||(q(!0),J("")),G&&!t.startsWith("/")&&(q(!1),J("")),G&&t.startsWith("/")){const e=t.substring(1);J(e)}"@"!==o||s||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(a(!0),c(""));const i=t.lastIndexOf("@");if(t.length<e.length&&-1!==i&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(i+1),n=!e.includes(" "),r=i>0?t[i-1]:"";n&&isPrecededByWhitespace(r)&&(a(!0),c(e))}if(s)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!1),c("");else{const n=t.substring(e+1);c(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);c(e),a(!1)}else c(n)}}D&&(t!==e||t.length<e.length)&&F(!1),0===t.length&&(M(!1),q(!1),J(""),Q(!1),re([]),te([]),c(""),se(""),he()),n(t)},[D,e,n,s,a,G,R,ne,le,pe,he]),Ee=B(async()=>{if(D)return void F(!1);let n=e.trim();if(!R&&n.startsWith("/"))return T?.add(n),l&&l(n),M(!1),q(!1),J(""),re([]),te([]),de(-1),void me("");n.length>0&&T?.add(n),de(-1),me("");let r=[];const o=ne.length>0,s=ee.length>0;if(!R&&o){const e=[];ne.forEach((t,r)=>{const o=`[Image#${r+1}]`;n.includes(o)&&e.push(t)}),e.length>0&&(r=e)}if(!R&&s){let e=n;ee.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}t({input:n,role:R?"bash":"user",images:r}),M(!1),q(!1),J(""),re([]),te([])},[t,l,D,e,R,ne,ee,T]),be=B(t=>{const r=E(process.cwd(),t);let o;if(s&&""!==i){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),a(!1),c(""),$(e=>e+1)},[n,a,e,s,i,c]),ke=B(()=>{a(!1),c("")},[a,c]),Se=B(t=>{if("/resume"===t)T?.add(t),de(-1),me(""),se(e),q(!1),J(""),Q(!0),n(""),$(e=>e+1);else{const e=Object.values(Os).includes(t);q(!1),J(""),e?(T?.add(t),de(-1),me(""),n(""),$(e=>e+1),l&&l(t)):(n(t+" "),$(e=>e+1))}},[l,n,e,T]),Ce=B(()=>{q(!1),J(""),n(""),de(-1),me(""),$(e=>e+1)},[n]),ve=B(e=>{Q(!1),n(""),se(""),de(-1),me(""),$(e=>e+1),l&&l(`/resume:${e}`)},[l,n]),Te=B(()=>{Q(!1),n(oe),de(-1),me(""),$(e=>e+1)},[oe,n]),Ae=B(e=>{ge.current=e},[]),Pe=W(()=>S?!D&&!Y:!D&&0===e.length&&!R&&!Y,[D,e,R,Y,S]),xe=__name(()=>D||s||G||Y||O?0:Pe||A||R?3:4,"getBottomMargin");return N.createElement(z,{width:"100%",flexDirection:"column",marginBottom:xe()},!Y&&N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(H,{color:R?"green":"gray"},ie.line.repeat(process.stdout.columns||80)),N.createElement(TextInput,{key:I,value:e,placeholder:o,onChange:we,onSubmit:()=>{ce.current?ce.current=!1:s||G||Y||Ee()},showCursor:r,onCursorChange:Ae,prefix:`${R?"!":ie.pointer} `,prefixColor:R?"green":"white"}),N.createElement(H,{color:R?"green":"gray"},ie.line.repeat(process.stdout.columns||80))),D&&N.createElement(Hs,null),O&&N.createElement(z,{paddingTop:1},N.createElement(H,{color:"yellow"},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),s&&N.createElement(Us,{onSelectFile:be,onClose:ke,searchQuery:i}),G&&N.createElement(Ns,{onSelectCommand:Se,onClose:Ce,searchQuery:K}),Y&&N.createElement(Bs,{onSelectSession:ve,onClose:Te}),(Pe||A)&&N.createElement(z,{flexDirection:"column",paddingLeft:1},N.createElement(z,{flexDirection:"row",justifyContent:"space-between"},N.createElement(z,null,A?N.createElement(H,{dimColor:!0},"Press Ctrl+C again to exit"):S?N.createElement(z,{flexDirection:"row"},N.createElement(H,{color:"#E4CCFF"},"» accept edits on"," "),N.createElement(H,{dimColor:!0},"(shift+tab to toggle)")):N.createElement(H,{color:"dim"},"? shortcuts")),N.createElement(z,{flexDirection:"column",alignItems:"flex-end"},u&&N.createElement(js,null),d&&N.createElement(_s,{usage:d}))),(y||w||k&&b)&&N.createElement(z,{flexDirection:"row",columnGap:1},y&&N.createElement(H,null,ie.tick," ","Command Code"," updated:"," ",N.createElement(H,{dimColor:!0},"v",y.updatedFrom),N.createElement(H,{dimColor:!0}," ",ie.arrowRight," "),N.createElement(H,null,"v",y.updatedTo)),!y&&w&&N.createElement(H,{color:"yellow",dimColor:!0},ie.info," Update available:"," ",w.currentVersion," ",ie.arrowRight," ",w.latestVersion),k&&b&&N.createElement(H,{color:"green",dimColor:!0},ie.bullet," Provider:"," ",getProviderDisplayName(b)))),R&&N.createElement(z,{paddingLeft:1},N.createElement(H,{color:"green"},"! for bash mode")),p&&g&&N.createElement(z,{paddingLeft:1},N.createElement(H,{color:"#E4CCFF"},"SHARED: ",g.url," (copied to clipboard)")),h&&N.createElement(z,{paddingLeft:1},N.createElement(H,{color:h.includes("NOT SHARED")?"red":"#E4CCFF"},h)),f&&N.createElement(z,{paddingLeft:1},N.createElement(H,{color:"#E4CCFF"},f)))},"InputBox"),qs=N.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:a,showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,outputTokens:m=0,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:k,currentProvider:S,showProviderInfo:C,autoAcceptMode:v,onToggleAutoAccept:T,hintMessage:A,historyManager:P,pendingExitKey:x,onResetPendingExitKey:I,onDoubleEscapeEmpty:$,retryAttempt:D})=>{const[F,R]=_(0),M=U(o);return j(()=>{x&&o!==M.current&&o.length>0&&I?.(),M.current=o},[o,x,I]),j(()=>{if(!t)return void R(0);const e=setInterval(()=>{R(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),N.createElement(z,{flexDirection:"column"},N.createElement(Ms,{messages:e}),N.createElement(z,{flexDirection:"row",justifyContent:"space-between"},N.createElement(z,{flexDirection:"column"},(t||n.isExecuting)&&null===D&&N.createElement(Is,{tokens:m,timeElapsed:F,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),A&&N.createElement(z,{marginLeft:1},N.createElement(H,{dimColor:!0}," ","⎿"," Tip: ",A)))),N.createElement(Gs,{input:o,setInput:s,onSubmit:a,placeholder:"Ask your question...",showFileList:i,setShowFileList:c,fileSearchQuery:l,setFileSearchQuery:d,onCommand:u,contextUsage:g,tasteLearning:p,tasteUsage:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:E,updateStatus:b,updateFailedInfo:k,currentProvider:S,showProviderInfo:C,autoAcceptMode:v,onToggleAutoAccept:T,hintMessage:A,historyManager:P,pendingExitKey:!x||t||n.isExecuting?null:x,onDoubleEscapeEmpty:$}))}),Vs=__name(({onClose:e})=>{const[t,n]=_(Mo.getEvents());V((t,n)=>{n.ctrl&&"t"===t&&(Ho(),e())},{isActive:!0}),j(()=>{const e=__name(()=>{n(Mo.getEvents())},"handleNewEvent"),t=__name(()=>{n([])},"handleCleared");return Mo.on("new-event",e),Mo.on("cleared",t),()=>{Mo.off("new-event",e),Mo.off("cleared",t)}},[]);const r=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),o=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const a={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:a,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),s=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),a=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails");return N.createElement(z,{flexDirection:"column",width:"100%",justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(Me,{name:"vice"},N.createElement(H,null,Sn()))),N.createElement(z,{marginBottom:1,width:"100%",justifyContent:"space-between"},N.createElement(z,null,N.createElement(H,{bold:!0},"Learning Feed"),N.createElement(H,{dimColor:!0}," - Real-time taste learning activity")),N.createElement(H,{dimColor:!0},"Press ctrl+t to close")),N.createElement(z,{flexDirection:"column"},0===t.length?N.createElement(z,null,N.createElement(H,{dimColor:!0},"No learning events yet...")):N.createElement(z,{flexDirection:"column-reverse"},t.map(e=>{if(r(e.type)){const{type:t,label:n,content:r,confidence:i}=o(e.message),c="moved"===t?a(e.details):null,l="upgraded"===t||"downgraded"===t?s(r):null;return N.createElement(z,{key:e.id,marginBottom:1},N.createElement(z,{flexDirection:"column"},N.createElement(z,null,N.createElement(H,{backgroundColor:"green",color:"black",bold:!0},` ${n} `),c?N.createElement(H,{dimColor:!0}," (",c.fullPath,")"):e.details?N.createElement(H,{dimColor:!0}," (",e.details,")"):null),N.createElement(z,{marginLeft:1},N.createElement(H,{dimColor:!0},"⎿"," "),c?N.createElement(N.Fragment,null,N.createElement(H,null,c.category," package ("),N.createElement(H,{dimColor:!0},c.oldPath),N.createElement(H,null," → ",c.newPath),N.createElement(H,null,")")):l?N.createElement(N.Fragment,null,N.createElement(H,null,l.text," ("),N.createElement(H,{dimColor:!0},"confidence: "),N.createElement(H,{dimColor:!0},l.oldPercent,"%"),N.createElement(H,null," → "),N.createElement(H,{color:l.diff>0?"green":"red"},l.newPercent,"%"),N.createElement(H,null,")")):N.createElement(N.Fragment,null,N.createElement(H,null,r),i&&N.createElement(H,{dimColor:!0}," (",i,")")))))}return N.createElement(z,{key:e.id,marginBottom:1},N.createElement(H,{dimColor:!0},ie.pointerSmall," ",e.message))}))))},"LearningFeedFull"),Ks=__name(({onClose:e})=>{const[t,n]=_([]),[r,o]=_(0),[s,a]=_(!0),[i,c]=_(null);j(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),a(!1)}catch(e){c(e instanceof Error?e.message:"Failed to discover memory files"),a(!1)}},"loadMemoryFiles")()},[]);const l=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(V((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&l(d[r]),"1"===t&&d[0]&&l(d[0]),"2"===t&&d[1]&&l(d[1]))}),s)return N.createElement(z,{paddingLeft:1,paddingTop:1},N.createElement(H,{color:"dim"},"Loading memory files..."));if(i)return N.createElement(z,{paddingLeft:1,paddingTop:1},N.createElement(H,{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 N.createElement(z,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},N.createElement(z,null,N.createElement(H,{color:"white",bold:!0},"Select memory to edit:")),N.createElement(z,{columnGap:4,marginTop:1},N.createElement(z,{flexDirection:"column"},u.map((e,t)=>N.createElement(H,{key:t,color:r===t?"white":"dim"},r===t?"> ":" ",e.label))),N.createElement(z,{flexDirection:"column"},u.map((e,t)=>N.createElement(H,{key:t,color:r===t?"white":"dim"},e.description)))))},"MemorySelector"),Js=class extends Le{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}list(e,t=!1,n=""){let r=super.list(e,t,n);return r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),r}},Ys=new Oe;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const o=W(()=>{if(!e)return"";try{const t=Ys.parse(e);return"string"!=typeof t?e:t.trim()}catch{return e}},[e]);return N.createElement(H,{color:t,dimColor:n,wrap:r},o)}function AssistantMessage({content:e}){return N.createElement(z,null,N.createElement(H,null,ie.nodejs),N.createElement(z,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},N.createElement(Markdown,null,e)))}Ys.setOptions({renderer:new Js({strong:t.bold,em:t.italic,del:t.strikethrough,codespan:t.yellow,code:t.yellow,heading:t.bold.underline,firstHeading:t.bold.underline,link:t.cyan,href:t.cyan.underline,blockquote:t.gray.italic,table:t.reset,hr:t.reset,paragraph:t.reset,html:t.gray,showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0}),__name(Markdown,"Markdown"),__name(AssistantMessage,"AssistantMessage");var Qs={"Interrupted by user":"Interrupted by user","Insufficient credits":mt};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&&Qs[e]||e;return N.createElement(z,{paddingX:1,backgroundColor:o?void 0:"#333333"},N.createElement(H,{color:o?"red":"#AAAAAA",bold:!o},ie.pointer),N.createElement(z,{marginLeft:1},N.createElement(H,{color:o?"red":"white",wrap:"wrap"},s)))}__name(UserMessage,"UserMessage");var Zs="#6B7280";function truncateToolOutputForDisplay({output:e,maxLines:t=1}){const n=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim(),r=n.split("\n");return r.length<=t?n:r.slice(0,t).join("\n")}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:o=!1,marginLeft:s=2,dimDiff:a=!1,maxLines:i}){const c=Ne.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(N.createElement(z,{key:`${t}-${r}-removed`,width:"100%"},N.createElement(H,{color:"gray",dimColor:a},u.toString().padStart(3)," "),N.createElement(z,{backgroundColor:"#712F37"},N.createElement(H,{dimColor:a},"-"),N.createElement(H,{dimColor:a}," ",n.replace(/\s/g," ")))))):e.added&&(u++,g.push(N.createElement(z,{key:`${t}-${r}-added`,width:"100%"},N.createElement(H,{color:"gray",dimColor:a},u.toString().padStart(3)," "),N.createElement(z,{backgroundColor:"#325B30"},N.createElement(H,{dimColor:a},"+"),N.createElement(H,{dimColor:a}," ",n.replace(/\s/g," "))))))}):u+=n.length});const p=void 0!==i&&g.length>i,h=p?g.slice(0,i):g;return{diffContent:N.createElement(z,{flexDirection:"column"},o&&!r&&N.createElement(H,{color:"gray"},"Updated"," ",N.createElement(H,{color:"white",bold:!0},n)," ","with ",N.createElement(H,{color:"#22C55E"},l)," addition",1!==l?"s":""," and"," ",N.createElement(H,{color:"#EF4444"},d)," removal",1!==d?"s":""),r&&N.createElement(H,{color:"red"},"Rejected update to",N.createElement(H,{color:"red"},` ${n}`)),N.createElement(z,{flexDirection:"column",marginLeft:s},h)),isTruncated:p,totalLines:g.length}}function formatTodosForDisplay(e){const t=Lr(e);return t?N.createElement(z,{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 N.createElement(z,{key:e.id||t,flexDirection:"row"},N.createElement(z,{width:2},N.createElement(H,{color:r},n)),N.createElement(H,{color:r,bold:"in_progress"===e.status,strikethrough:o},e.content))})):N.createElement(H,null,e)}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:o=!1,metadata:s,expandedOutput:a=!1}){const i="Thinking…"===e,c="Todos"===e,l="Edit"===e,d=!0===s?.isTasteFile,u=s?.tasteCategory,m=!0===s?.permissionDenied,g=!i&&!c&&!d,{name:p}=detectTerminal(),h="iTerm2"===p?"shift":"ctrl",f=!0===s?.isAgent,y=t&&f?(()=>{const e=t.split(/[.\n]/)[0];return e?e+(t.includes(".")||t.includes("\n")?".":""):t})():t,w=!i&&y&&!d,E=s?.status,b=s?.tokensUsed||0,k="number"==typeof s?.elapsedSeconds?Math.floor(s.elapsedSeconds):0;let S,C;if(r)S="yellow",C="→";else if(o)S="red",C=ie.nodejs;else if(i)S=Zs,C="✻";else if(c&&n){const e=Lr(n),t=e?.every(e=>"completed"===e.status);S=t?"#22C55E":"#D4A017",C=ie.nodejs}else S="#22C55E",C=ie.nodejs;return N.createElement(z,null,i&&N.createElement(H,{color:S},C),N.createElement(z,{flexDirection:"column",marginLeft:i?1:0},N.createElement(z,null,i?N.createElement(N.Fragment,null,N.createElement(H,{color:Zs},(()=>{const e=n?Math.max(1,Math.round(n.length/500)):1;return`Thought for ${e} second${1!==e?"s":""}`})()," "),!a&&N.createElement(H,{dimColor:!0},"(",`${h}+o to expand`,")")):d?N.createElement(N.Fragment,null,N.createElement(H,{backgroundColor:"green",color:"#FFFFFF",bold:!0}," Taste "),N.createElement(H,null," ","Using your taste ",u?"package of ":"packages",u&&N.createElement(H,{bold:!0},u))):N.createElement(H,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${e} `),w&&N.createElement(H,null," ",N.createElement(Markdown,null,`(${y})`))),f&&("running"===E||n)&&N.createElement(z,{columnGap:1,marginLeft:g?1:0},g&&N.createElement(H,null,"⎿"," "),"running"===E?N.createElement(H,{color:"gray"},"Running (",formatTime2(k)," | ",formatTokens(b),")"):"interrupted"===E?N.createElement(H,{color:"red",wrap:"wrap"},"Interrupted by user"):"error"===E||o?N.createElement(H,{color:"red",wrap:"wrap"},n," (",formatTime2(k)," | ",formatTokens(b),")"):"Interrupted by user"===n?N.createElement(N.Fragment,null,N.createElement(H,{color:"red",wrap:"wrap"},"Interrupted by user")):N.createElement(N.Fragment,null,N.createElement(H,{wrap:"wrap"},"Done"),N.createElement(H,{color:"gray"}," ","(",formatTime2(k)," | ",formatTokens(b),")"))),n&&!d&&!f&&N.createElement(z,{columnGap:1,marginLeft:g?1:0},g&&N.createElement(H,null,"⎿"," "),c?formatTodosForDisplay(n):i?a?N.createElement(z,{width:"100%",flexDirection:"column"},N.createElement(H,null," "),N.createElement(H,{color:Zs,wrap:"wrap",italic:!0},n)):null:l&&s?.oldValue&&s?.newValue?N.createElement(z,{flexDirection:"column"},(()=>{const e=a?void 0:10,{diffContent:n,isTruncated:r,totalLines:o}=generateDiff({filePath:t,showMetadata:!0,oldValue:s.oldValue,newValue:s.newValue,dimDiff:m,permissionDenied:m,maxLines:e});return N.createElement(N.Fragment,null,n,r&&N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"… (",o-10," more lines) (",`${h}+o to expand`,")")))})(),m&&n&&N.createElement(z,{marginTop:1},N.createElement(H,{color:"red",wrap:"wrap"},n))):N.createElement(z,{width:"100%"},N.createElement(H,{color:o?"red":"",wrap:"wrap"},a?n:N.createElement(N.Fragment,null,truncateToolOutputForDisplay({output:n,maxLines:"Question"===e?10:1}),n.includes("\n")&&"Question"!==e&&N.createElement(H,{dimColor:!0}," ","(",`${h}+o to expand`,")"))))),r&&!f&&N.createElement(z,{columnGap:1,marginLeft:1},N.createElement(H,null,"⎿"," "),N.createElement(H,{color:"gray"},"Processing…"))))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o,s;return n?(o="yellow",s="→"):r?(o="red",s="✗"):(o="green",s="✓"),N.createElement(z,null,N.createElement(H,{color:o},s),N.createElement(z,{flexDirection:"column",marginLeft:1},N.createElement(z,null,N.createElement(H,{color:"gray"},"$ "),N.createElement(H,{color:o,bold:!0},e)),N.createElement(z,{columnGap:1,marginLeft:1},N.createElement(H,null,"⎿"," "),N.createElement(H,{color:r?"red":n?"yellow":"default",wrap:"wrap"},n?"Executing…":t||"(No output)"))))}__name(truncateToolOutputForDisplay,"truncateToolOutputForDisplay"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(ToolMessage,"ToolMessage"),__name(BashMessage,"BashMessage");var Xs="Coding agent that continuously learns your taste of writing code.",ea=[{key:"Shift+Tab",description:"Toggle auto-accept mode"},{key:"Ctrl+T",description:"Toggle learning feed"},{key:"Ctrl+O",description:"Toggle expanded tool output (Shift+O in iTerm2)"},{key:"Esc Esc",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],ta=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume",description:"Resume a conversation"},{key:"-c, --continue",description:"Continue the last conversation"},{key:"-t, --trust",description:"Auto-trust project (skip initial permission prompt)"},{key:"-p, --print [query]",description:"Run in non-interactive mode, output response and exit"},{key:"--dangerously-skip-permissions",description:"Bypass all permission prompts (use with caution)"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],na=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rewind",description:"Restore to a previous checkpoint (Esc Esc)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/model",description:"Switch between Command Code models"},{key:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{key:"/compact",description:"Compact the conversation history"},{key:"/login",description:"Authenticate with CommandCode via browser"},{key:"/logout",description:"Remove stored authentication"},{key:"/exit",description:"Exit the REPL"}],ra=[{key:"cmd info",description:"Display system information"},{key:"cmd config",description:"Manage CLI configuration"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],oa=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],sa=["cmd Start interactive session",'cmd "fix the login bug" Start with a task',"cmd -c Continue last conversation","cmd -r Resume a past session",'cmd -p "your query" Run non-interactive query',"cmd info Show system information"],aa='Start with a prompt: cmd "fix the login bug"',ia="cmd";function getBinNames(){const e=getPackageJson();return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name]:[ia]}function getInvokedCommandName(){try{const e=getBinNames(),t=process.argv[1];if(!t)return e[0]||ia;const n=w.basename(t).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(n)?n:e[0]||ia}catch{return ia}}function HelpMessage(){const e=getInvokedCommandName(),t=W(()=>na.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return N.createElement(z,{flexDirection:"column",paddingY:1},N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(z,null,N.createElement(H,{bold:!0},"Command Code"),N.createElement(H,{color:"gray"}," v","0.10.11")),N.createElement(H,{color:"gray"},Xs)),N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(H,{bold:!0},"Usage"),N.createElement(z,{paddingLeft:2},N.createElement(H,null,e," <command> [options]"))),N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(H,{bold:!0},"Options"),N.createElement(z,{flexDirection:"column",paddingLeft:2},ta.map(t=>N.createElement(z,{key:t.key},N.createElement(H,null,t.key.replace(/^cmd/,e).padEnd(20)),N.createElement(H,{color:"gray"},t.description))))),N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(H,{bold:!0},"Commands"),N.createElement(z,{flexDirection:"column",paddingLeft:2},ra.map(t=>N.createElement(z,{key:t.key},N.createElement(H,null,t.key.replace(/^cmd/,e).padEnd(20)),N.createElement(H,{color:"gray"},t.description))))),N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(H,{bold:!0},"Slash Commands"),N.createElement(z,{flexDirection:"column",paddingLeft:2},t.map(e=>N.createElement(z,{key:e.key},N.createElement(H,null,e.key.padEnd(17)),N.createElement(H,{color:"gray"},e.description))))),N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(H,{bold:!0},"Keyboard Shortcuts"),N.createElement(z,{flexDirection:"column",paddingLeft:2},ea.map(e=>N.createElement(z,{key:e.key},N.createElement(H,null,e.key.padEnd(15)),N.createElement(H,{color:"gray"},e.description))))),N.createElement(z,{flexDirection:"column",marginBottom:1},N.createElement(H,{bold:!0},"Examples"),N.createElement(z,{flexDirection:"column",paddingLeft:2},sa.map((t,n)=>N.createElement(H,{key:n},t.replace(/^cmd/,e))))),N.createElement(z,{marginBottom:1},N.createElement(H,{color:"cyan"},"❯"),N.createElement(H,{color:"gray"}," ",aa.replace(/cmd/,e))),N.createElement(z,{flexDirection:"column"},N.createElement(H,{bold:!0},"Links"),N.createElement(z,{flexDirection:"column",paddingLeft:2},oa.map(e=>N.createElement(z,{key:e.key},N.createElement(H,null,e.key.padEnd(20)),N.createElement(H,{color:"cyan"},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?N.createElement(HelpMessage,null):N.createElement(z,{flexDirection:"column"},N.createElement(H,{wrap:"wrap"},N.createElement(Markdown,null,e)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return N.createElement(z,null,N.createElement(H,{color:"red"},t?ie.pointer:ie.warning),N.createElement(z,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?N.createElement(H,{color:"red",wrap:"wrap"},e):N.createElement(Markdown,{color:"red"},e)))}function InfoMessage({content:e}){return N.createElement(z,null,N.createElement(H,{dimColor:!0},ie.info),N.createElement(z,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},N.createElement(Markdown,{dimColor:!0},e)))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){return N.createElement(z,{flexDirection:"column",marginBottom:0,marginTop:-1},N.createElement(z,{columnGap:1},N.createElement(H,null,"⎿"," "),N.createElement(z,{flexGrow:1,flexShrink:1,minWidth:0},N.createElement(H,{color:n?"yellow":void 0},e))),t&&N.createElement(z,{marginLeft:3},N.createElement(H,{dimColor:!0},"See ",t)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(ErrorMessage,"ErrorMessage"),__name(InfoMessage,"InfoMessage"),__name(CommandResultMessage,"CommandResultMessage");var ca=w.join(T.homedir(),".commandcode","updates.json");function ensureDir(){const e=w.dirname(ca);l.existsSync(e)||l.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!l.existsSync(ca))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=l.readFileSync(ca,"utf-8");return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null,...JSON.parse(e)}}catch{return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}}}function writeUpdatesConfig(e){ensureDir(),l.writeFileSync(ca,JSON.stringify(e,null,2))}function updateUpdatesConfig(e){writeUpdatesConfig({...readUpdatesConfig(),...e})}function shouldCheckForUpdate(){const e=readUpdatesConfig();return!!e.autoUpdate&&Date.now()-e.lastCheckedAt>=e.checkIntervalMs}function recordUpdateCheck(){updateUpdatesConfig({lastCheckedAt:Date.now()})}function setPendingUpdate(e){updateUpdatesConfig({lastCheckedAt:Date.now(),pending:e})}function clearPendingUpdate(){updateUpdatesConfig({pending:null})}function getPendingUpdate(e){const t=readUpdatesConfig();return t.pending?t.pending.currentVersion!==e?(clearPendingUpdate(),null):t.pending:null}__name(function getDefaultConfig(){return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}},"getDefaultConfig"),__name(ensureDir,"ensureDir"),__name(readUpdatesConfig,"readUpdatesConfig"),__name(writeUpdatesConfig,"writeUpdatesConfig"),__name(updateUpdatesConfig,"updateUpdatesConfig"),__name(shouldCheckForUpdate,"shouldCheckForUpdate"),__name(recordUpdateCheck,"recordUpdateCheck"),__name(setPendingUpdate,"setPendingUpdate"),__name(clearPendingUpdate,"clearPendingUpdate"),__name(getPendingUpdate,"getPendingUpdate");var la=_e(R),da=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=F("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return da.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort(Ue.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Ue.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Ue.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:o,updateAvailable:s}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:o,updateAvailable:s}}async function executeUpdate(e){try{return await la(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!Ue.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=ke(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`)}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const o=n||await checkForUpdateAvailable();return o?.updateAvailable?(r?.(o.latestVersion),await executeUpdate(o.latestVersion)?{success:!0,updateInfo:o}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:o})):{success:!1}}function getCurrentGitBranch(){try{return F("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","ignore"],cwd:process.cwd()}).trim()||null}catch(e){return null}}function getGitHeaderInfo(){return{branch:getCurrentGitBranch(),isLocal:isLocalDevelopmentBuild()}}function getModelShortName(e){const t=Object.values(st).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(shouldSkipUpdateSystem,"shouldSkipUpdateSystem"),__name(fetchVersions,"fetchVersions"),__name(getCurrentVersion,"getCurrentVersion"),__name(isAlphaVersion,"isAlphaVersion"),__name(filterVersions,"filterVersions"),__name(getLatestVersion,"getLatestVersion"),__name(determineUpdateTarget,"determineUpdateTarget"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(executeUpdate,"executeUpdate"),__name(checkForUpdateAsync,"checkForUpdateAsync"),__name(doUpdateCheck,"doUpdateCheck"),__name(maybeRunPendingUpdate,"maybeRunPendingUpdate"),__name(performAutoUpdate,"performAutoUpdate"),__name(getCurrentGitBranch,"getCurrentGitBranch"),__name(getGitHeaderInfo,"getGitHeaderInfo"),__name(getModelShortName,"getModelShortName");var ua=N.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o})=>{const s=t?["header",...e]:e,a=Sn();getTerminalWidth();const i=getPackageJson().version||"0.0.0",c=o?getModelShortName(o):"sonnet-4.5",l=process.cwd(),d=process.env.HOME||process.env.USERPROFILE||"",u=l.replace(d,"~"),m=getGitHeaderInfo();return N.createElement(G,{items:s,key:n,style:{width:"100%"}},e=>{if("header"===e)return N.createElement(z,{key:"header",marginBottom:1,flexDirection:"column"},N.createElement(Me,{name:"vice"},N.createElement(H,null,a.trimEnd())),N.createElement(z,{flexDirection:"column",marginTop:1},N.createElement(z,null,N.createElement(H,{color:"gray"},"# "),N.createElement(H,{bold:!0},"Command Code"),N.createElement(H,{color:"gray"}," v",i)),N.createElement(H,{color:"gray"},"# models: ",c," · ","taste-1",isInternalTeamFlagEnforced()&&" · --co"),N.createElement(z,null,N.createElement(H,{color:"gray"},"# ",u,m&&m.isLocal&&m.branch&&N.createElement(H,{color:"gray"}," (branch: ",m.branch,")")))));const t=e,n=(()=>{switch(t.role){case"user":return N.createElement(UserMessage,{content:t.input});case"assistant":return N.createElement(AssistantMessage,{content:t.input});case"tool":return N.createElement(ToolMessage,{name:Mr(t.name||""),input:t.input,output:t.output||"",isPending:Dr(t),hasError:$r(t),metadata:t.metadata,expandedOutput:r});case"bash":return N.createElement(BashMessage,{command:t.command||"",output:t.output||"",isPending:Dr(t),hasError:$r(t)});case"system":return N.createElement(SystemMessage,{content:t.input});case"info":return N.createElement(InfoMessage,{content:t.input});case"error":return N.createElement(ErrorMessage,{content:t.input});case"command-result":return N.createElement(CommandResultMessage,{message:t.input,details:t.details,hasError:t.hasError??!1});default:return N.createElement(N.Fragment,null)}})();return N.createElement(z,{key:t.id,marginBottom:1,width:"90%"},n)})});function getModelOptions(){return Object.values(st).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}__name(getModelOptions,"getModelOptions");var ma=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),o=__name(t=>{e(t.value)},"handleSelect");V((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0;return N.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},N.createElement(z,null,N.createElement(H,{color:"#E4CCFF",bold:!0},"Select model")),N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),N.createElement(Fe,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const o=r.find(e=>e.label===t),s=o?.value===n,a=o?.description?`${o.label} (${o.description})`:o?.label||t;return N.createElement(z,null,N.createElement(H,{color:e?"green":"gray"},` ${a.padEnd(24)}`),N.createElement(H,{color:e?"green":"gray"},o?.modelName),s&&N.createElement(H,{color:"green"}," ✓"))}}),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press "),N.createElement(H,{dimColor:!0,bold:!0},"Esc"),N.createElement(H,{dimColor:!0}," to cancel")))},"ModelSelector"),ga=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=_(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"),a=__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"),i=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const t=w.basename(e.filePath),n=w.relative(process.cwd(),e.filePath);return n&&!n.startsWith("../")&&n.length<50?n:t||e.filePath}catch{return e.filePath}},"getDisplayPath"),c=__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 N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},N.createElement(z,{marginBottom:1},N.createElement(H,{bold:!0,color:"yellow"},`${c()} ${"edit"===e.action?i():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&N.createElement(z,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:i(),marginLeft:0}).diffContent),N.createElement(z,{marginBottom:1},N.createElement(H,{bold:!0},"Do you want to ",a()," ",N.createElement(H,{color:"cyan"},i()),"?")),N.createElement(Fe,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:"cyan"},e?ie.pointer:" "),itemComponent:({label:e,isSelected:t})=>N.createElement(H,{color:t?"cyan":"white"},e.includes("(shift+tab)")?N.createElement(N.Fragment,null,e.split("(shift+tab)")[0],N.createElement(H,{bold:!0,dimColor:!0},"(shift+tab)")):e.includes("(")?N.createElement(N.Fragment,null,e.split("(")[0],N.createElement(H,{color:"gray"},"(",e.split("(")[1])):e)}))},"PermissionPrompt"),pa=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");V((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,a=n&&-1===s;return N.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},N.createElement(z,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},N.createElement(z,null,N.createElement(H,{bold:!0},"Select AI Provider")),n&&N.createElement(z,{flexDirection:"row"},N.createElement(H,{dimColor:!0},"Current: "),N.createElement(H,{color:"green"},getProviderDisplayName(n)),a&&N.createElement(H,{color:"yellow"}," [OAuth enforced]"))),N.createElement(z,{marginBottom:0},N.createElement(H,{dimColor:!0},"Available Providers:")),N.createElement(Fe,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:e?"cyan":"gray",bold:e},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>N.createElement(H,{color:e?"cyan":"gray",bold:e},` ${t}`)}),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press ESC to cancel")))},"ProviderSelector"),ha=__name(({staticKey:e})=>N.createElement(G,{items:[{staticKey:e}],key:e},()=>N.createElement(H,{key:e},"\0")),"Responsive");function RetryMessage({attempt:e}){const[t,n]=_(0);if(j(()=>{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 N.createElement(z,{marginBottom:1},N.createElement(H,{color:"#FFA500",dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}__name(RetryMessage,"RetryMessage");var fa=[{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"}],ya=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=W(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=_(Math.max(0,r.length-1)),[a,i]=_(Math.max(0,r.length-8)),[c,l]=_("checkpoint"),[d,u]=_(null),[m,g]=_(0),p=W(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),h=W(()=>p?fa:fa.filter(e=>"conversation"===e.mode),[p]);if(j(()=>{if(r.length>0){const e=r.length-1;s(e),i(Math.max(0,r.length-8))}},[r.length,8]),V((e,p)=>{p.escape?"mode"===c?(l("checkpoint"),u(null),g(0)):n():"checkpoint"===c?p.upArrow?s(e=>{const t=Math.max(0,e-1);return t<a&&i(t),t}):p.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=a+8&&i(t-8+1),t}):p.return&&r.length>0&&(u(r[o]),l("mode"),g(0)):"mode"===c&&(p.upArrow?g(e=>Math.max(0,e-1)):p.downArrow?g(e=>Math.min(h.length-1,e+1)):p.return&&d&&h[m]&&t({messageId:d.messageId,mode:h[m].mode}))}),0===r.length)return N.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},N.createElement(H,{color:"#E4CCFF",bold:!0},"Rewind"),N.createElement(H,{dimColor:!0},"No checkpoints available. Start a conversation to create checkpoints."),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press "),N.createElement(H,{dimColor:!0,bold:!0},"Esc"),N.createElement(H,{dimColor:!0}," to close")));if("mode"===c&&d)return N.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},N.createElement(H,{color:"#E4CCFF",bold:!0},"Rewind"),N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"Restore to: "),N.createElement(H,{color:"white"},truncateString2({text:d.userPrompt||"checkpoint",maxLength:50}))),N.createElement(z,{flexDirection:"column"},h.map((e,t)=>{const n=m===t,r=t===h.length-1;return N.createElement(z,{key:e.mode,flexDirection:"column"},N.createElement(z,{flexDirection:"row"},N.createElement(H,{color:n?"#E4CCFF":void 0},n?"> ":" "),N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:n?"#E4CCFF":"white"},e.label),N.createElement(H,{dimColor:!0},e.description))),!r&&N.createElement(H,null," "))})),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press "),N.createElement(H,{dimColor:!0,bold:!0},"Enter"),N.createElement(H,{dimColor:!0}," to confirm, "),N.createElement(H,{dimColor:!0,bold:!0},"Esc"),N.createElement(H,{dimColor:!0}," to go back")));const f=r.slice(a,a+8);return N.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},N.createElement(H,{color:"#E4CCFF",bold:!0},"Rewind"),N.createElement(H,{dimColor:!0},"Select a checkpoint to restore your session"),r.length>8&&N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Showing ",a+1,"-",Math.min(a+8,r.length)," ","of ",r.length)),N.createElement(z,{marginTop:1}),N.createElement(z,{flexDirection:"column"},f.map((e,t)=>{const n=a+t,s=o===n,i=e.filesModified.length,c=t===f.length-1,l=n===r.length-1;return N.createElement(z,{key:e.messageId,flexDirection:"column"},N.createElement(z,{flexDirection:"row"},N.createElement(H,{color:s?"#E4CCFF":void 0},s?"> ":" "),N.createElement(z,{flexDirection:"column"},N.createElement(z,null,N.createElement(H,{color:s?"#E4CCFF":"white"},truncateString2({text:e.userPrompt||"(no prompt)",maxLength:60})),N.createElement(H,{dimColor:!0}," • "),N.createElement(H,{dimColor:!0},getRelativeTimeString({timestamp:e.timestamp}),l&&" (latest)")),N.createElement(H,{dimColor:!0},i>0?`${i} file${i>1?"s":""} changed`:"No code changes"))),!c&&N.createElement(H,null," "))})),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press "),N.createElement(H,{dimColor:!0,bold:!0},"Enter"),N.createElement(H,{dimColor:!0}," to select, "),N.createElement(H,{dimColor:!0,bold:!0},"Esc"),N.createElement(H,{dimColor:!0}," to cancel")))},"RewindSelector"),wa=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=K(),[r,o]=_([]),[s,a]=_(0),[i,c]=_(!0),[l,d]=_(0),u=30;j(()=>{m()},[]);const m=__name(async()=>{c(!0);const e=await vo.listSessions();o(e),c(!1)},"loadSessions");if(V((t,o)=>{o.upArrow?a(e=>{const t=Math.max(0,e-1);return t<l&&d(t),t}):o.downArrow?a(e=>{const t=Math.min(r.length-1,e+1);return t>=l+u&&d(t-u+1),t}):o.return?r.length>0&&e(r[s].id):(o.escape||o.ctrl&&"c"===t)&&n()}),i)return N.createElement(z,{flexDirection:"column",paddingLeft:2,paddingTop:1},N.createElement(H,{color:"gray"},"Loading sessions..."));const g=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5),a=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o} hour${o>1?"s":""} ago`:s<7?`${s} day${s>1?"s":""} ago`:1===a?"1 week ago":`${a} weeks ago`},"formatRelativeTime"),p=__name((e,t=30)=>e.length<=t?e:e.substring(0,t-3)+"...","truncateMessage");if(0===r.length)return N.createElement(z,{flexDirection:"column"},N.createElement(H,{color:"gray"},"No sessions available"));const h=r.slice(l,l+u),f=l;return N.createElement(z,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>u&&N.createElement(z,{marginBottom:1},N.createElement(H,{color:"dim"},"Showing ",l+1,"-",Math.min(l+u,r.length)," ","of ",r.length," sessions",l>0&&" (↑ for more)",l+u<r.length&&" (↓ for more)")),N.createElement(z,{columnGap:2,marginBottom:1},N.createElement(z,{width:7},N.createElement(H,{color:"gray"}," ")),N.createElement(z,{width:13},N.createElement(H,{color:"gray"},"Modified")),N.createElement(z,{width:11},N.createElement(H,{color:"gray"},"# Messages")),N.createElement(z,{width:20},N.createElement(H,{color:"gray"},"Git Branch")),N.createElement(z,null,N.createElement(H,{color:"gray"},"Summary"))),N.createElement(z,{columnGap:2},N.createElement(z,{flexDirection:"column",width:7},h.map((e,t)=>{const n=f+t;return N.createElement(H,{key:`sel-${n}`,color:s===n?"cyan":"gray"},s===n?`${ie.pointer} ${n+1}.`:` ${n+1}.`)})),N.createElement(z,{flexDirection:"column",width:13},h.map((e,t)=>{const n=f+t;return N.createElement(H,{key:`mod-${e.id}`,color:s===n?"white":"gray"},g(e.lastModified))})),N.createElement(z,{flexDirection:"column",width:11},h.map((e,t)=>{const n=f+t;return N.createElement(H,{key:`msg-${e.id}`,color:s===n?"white":"gray"},e.messageCount)})),N.createElement(z,{flexDirection:"column",width:20},h.map((e,t)=>{const n=f+t;return N.createElement(H,{key:`branch-${e.id}`,color:s===n?"white":"gray",wrap:"truncate-end"},e.gitBranch||"-")})),N.createElement(z,{flexDirection:"column"},h.map((e,t)=>{const n=f+t;return N.createElement(H,{key:`summary-${e.id}`,color:s===n?"white":"gray"},p(e.firstMessage))}))))},"SessionTable"),Ea=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=_(0),o=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session (shift+tab)",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],s=__name(e=>{const r=o.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),a=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"",n=t?`${e.command} ${t}`:e.command;return n.length>60?n.substring(0,57)+"...":n},"getCommandDisplay");return N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,width:"100%"},N.createElement(z,{marginBottom:1},N.createElement(H,{bold:!0,color:"yellow"},"Execute Shell Command")),N.createElement(z,{marginBottom:1},N.createElement(H,{bold:!0},"Command Code needs to execute ",N.createElement(H,{color:"cyan"},a()),".")),e.workingDirectory&&N.createElement(z,{marginBottom:1},N.createElement(H,{color:"gray"},"Working directory: ",e.workingDirectory)),e.description&&N.createElement(z,{marginBottom:1},N.createElement(H,{color:"gray",italic:!0},e.description)),N.createElement(Fe,{items:o.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:s,initialIndex:r,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:"cyan"},e?ie.pointer:" "),itemComponent:({label:e,isSelected:t})=>N.createElement(H,{color:t?"cyan":"white"},e.includes("(shift+tab)")?N.createElement(N.Fragment,null,e.split("(shift+tab)")[0],N.createElement(H,{bold:!0,dimColor:!0},"(shift+tab)")):e)}))},"ShellPermissionPrompt"),ba=__name(({onClose:e,staticKey:t})=>{const[n,r]=_([]),[o,s]=_(!0),[a,i]=_(null),{stdout:c}=J(),l=c?.columns??80,d=__name((e,t)=>e.length<=t?e:t<=3?e.substring(0,t):e.substring(0,t-3)+"...","truncateText");j(()=>{__name(async()=>{try{const{personal:e,project:t}=await loadAllSkillSummaries(),n=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];r(n)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=__name(async t=>{const r=n.find(e=>e.value===t.value);if(r)try{await je([{file:r.filePath,line:1}]),Ho(),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");V((t,n)=>{n.escape&&(Ho(),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?N.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},N.createElement(H,{color:"#E4CCFF",bold:!0},"Agent Skills"),N.createElement(H,{dimColor:!0},"Loading skills...")):a?N.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},N.createElement(H,{color:"red",bold:!0},"Agent Skills"),N.createElement(H,{dimColor:!0},a),N.createElement(z,{marginTop:1}),N.createElement(H,{dimColor:!0},"Press ",N.createElement(H,{bold:!0},"Esc")," to close")):0===n.length?N.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},N.createElement(H,{color:"#E4CCFF",bold:!0},"Agent Skills"),N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"No skills found")),N.createElement(H,{dimColor:!0},"Create skills in:"),N.createElement(H,{dimColor:!0}," ~/.commandcode/skills/ (user)"),N.createElement(H,{dimColor:!0}," .commandcode/skills/ (project)"),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press ",N.createElement(H,{bold:!0},"Esc")," to close"))):N.createElement(z,{flexDirection:"column",paddingX:0,width:"100%"},N.createElement(z,null,N.createElement(H,{color:"#E4CCFF",bold:!0},"Agent Skills")),N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"Select a skill to open in your editor. Skills provide specialized guidance for coding tasks.")),N.createElement(Fe,{items:n,onSelect:u,initialIndex:0,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:e?"green":"gray"},e?"▸":" "),itemComponent:({isSelected:e,label:t})=>{const r=n.find(e=>e.label===t),o=r?.location?` (${r.location})`:"",s=Math.max(30,l-35),a=r?.description?d(r.description,s):"";return N.createElement(z,null,N.createElement(H,{color:e?"green":"white"},` ${t}`),N.createElement(H,{color:"gray"},o.padEnd(25-t.length)),N.createElement(H,{color:"gray"},a))}}),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press ",N.createElement(H,{bold:!0},"Esc")," to cancel")))},"SkillsConfig"),ka=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=_(!1),[s,a]=_(!0);j(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{a(!1)}},"loadSettings")()},[]),V((t,n)=>{if(!n.return&&" "!==t)return n.escape?(Ho(),void e()):void 0;i()});const i=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?N.createElement(z,{key:n,borderStyle:"single",borderColor:"blue",padding:1,flexDirection:"column"},N.createElement(H,{color:"blue",bold:!0},"Taste Settings"),N.createElement(H,{dimColor:!0},"Loading configuration...")):N.createElement(z,{key:n,borderStyle:"single",borderColor:"gray",padding:1,flexDirection:"column"},N.createElement(H,{bold:!0},"Taste Learning"),N.createElement(H,{dimColor:!0},"Configure taste learning preferences for this project"),N.createElement(z,{marginTop:1}),N.createElement(z,{justifyContent:"space-between"},N.createElement(H,null,"Taste learning",N.createElement(H,{dimColor:!0}," - Learn from your interactions")),N.createElement(H,{color:r?"green":"gray"},r?"enabled":"disabled")),N.createElement(z,{marginTop:1}),N.createElement(H,{dimColor:!0},"Taste data stored in .commandcode/taste/taste.md"),N.createElement(H,{dimColor:!0},"Enter/Space to toggle • Esc to close"))},"TasteConfig"),Sa=__name(e=>{const[t,n]=_(e),[r,o]=_(null);return j(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):o(e.message)},"handleNewEvent");return Mo.on("reset",t),Mo.on("new-event",r),()=>{Mo.off("reset",t),Mo.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Bn({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o;if(n===rt)try{const e=await ut.getValidAccessToken();validateOAuthToken({token:e,provider:n}),o=e}catch(e){dlog("Failed to get or validate Anthropic OAuth token:",e instanceof Error?e.message:String(e))}const s={[Ze]:vo.getCurrentProjectDirName(),[Ye]:r.toString()};return o&&(s[Qe]=`Bearer ${o}`),{request:t,headers:s}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}__name(createRequestClient,"createRequestClient"),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch");var Ca="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Scan prompts. ${t} casual observations like a dev friend glancing at your work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words\n- sound human, not robotic\n\nPrompts:\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${Ca}`,max_tokens:200,temperature:.7,stream:!0},threadId:`observer-${Date.now()}`}}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),Mo.addEvent({type:"insight",message:n}))}e=t[t.length-1]}},"emitCompletedLines");return{addText:__name(r=>{t++,dlog(`[ObserverAPI] text chunk ${t}: "${r.substring(0,50)}..."`),e+=r,n()},"addText"),emitRemaining:__name(()=>{e.trim()&&(dlog(`[ObserverAPI] emitting final insight: ${e.trim()}`),Mo.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=Pe.fromReadableStream(e),dlog("[ObserverAPI] created MessageStream")}catch(e){throw dlog(`[ObserverAPI] MessageStream creation failed: ${e instanceof Error?e.message:String(e)}`),e}const n=createInsightEmitter();t.on("text",e=>{n.addText(e)});try{await t.finalMessage(),dlog(`[ObserverAPI] stream complete, ${n.getChunkCount()} chunks received`)}catch(e){throw dlog(`[ObserverAPI] stream failed: ${e instanceof Error?e.message:String(e)}`),e}n.emitRemaining()}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${et.ALPHA.GENERATE} with model: ${Ca}`);const r=buildRequestBody(n);let o;try{o=await e.post({endpoint:et.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(o),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const a=buildObserverPrompt(n,4);await callObserverAPI(e,t,a)}async function observeSessionPrompts(e){if(Mo.observerHasRun)return;Mo.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const o=Math.min(r.length,6);for(let t=0;t<o;t++){if(Mo.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const o=r[t];try{await processBatch(e,n,o,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),Mo.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var va=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(e=0){const t=[];try{const n=y.join(v.homedir(),".claude","projects");await x.access(n);const r=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${r}`);const o=(await x.readdir(n)).filter(e=>e===r);for(const r of o){const o=y.join(n,r);try{if(!(await x.stat(o)).isDirectory())continue;const n=(await x.readdir(o)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${n.length} sessions`);for(const r of n){const n=y.join(o,r),s=await x.stat(n),a=r.replace(".jsonl","");if(t.push({id:a,filePath:n,createdAt:s.birthtime,lastModified:s.mtime,messageCount:0,agent:"claude-code"}),e>0&&t.length>=e)break}if(e>0&&t.length>=e)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return t}static async findCodexSessions(e=0,t){try{Mo.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Mo.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await x.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[];try{Mo.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),s=o.tasteOnboarding?.learnedSessions||{},a=s["claude-code"]?.length||0,i=s.codex?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${i} learned`);const c=await findNewSessions(s),l=c["claude-code"]||[],d=c.codex||[],u=l.length+d.length;if(dlog(`[Import] findNewSessions returned: claude-code=${l.length} new, codex=${d.length} new`),0===u){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=e.length+t.length,r=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Mo.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:n>0?`From ${r.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:n,learnedSessions:a+i,agentSessions:o,status:"already-learned"}}if(l.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>l.includes(e.id));n.push(...e)}if(d.length>0){const e=(await this.findCodexSessions()).filter(e=>d.includes(e.id));r.push(...e)}const m=n.length+r.length;dlog(`[Import] total sessions: ${m} (claude-code: ${n.length}, codex: ${r.length})`),Mo.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const g=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of g){Mo.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const p=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${p.length} batches`);const h=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Mo.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${p.length} batch${1===p.length?"":"es"}`});try{const o=getApiBaseUrl(),s=new Bn({baseUrl:o});let a=!0;for(let e=0;e<p.length;e++){const t=p[e],n=e+1,r=p.length;r>1&&Mo.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),i=new Lo({request:s,sessionId:`taste-import-batch-${e}-${Date.now()}`,projectRoot:process.cwd()}),c=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await i.checkAndProcess({messages:c})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Mo.markLearningComplete(),await h,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const i=await this.extractLearningSummary(),c=[];if(n.length>0&&c.push(`Claude Code (${n.length})`),r.length>0&&c.push(`Codex (${r.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),Mo.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}return Mo.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${c.join(" + ")}`,learningCount:i.totalLearnings,categories:i.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:i.totalLearnings,errors:e,totalSessions:m,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),Mo.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const e=y.join(process.cwd(),".commandcode","taste","taste.md"),t=await x.readFile(e,"utf-8"),n=t.match(/^- .+Confidence:/gm),r=n?n.length:0;return{totalLearnings:r,categories:t.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},Ta=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),Aa=__name(e=>{const[t,n]=_({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return j(()=>{Mo.reset(),Mo.markImportStarted(),(async()=>{try{const t=await Promise.race([va.importAndLearn(),Ta(12e4)]);if(t.success)return void n(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void n(e=>({...e,isImporting:!1,alreadyLearned:!0,learnedSessionCount:t.learnedSessions||0,totalSessionCount:t.totalSessions||0,agentSessions:t.agentSessions||[],waitingForInput:!0}));const r=t.errors.join("\n");n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}catch(t){const r=t instanceof Error?t.message:String(t);n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}})()},[e]),t},"useImportProcess"),Pa=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{V((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput"),xa=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=_(null),[o,s]=_(null),a=U(!1);return j(()=>{if(a.current)return;let n=null;return(async()=>{try{a.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{Mo.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{Mo.reset(),e()}}__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var Ia=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=U(n),o=B(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=B(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),a=B(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),i=B(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current())},[e]),c=B(async()=>{dlog("[Handler] demo complete → done"),e("done"),await markDemoShown(),await completeOnboarding(()=>r.current())},[e]),l=B(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current())},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:a,handleErrorDismiss:i,handleDemoComplete:c,handleSkip:l}},"useOnboardingHandlers"),$a=__name(({conditions:e,autoLearn:t})=>{const[n,r]=_("checking"),o=U(!1);return j(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),j(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow"),Da=__name(({error:e})=>N.createElement(z,{padding:1},N.createElement(z,{flexDirection:"column",borderColor:"red",padding:1},N.createElement(z,{marginBottom:1},N.createElement(H,null,"Error initializing onboarding: ",e)),N.createElement(z,null,N.createElement(H,null,"Continuing without onboarding...")))),"OnboardingError"),Fa=[{type:"user",text:"I always prefer pnpm",duration:2e3},{type:"learned",text:"Learned: pnpm (95% preference)",details:".commandcode/taste/taste.md",duration:2e3},{type:"user",text:"I prefer commander over meow",duration:2e3},{type:"updated",text:"Updated: commander boosted (60% → 95%), meow adjusted (90% → 35%)",details:".commandcode/taste/cli/taste.md",duration:2e3},{type:"user",text:"I prefer TypeScript for Node CLIs",duration:2e3},{type:"learned",text:"Learned: TypeScript for CLIs (90% preference)",details:".commandcode/taste/cli/taste.md",duration:2e3}],Ra=__name(({onComplete:e})=>{const[t,n]=_(0),[r,o]=_(!1),s=t>=Fa.length;j(()=>{if(t>=Fa.length)return;if(r)return;const e=Fa[t],o=setTimeout(()=>{n(e=>Math.min(e+1,Fa.length))},e.duration);return()=>clearTimeout(o)},[t,r]),V((t,r)=>{r.escape?e():s?(r.return||" "===t)&&e():" "===t?o(e=>!e):r.return&&n(e=>Math.min(e+1,Fa.length))});const a=Fa.slice(0,t);return N.createElement(z,{flexDirection:"column"},N.createElement(z,null,N.createElement(H,{color:"cyan"},"Meet Your Coding Taste")),N.createElement(z,null,N.createElement(H,null,"Command Code learns your coding style as you work.")),N.createElement(z,null,N.createElement(H,null,"Here's how your preferences evolve in real-time:")),N.createElement(z,{flexDirection:"column",marginY:1},0===a.length&&!s&&N.createElement(H,{dimColor:!0},"Starting demo..."),a.map((e,t)=>"user"===e.type?N.createElement(z,{key:t},N.createElement(H,{color:"white"},`${ie.pointer} ${e.text}`)):N.createElement(z,{key:t,marginBottom:1,marginTop:0,marginLeft:1},N.createElement(z,null,N.createElement(H,null,"⎿"),N.createElement(z,{flexDirection:"column",marginLeft:2,marginTop:0},N.createElement(H,{color:"green"},e.text),e.details&&N.createElement(H,{dimColor:!0},"Saved(",e.details,")")))))),s&&N.createElement(z,{flexDirection:"column",marginY:1,width:80},N.createElement(z,null,N.createElement(H,{color:"green",bold:!0},"Demo Complete!"," ")),N.createElement(H,null,"Command Code will now use these preferences to generate better suggestions tailored to your coding style. The more you code, the smarter it gets."),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Press Enter to get started →"))),!s&&N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"[SPACE: pause] [ENTER: next] [ESC: skip]"," ",r?"(paused)":"")))},"TasteDemoComponent"),Ma=__name(()=>`(run /${ot} anytime)`,"getSkipHint"),Oa=__name(()=>N.createElement(H,null,"Skip for now"," ",N.createElement(H,{dimColor:!0},Ma())),"SkipOptionText"),La=__name(({sessionCount:e,agentSessions:t,onImport:n,onDemo:r,onSkip:o,demoShown:s=!1})=>{const[a,i]=_(1),c=s?2:3,l=s?2:3;return V((e,t)=>{if(t.escape)o();else if(t.upArrow)i(e=>1===e?c:e-1);else if(t.downArrow)i(e=>e===c?1:e+1);else if("1"!==e)if("2"!==e)if("3"!==e||s){if(t.return){if(1===a)return void n();if(2===a)return void(s?o():r());o()}}else o();else s?o():r();else n()}),N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,paddingY:0},N.createElement(H,{color:"cyan",bold:!0},"Build Your Coding Taste"),N.createElement(z,{marginTop:1,flexDirection:"column"},N.createElement(H,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),N.createElement(z,{marginTop:1},N.createElement(H,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),N.createElement(z,{marginTop:1,flexDirection:"column"},N.createElement(z,null,N.createElement(H,{color:1===a?"cyan":"gray"},1===a?ie.pointer:" "," 1. Yes, learn from my sessions (recommended)")),!s&&N.createElement(z,null,N.createElement(H,{color:2===a?"cyan":"gray"},2===a?ie.pointer:" "," ","2. No, show me a demo instead")),N.createElement(z,null,N.createElement(H,{color:a===l?"cyan":"gray"},a===l?ie.pointer:" "," ",l,". ",N.createElement(Oa,null)))),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice"),Na=__name(({onDemo:e,onSkip:t})=>{const[n,r]=_(1);return V((o,s)=>{s.escape?t():s.upArrow||s.downArrow?r(e=>1===e?2:1):"1"!==o?"2"!==o?s.return&&(1===n?e():t()):t():e()}),N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",padding:1},N.createElement(H,{color:"cyan",bold:!0},"No Previous Sessions Found"),N.createElement(z,{marginTop:1,flexDirection:"column"},N.createElement(H,null,"No previous sessions found to analyze."),N.createElement(z,{marginTop:1},N.createElement(H,null,"Would you like to see how taste learning works?"))),N.createElement(z,{marginTop:1,flexDirection:"column"},N.createElement(z,null,N.createElement(H,{color:1===n?"cyan":"gray"},1===n?ie.pointer:" "," 1. Yes, show me a demo")),N.createElement(z,null,N.createElement(H,{color:2===n?"cyan":"gray"},2===n?ie.pointer:" "," 2."," ",N.createElement(Oa,null)))),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Use arrow keys or numbers to select, Enter to confirm")))},"NoSessionsChoice"),_a=__name(({error:e})=>N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"red",paddingX:2,paddingY:1,marginBottom:2},N.createElement(H,{color:"red",bold:!0},"Oops, something went wrong:"),N.createElement(z,{marginTop:1},N.createElement(H,null,e))),"ErrorSection"),Ua=[ie.bullet,ie.squareSmallFilled,ie.lozenge,ie.star,ie.triangleRight,ie.triangleUp,ie.circleFilled,ie.pointer],ja=__name(()=>N.createElement(H,{backgroundColor:"green",color:"black"}," TASTE "),"TasteBadge"),Ba=["percolating","excavating","deciphering","triangulating","osmosing","metabolizing","grokking","spelunking","interpolating","marinating","crystallizing","synthesizing","calibrating","fermenting","coalescing","transmuting","simmering","distilling","ruminating","perusing","assimilating","untangling","decoding","absorbing","harmonizing","digesting","contemplating","extrapolating","materializing","finalizing"],Wa=__name(()=>{const[e,t]=_(()=>Math.floor(Math.random()*Ba.length));j(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*Ba.length))},2e3);return()=>clearInterval(e)},[]);const n=Ba[e];return N.createElement(H,{color:"yellow"},n,"...")},"PulsingText"),za=__name(e=>String(e).padStart(3," "),"padNum"),Ha=__name(e=>Ua[e%Ua.length],"getSymbol"),Ga=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${za(t)} ↓${za(n)} (↑↓ scroll)`,"buildStatusLine"),qa=__name(({insights:e})=>{const[t,n]=_(0),[r,o]=_(!0),s=e.length,a=s>10,i=Math.max(0,s-10);if(j(()=>{r&&a&&n(i)},[s,r,a,i]),V((e,t)=>{if(a)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(i,e+1);return t===i&&o(!0),t}))}),0===s)return null;const c=e.slice(t,t+10),l=t,d=s-t-10;return N.createElement(z,{flexDirection:"column",marginLeft:4,marginBottom:0},a&&N.createElement(H,{dimColor:!0},Ga(s,l,d,r)),c.map((e,n)=>{const r=t+n;return N.createElement(z,{key:r,marginBottom:0},N.createElement(H,{dimColor:!0},Ha(r)," ",e))}))},"ScrollableInsights"),Va=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:a,isAllComplete:i,summary:c})=>{if(a)return N.createElement(z,{flexDirection:"column",marginBottom:0},N.createElement(ja,null),N.createElement(z,{marginTop:0},N.createElement(H,{dimColor:!0},"⎿"),N.createElement(z,{marginLeft:2},i?N.createElement(H,{color:"green"},"learned your coding taste"):N.createElement(Wa,null))));const l=__name(()=>{const[e,t]=_(!0);return j(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),N.createElement(H,{color:"yellow"},e?ie.circleFilled:ie.circle)},"PulsingDot"),d=__name(()=>r?N.createElement(H,{color:"green"},ie.nodejs):n?N.createElement(l,null):N.createElement(H,{dimColor:!0},ie.circle),"getStatusIcon"),u=o.length>0||s.length>0||t||c&&c.learningCount>0;return!r||n||u?N.createElement(z,{flexDirection:"column",marginBottom:0},(n||r)&&N.createElement(z,{marginBottom:0},N.createElement(z,{marginRight:1},d()),N.createElement(H,{color:r?"white":n?"yellow":"dim"},e)),r&&t&&(!c||0===c.learningCount)&&N.createElement(z,{marginLeft:3,marginBottom:0},N.createElement(H,{dimColor:!0},t)),o.length>0&&N.createElement(z,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>N.createElement(H,{key:t,dimColor:!0},`${ie.bullet} ${e}`))),s.length>0&&N.createElement(qa,{insights:s}),r&&c&&c.learningCount>0&&N.createElement(z,{flexDirection:"column",marginLeft:1,marginBottom:0},N.createElement(z,{marginBottom:1,flexDirection:"row"},N.createElement(H,null,"⎿"),N.createElement(z,{marginLeft:2},N.createElement(H,{color:"green"},"Learned ",c.learningCount," preference",1===c.learningCount?"":"s",c.categories.length>0?` across ${c.categories.length} ${1===c.categories.length?"category":"categories"}`:""))),N.createElement(z,{flexDirection:"column",marginLeft:1},N.createElement(H,{dimColor:!0},ie.pointerSmall," Stored in"," ",c.storage),N.createElement(H,{dimColor:!0},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),Ka=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return N.createElement(z,{flexDirection:"column",marginBottom:1},e.map((e,n)=>N.createElement(z,{key:e.id,marginLeft:0===n?0:3},N.createElement(Va,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),Ja=__name(({steps:e})=>N.createElement(Ka,{steps:e}),"ProgressSection"),Ya=__name(({isImporting:e=!1,waitingForInput:t=!1})=>N.createElement(N.Fragment,null,e&&N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"ESC to cancel")),t&&N.createElement(z,{marginTop:1},N.createElement(H,{bold:!0},"Press ENTER to continue"))),"HelpTextSection"),Qa=[{id:"importing",label:"Initializing Taste Profile",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"batching",label:"Organizing your sessions",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"learning",label:"Learning your coding taste",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"complete",label:"Learned your coding taste!",message:"",active:!1,complete:!1,items:[],insights:[],summary:{learningCount:0,categories:[],storage:".commandcode/taste/taste.md"}}],Za=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=Sa(Qa),{isImporting:s,waitingForInput:a,error:i}=Aa(t);return Pa({onEscape:e,onEnter:__name(()=>{a&&(i&&n?n():e())},"onEnter"),enabled:s||a}),N.createElement(z,{flexDirection:"column",padding:1},o&&N.createElement(_a,{error:o}),!o&&N.createElement(Ja,{steps:r}),N.createElement(Ya,{isImporting:s,waitingForInput:a}))},"ImportProgress"),Xa=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onDemoComplete:a,onDemo:i,onSkip:c})=>"asking"===e?"has_sessions"!==t?.reason?N.createElement(Na,{onDemo:i,onSkip:c}):N.createElement(La,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onDemo:i,onSkip:c,demoShown:t.demoShown}):"learning"===e?N.createElement(Za,{onComplete:r,onError:o,onErrorDismiss:s}):"demo"===e?N.createElement(Ra,{onComplete:a}):null,"OnboardingStepRenderer"),ei=__name(({onComplete:e,autoLearn:t=!1})=>{j(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=xa({autoLearn:t,onShouldSkip:e}),{step:s,setStep:a}=$a({conditions:n,autoLearn:t}),{handleImportStart:i,handleImportComplete:c,handleImportError:l,handleErrorDismiss:d,handleDemoComplete:u,handleSkip:m}=Ia({onStepChange:__name(e=>{a(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?N.createElement(Da,{error:r}):"done"===s?null:N.createElement(Xa,{step:s,conditions:n,onImportStart:i,onImportComplete:c,onImportError:l,onErrorDismiss:d,onDemoComplete:u,onDemo:()=>a("demo"),onSkip:m})},"TasteOnboarding"),ti=__name(({onTrust:e,onExit:t})=>{const{exit:n}=K(),[r,o]=_(1),s=process.cwd().replace(process.env.HOME||"","~");return V((s,a)=>{a.upArrow||a.downArrow?o(1===r?2:1):a.return?1===r?e():(t(),n()):"1"===s?e():("2"===s||a.escape||a.ctrl&&"c"===s)&&(t(),n())}),N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"yellow",padding:1},N.createElement(H,{color:"yellow",bold:!0},"Do you trust the files in this folder?"),N.createElement(z,{marginTop:1},N.createElement(H,{color:"gray"},s)),N.createElement(z,{marginTop:1,flexDirection:"column"},N.createElement(H,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),N.createElement(z,{marginTop:1},N.createElement(H,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),N.createElement(z,{marginTop:1,flexDirection:"column"},N.createElement(z,null,N.createElement(H,{color:1===r?"cyan":"gray"},1===r?ie.pointer:" "," 1. Yes, proceed")),N.createElement(z,null,N.createElement(H,{color:2===r?"cyan":"gray"},2===r?ie.pointer:" "," 2. No, exit"))))},"TrustPrompt"),ni=__name(({onComplete:e,onCancel:t})=>{const[n,r]=_(!1),[o,s]=_(""),{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u,cancel:m}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return V((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");m()}}),n?N.createElement($t,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):N.createElement(Xt,{authState:a,statusMessage:i,browserUrl:c,apiKeyInput:l,setApiKeyInput:d,handleApiKeySubmit:u})},"LoginOverlay"),ri=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;constructor(){this.filePath=y.join(v.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await x.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean).slice(-100);let t=0;this.buffer=e.map(e=>{try{return JSON.parse(e).p}catch{return t++,""}}).filter(Boolean),t>0&&dlog(`[PromptHistory] Skipped ${t} corrupted entries`)}catch(e){e instanceof Error&&"code"in e&&"ENOENT"===e.code||dlog(`[PromptHistory] Failed to load history: ${e instanceof Error?e.message:String(e)}`),this.buffer=[]}this.initialized=!0}}add(e){if(!e||0===e.trim().length)return;const t=e.length>500?e.slice(0,500)+"...":e;this.buffer.push(t),this.buffer.length>500&&(this.buffer=this.buffer.slice(-500)),this.writeQueue.push({p:t,t:Date.now()}),this.scheduleFlush()}getAt(e){if(e<0||e>=this.buffer.length)return;const t=this.buffer.length-1-e;return this.buffer[t]}count(){return this.buffer.length}getAll(){return[...this.buffer]}isInitialized(){return this.initialized}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,await this.flush()},100))}async flush(){if(0===this.writeQueue.length)return;if(this.isFlushing)return void this.scheduleFlush();if(this.writeFailures>=3)return void(this.writeQueue=[]);this.isFlushing=!0;const e=this.writeQueue;this.writeQueue=[];try{const t=y.dirname(this.filePath);await x.mkdir(t,{recursive:!0});const n=e.map(e=>JSON.stringify(e)).join("\n")+"\n";await x.appendFile(this.filePath,n),this.writeFailures=0,await this.rotateIfNeeded()}catch(t){this.writeFailures++;const n=t instanceof Error?t.message:String(t);this.writeFailures<3?(this.writeQueue.unshift(...e),dlog(`[PromptHistory] Write failed, retrying (${this.writeFailures}/3): ${n}`)):dlog(`[PromptHistory] Write disabled after 3 failures: ${n}`)}finally{this.isFlushing=!1}}async rotateIfNeeded(){try{const e=await x.stat(this.filePath);if(e.size<=5242880)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await x.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=t.slice(-100);await x.writeFile(this.filePath,n.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${n.length} of ${t.length} entries`)}catch(e){dlog(`[PromptHistory] Rotation failed (non-critical): ${e instanceof Error?e.message:String(e)}`)}}async cleanup(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);const e=Date.now();for(;this.isFlushing;){if(Date.now()-e>=5e3){dlog("[PromptHistory] Cleanup timed out waiting for flush after 5000ms");break}await new Promise(e=>setTimeout(e,10))}await this.flush()}};function createHistoryManager(){return new ri}__name(createHistoryManager,"createHistoryManager");var oi=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),si=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r})=>{const o=[];e.forEach((s,a)=>{const i=a===t&&!r,c=n.has(a);let l,d;i?(l="●",d="cyan"):c?(l="✓",d="green"):(l="○",d="gray"),o.push(N.createElement(H,{key:a},N.createElement(H,{color:d},l),N.createElement(H,{color:i?"cyan":void 0}," ",s.header),a<e.length-1?N.createElement(H,{dimColor:!0}," | "):null))});const s=r;return o.push(N.createElement(H,{key:"review"},N.createElement(H,{dimColor:!0}," | "),N.createElement(H,{color:s?"cyan":"gray"},s?"●":"○"),N.createElement(H,{color:s?"cyan":void 0,bold:s}," ","Review"))),N.createElement(z,null,o)},"TabIndicator"),ai=__name(({questions:e,onResponse:t})=>{const[n,r]=_(0),[o,s]=_(new Map),a=U(new Map),[i,c]=_(""),[l,d]=_(new Set),[u,m]=_(null),[g,p]=_(!1),[h,f]=_(!1),[y,w]=_(!1),[E,b]=_(null),[k,S]=_(!1),C=e[n],v=C?.multiSelect??!1,T=o.get(n),A=C?[...C.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],P=A.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),x=new Map(P.map((e,t)=>[e.label,A[t]])),I=__name(e=>{"submit"===e.value?O():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),$=__name(()=>{if(!T||0===T.length)return 0;const e=T[0],t=C.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),D=__name(e=>{if(!g)if(v){const t=oi(e.value,C.options.length-1);if(null===t)return;const n=C.options[t]?.label||"";d(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=oi(e.value,C.options.length-1);if(null===t)return;p(!0);const n=C.options[t]?.label||"";M([n])}},"handleSelect"),F=__name(()=>{if(g)return;p(!0);const e=Array.from(l);M(e)},"handleMultiSelectDone"),R=__name(()=>{if(!g&&i.trim())if(v){const e=new Set(C.options.map(e=>e.label));d(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(i.trim()),n})}else p(!0),M([i.trim()])},"handleOtherSubmit"),M=__name(t=>{a.current.set(n,t);const o=new Map(a.current);s(o);const i=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){d(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),n?.multiSelect||1!==r?.length)c("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);c(t&&e?e:"")}},"restoreStateForQuestion");if(n<e.length-1){const e=n+1;i(e),r(e),p(!1),w(!1),b(null),S(!1)}else if(e.every((e,t)=>o.has(t)))d(new Set),c(""),f(!0),p(!1);else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(i(t),r(t)),p(!1),w(!1),b(null),S(!1)}},"finishQuestion"),O=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),L=__name(t=>{f(!1),r(t),S(!1),w(!1),b(null);const n=e[t],o=a.current.get(t);if(n?.multiSelect&&o){d(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),n?.multiSelect||1!==o?.length)c("");else{const e=o[0],t=!n.options.some(t=>t.label===e);c(t&&e?e:"")}},"editQuestion"),j=__name(t=>{if(t<0||t>=e.length)return;v&&(l.size>0?a.current.set(n,Array.from(l)):a.current.delete(n),s(new Map(a.current))),p(!1),w(!1),b(null),S(!1);const o=e[t],i=a.current.get(t);if(o?.multiSelect&&i){d(new Set(i));const e=i.find(e=>!o.options.some(t=>t.label===e));c(e||"")}else if(d(new Set),o?.multiSelect||1!==i?.length)c("");else{const e=i[0],t=!o.options.some(t=>t.label===e);c(t&&e?e:"")}r(t)},"navigateToQuestion"),B=__name(()=>{if(!u||!v)return;if("done"===u.value)return;const e=oi(u.value,C.options.length-1);if(null===e)return;const t=C.options[e]?.label||"";d(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return V((t,r)=>{if(" "===t&&v&&!y&&B(),"d"!==t||!v||y||h||F(),!h&&!g){if(r.downArrow&&!y&&!k&&u&&P.length>0&&u.value===P[P.length-1]?.value&&w(!0),r.upArrow&&!y&&!k&&u&&P.length>0&&u.value===P[0]?.value&&(v?S(!0):(w(!0),b(P.length-1))),r.upArrow&&y){w(!1),b(P.length-1);const e=P[P.length-1];e&&m(e)}if(r.downArrow&&y)if(w(!1),v)S(!0);else{b(0);const e=P[0];e&&m(e)}if(r.upArrow&&k&&(S(!1),w(!0)),r.downArrow&&k){S(!1),b(0);const e=P[0];e&&m(e)}r.return&&k&&v&&F()}if(g||y||k||(h?r.leftArrow&&L(e.length-1):r.leftArrow&&n>0?j(n-1):r.rightArrow&&(n<e.length-1?j(n+1):(v&&(l.size>0?a.current.set(n,Array.from(l)):a.current.delete(n),s(new Map(a.current))),f(!0)))),r.escape&&!g)if(h)f(!1);else if(y){w(!1);const e=E??P.length-1;b(e);const t=P[e];t&&m(t)}else if(k){S(!1);const e=P[P.length-1];e&&m(e)}}),C||h?h?N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},N.createElement(z,{marginBottom:1},N.createElement(si,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>N.createElement(z,{key:t,marginBottom:1,flexDirection:"column"},N.createElement(H,{dimColor:!0},t+1,". ",e.question),N.createElement(H,{color:"green"}," ",o.get(t)?.join(", ")||"No answer"))),N.createElement(Fe,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:I,initialIndex:0,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:"cyan"},e?ie.pointer:" "),itemComponent:({label:e,isSelected:t})=>N.createElement(H,{color:t?"cyan":"white"},e)}),N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},ie.arrowLeft," to go back and edit"))):N.createElement(z,{flexDirection:"column",borderStyle:"single",borderColor:"gray",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},N.createElement(z,{marginBottom:1},N.createElement(si,{questions:e,currentIndex:n,answeredQuestions:new Set(o.keys()),isReviewPage:!1})),N.createElement(z,{marginBottom:1},N.createElement(H,{bold:!0},C.question)),y||k?N.createElement(z,{flexDirection:"column"},P.map((e,t)=>{const n=x.get(e.label),r=v&&n&&l.has(n.label),o=!v&&n&&T?.includes(n.label),s=r||o;return N.createElement(z,{key:t,flexDirection:"column"},N.createElement(z,null,N.createElement(H,null," "),N.createElement(H,{color:s?"green":"white"}," ",t+1,"."," "),v&&(s?N.createElement(H,{color:"green"},"[",ie.tick,"]"," "):N.createElement(H,{dimColor:!0},"[ ] ")),N.createElement(H,{color:s?"green":"white"},n?.label||""),!v&&s&&N.createElement(H,{color:"green"}," ",ie.tick)),n?.description&&N.createElement(z,null,N.createElement(H,null," "),N.createElement(H,{dimColor:!0},v?" ":" ",n.description)))})):N.createElement(Fe,{key:`${n}-${E??"default"}`,items:P,initialIndex:E??$(),onSelect:D,onHighlight:m,indicatorComponent:({isSelected:e})=>N.createElement(H,{color:"cyan"},e?ie.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=x.get(e),r=v&&n&&l.has(n.label),o=!v&&n&&T?.includes(n.label),s=r||o,a=e.match(/^\s*(\d+)\.\s*(.*)$/),i=a?.[1]||"",c=a?.[2]||e;return N.createElement(z,{flexDirection:"column"},N.createElement(z,null,N.createElement(H,{color:t?"cyan":s?"green":"white"}," ",i,"."," "),v&&(s?N.createElement(H,{color:"green"},"[",ie.tick,"]"," "):N.createElement(H,{dimColor:!0},"[ ] ")),N.createElement(H,{color:t?"cyan":s?"green":"white"},c),!v&&s&&N.createElement(H,{color:"green"}," ",ie.tick)),n?.description&&N.createElement(H,{dimColor:!0},v?" ":" ",n.description))}}),N.createElement(z,null,N.createElement(H,{color:"cyan"},y?ie.pointer:" "),N.createElement(H,{color:y?"cyan":void 0}," ",P.length+1,"."," "),v&&(l.has(i.trim())?N.createElement(H,{color:"green"},"[",ie.tick,"] "):N.createElement(H,{dimColor:!0},"[ ] ")),N.createElement(Be,{value:i,onChange:e=>{const t=i.trim();c(e),v&&d(n=>{const r=new Set(n);return t&&r.has(t)&&r.delete(t),e.trim()&&r.add(e.trim()),r})},onSubmit:R,placeholder:"Type something...",focus:y})),v&&N.createElement(z,null,N.createElement(H,{color:"cyan"},k?ie.pointer:" "),N.createElement(H,{color:k?"cyan":void 0,bold:k}," ",n===e.length-1?"Submit":"Next")),e.length>1&&N.createElement(z,{marginTop:1},N.createElement(H,{dimColor:!0},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function LiveAgentStatusInner({entry:e}){const t=Mr(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,a=e.metadata?.elapsedSeconds||0,i=e.metadata?.recentTools||[],[c,l]=_(".");return j(()=>{const e=setInterval(()=>{l(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),N.createElement(z,{flexDirection:"column",marginBottom:1,width:"90%"},N.createElement(z,null,N.createElement(H,{backgroundColor:"#4C3575",color:"#F3E8FF",bold:!0},` ${t} `),o&&N.createElement(H,null," ","(",o,")")),N.createElement(z,{columnGap:1,marginLeft:1},N.createElement(H,null,"⎿"," "),N.createElement(H,{color:"gray"},"Running (",formatTime2(a)," | ",formatTokens(s),")",c)),i.length>0&&N.createElement(z,{flexDirection:"column",marginLeft:1},i.map((e,t)=>{const n=Mr(e.name);return N.createElement(z,{key:t,columnGap:1},N.createElement(H,{color:"gray"},"⎿"),N.createElement(H,{color:"gray"}," ",n),e.input&&N.createElement(H,{color:"gray"},"(",e.input,")"))})))}function LiveAgentStatus({entry:e}){return"tool"!==e.role?null:N.createElement(LiveAgentStatusInner,{entry:e})}__name(LiveAgentStatusInner,"LiveAgentStatusInner"),__name(LiveAgentStatus,"LiveAgentStatus");var{setText:ii}=Se;function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}__name(createKillShellPermissionRequest,"createKillShellPermissionRequest");var ci=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:o,updateFailedInfo:s,initialPrompt:a,skipOnboarding:i=!1})=>{const{exit:c}=K(),[l,d]=_(""),[u,m]=_("Ready..."),[g,p]=_(null),[h,f]=_(o);j(()=>{if(h){const e=setTimeout(()=>{f(null)},3e4);return()=>clearTimeout(e)}},[h]);const{stdout:y}=J(),[w,E]=_(!1),[b,k]=_(!1),[S,C]=_(!1),[v,T]=_(!1),[A,P]=_(!1),[x,I]=_(!1),[$,D]=_(!1),[F,R]=_(!1),[M,O]=_(null),[L,W]=_(null),[G,q]=_(getConfiguredModel()),[Y,Q]=_(!1),[Z,X]=_(!1),[ee,te]=_(!1),ne=U(null),re=U(null),[oe,se]=_(0),[ae,ie]=_(!1),{executeBash:ce,executionState:le}=Bo(),[de,ue]=_(""),[me,ge]=_([]),[pe,he]=_([]),[fe,ye]=_(!1),[we,Ee]=_([]),[be,ke]=_(crypto.randomUUID()),[Se,Ce]=_(!1),[ve,Te]=_(!1),Ae=U(null),[Pe,xe]=_(!1),[Ie,$e]=_(!1),[De,Fe]=_(!0),[Re,Me]=_(!1),[Oe,Le]=_(!1),[Ne,_e]=_(null),[Ue,je]=_(!1),Be=U(!1),[We,ze]=_(!1),[He,Ge]=_(0),[qe,Ve]=_(null),[Ke,Je]=_(null),[Ye,Qe]=_(null),Ze=U(!1),Xe=U(!1),tt=U(Ye);j(()=>{tt.current=Ye},[Ye]);const[nt,rt]=_(!1),[ot,at]=_(""),[it,ct]=_(!1),[dt,mt]=_(!!r),[gt,pt]=_(""),ht=U(null),ft=U(null),yt=__name(()=>{ht.current&&clearTimeout(ht.current),ft.current&&clearTimeout(ft.current),ne.current&&clearTimeout(ne.current),re.current&&clearTimeout(re.current)},"cleanupTimers"),[wt,Et]=_(!1),[bt,kt]=_(!1),St=U(null),Ct=U(0),[vt,Tt]=_(null),At=B(()=>{St.current=null,Tt(null),ft.current&&(clearTimeout(ft.current),ft.current=null)},[]);j(()=>{if(We){yt();try{c()}catch{process.exit(0)}}},[We,c]);const Pt=B(()=>{Le(!0),Me(!1),je(!1),Ho(),se(e=>e+1),e&&Ce(!0)},[e,t]),xt=__name(async()=>{try{const e=await isTasteLearningEnabled();ct(e),e&&await hs.initializeProject()}catch(e){}},"loadTasteStatus"),It=__name(async()=>{const e=await getConfiguredProvider();W(e);const t=await isOAuthEnforced();Q(t)},"loadCurrentProvider"),$t=U([]),Dt=U(null),Ft=U(null),[Rt,Mt]=_(null),[Ot,Lt]=_(null),{requestShellPermission:Nt,service:_t,respondToPrompt:Ut,clearSessionPermissions:jt,setEnabled:Bt}=zo({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{Mt({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),Dt.current&&m("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{Mt({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),Dt.current&&m("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?m("Permission granted"):m("Permission denied")},"onPermissionResponse")}),Wt=__name(e=>{ht.current&&clearTimeout(ht.current),pt(e),ht.current=setTimeout(()=>{pt(""),ht.current=null},5e3)},"showHintMessage");j(()=>()=>yt(),[]),j(()=>{_t&&applyAutoAcceptMode({enabled:dt,service:_t})},[dt,_t]),j(()=>{(async()=>{if(await vo.isProjectInitialized())if($e(!0),Fe(!1),xt(),It(),t){const e=await vo.listSessions();if(e.length>0){const t=e[0];dn(t.id)}}else e&&Ce(!0);else if(n)if(await vo.initializeProject(),$e(!0),Fe(!1),xt(),It(),t){const e=await vo.listSessions();if(e.length>0){const t=e[0];dn(t.id)}}else e&&Ce(!0);else isDirectoryEmpty()?(await vo.initializeProject(),$e(!0),Fe(!1),xt(),It()):(xe(!0),Fe(!1))})()},[e,t,n,c]),j(()=>{i||triggerTasteOnboarding({projectTrusted:Ie,onboardingComplete:Oe,isOnboardingMode:Re,tasteOnboardingCheckedRef:Be,setIsOnboardingMode:Me})},[Ie,Oe,Re,i]),j(()=>{if(Re&&!Ne){const e=Tr();_e(e.id),ge(t=>[...t,e])}else!Re&&Ne&&(ge(e=>e.filter(e=>e.id!==Ne)),_e(null))},[Re,Ne]),j(()=>{$t.current=we},[we]),j(()=>{(async()=>{if(L&&"anthropic"===L&&Y)try{await ut.getValidAccessToken()||m("OAuth setup required. Use /provider to select Claude and authenticate.")}catch(e){m("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[L,Y]),j(()=>{if(!fe)return;if(null!==g)return;const e=setInterval(()=>{m(Rr())},7e3);return()=>clearInterval(e)},[fe,g]);const zt=B(()=>{const e=!fe&&!Rt&&!Ot,t=Dt.current?.hasCheckpoints()??!1;e&&t&&Et(!0)},[fe,Rt]),Ht=__name(()=>{mt(e=>{const t=!e;return t&&Rt&&(Ut({label:"Yes",value:"yes",description:"Allow this action",scope:void 0}),Rt.resolve(!0),Mt(null)),t})},"handleToggleAutoAccept");async function getBillingLink(){if(Ke)return Ke;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"}}V((e,t)=>{if(t.shift&&t.tab||""===e)Ht();else if(S||v||A||x||$||M||F||wt||bt)vt&&At();else{if(""===e||t.ctrl&&"c"===e){const e=Date.now(),t=e-Ct.current;return Ct.current=e,void("ctrl-c"===St.current&&t<2e3?(ft.current&&(clearTimeout(ft.current),ft.current=null),ze(!0)):(d(""),St.current="ctrl-c",Tt("ctrl-c"),ft.current&&clearTimeout(ft.current),ft.current=setTimeout(()=>{St.current=null,Tt(null),ft.current=null},2e3)))}if(t.ctrl&&"t"===e)return Ho(),R(e=>!e),void se(e=>e+1);if(getIsExpandToolShortcut(t,e))return Ho(),ie(e=>!e),void se(e=>e+1);if(t.escape){if(Ot)return Ot.reject(new Error("Question cancelled by user")),Lt(null),void m("Question cancelled");if(Rt)Ut({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),Rt.resolve(!1),Mt(null),m("Permission denied");else if(fe&&Dt.current){Dt.current.interrupt(!0);const e=pe.length>0;if(ye(!1),p(null),he([]),m("Interrupted by user"),!e){const e=vr("Interrupted by user");ge(t=>[...t,e])}if($t.current.length>0){const e=$t.current.join("\n");d(t=>t?e+"\n"+t:e),Ee([]),$t.current=[]}}}t.meta||t.ctrl}}),j(()=>{const e=__name(()=>{Ho(),se(e=>e+1)},"handleResize");if(y)return y.on("resize",e),()=>{y.off("resize",e)}},[y]),j(()=>{Dt.current||!Ie||Se||ve||(Dt.current=new _o({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?he(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(he(t=>t.filter(t=>t.id!==e.id)),ge(t=>[...t,e])):ge(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...$t.current];return $t.current=[],Ee([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ge(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ve(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{p(e)},"onRetryUpdate"),onProviderChange:__name(e=>{W(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&_t){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 _t.requestShellPermission(n).then(e=>e.allowed)}if("kill_shell"===e&&_t){const e=createKillShellPermissionRequest(t);return _t.requestShellPermission(e).then(e=>e.allowed)}if(_t){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 _t.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Lt({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=tt.current;return e?{sessionId:be,secret:e.secret}:null},"getShareInfo")},be),(async()=>{await en()})())},[be,Se,ve,Ie]),j(()=>{if(!Ie)return;const e=createHistoryManager();return Ae.current=e,e.init(),()=>{e.cleanup()}},[Ie]),j(()=>{a&&Ie&&!De&&Dt.current&&!Se&&!Xe.current&&(Xe.current=!0,Gt({role:"user",input:a}))},[a,Ie,De,Se]),__name(getBillingLink,"getBillingLink");const Gt=__name(async({role:e,input:t,images:n})=>{if(t.length)if(h&&f(null),Ge(0),"bash"===e){if(Ze.current)return;Ze.current=!0;const e=Sr(t);ge([...me,e]),d(""),await ce(t,e=>{ge(e)},()=>{Ho(),se(e=>e+1)}),Ze.current=!1}else{if(fe)return Ee(e=>[...e,t]),void d("");if(Ze.current)return;Ze.current=!0,ye(!0),m(Rr()),d("");try{Dt.current&&await Dt.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){m("Insufficient credits");const e=await getBillingLink(),t=vr(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${e}`);ge(e=>[...e,t])}else if(e.message.startsWith("Error:")){m("Error");const t=vr(e.message);ge(e=>[...e,t])}else{m("Error");const t=e.message||"An unexpected error occurred",n=vr(t);ge(e=>[...e,n])}}finally{ye(!1),"Interrupted by user"!==u&&"Permission denied"!==u&&"Insufficient credits"!==u&&m("Ready..."),Ze.current=!1}}},"handleSubmit"),qt=__name(()=>{ge(e=>[...e,Cr("KEYBOARD SHORTCUTS\nCOMMANDS")])},"handleHelpCommand"),Vt=__name(()=>{const e=wr("/terminal-setup"),t=setupVSCodeTerminal(),n=Ar(t.message,!t.success,t.details);ge(t=>[...t,e,n])},"handleTerminalSetupCommand"),Kt=__name(async()=>{if(ge([]),he([]),Ho(),mt(!!r),Qe(null),rt(!1),at(""),Dt.current){const e=Dt.current.getSessionManager();e&&await e.deleteShareInfo(),Dt.current=null;const t=crypto.randomUUID();ke(t),jt(),Dt.current=new _o({onFeedUpdate:__name(e=>{const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?he(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(he(t=>t.filter(t=>t.id!==e.id)),ge(t=>[...t,e])):ge(t=>[...t,e])},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...$t.current];return $t.current=[],Ee([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ge(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ve(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{p(e)},"onRetryUpdate"),onProviderChange:__name(e=>{W(e)},"onProviderChange"),onPermissionRequest:__name(async(e,t)=>{if("shell_command"===e&&_t){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 _t.requestShellPermission(n).then(e=>e.allowed)}if("kill_shell"===e&&_t){const e=createKillShellPermissionRequest(t);return _t.requestShellPermission(e).then(e=>e.allowed)}if(_t){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 _t.requestPermission(n).then(e=>e.allowed)}return Promise.resolve(!0)},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Lt({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const e=tt.current;return e?{sessionId:t,secret:e.secret}:null},"getShareInfo")},t)}se(e=>e+1),Ve(null),Ge(0)},"handleClearCommand"),Jt=__name(()=>{Dt.current?Dt.current.hasCheckpoints()?Et(!0):ge(e=>[...e,Er("No checkpoints available. Start sending messages to create checkpoints.")]):ge(e=>[...e,Er("No active conversation to rewind.")])},"handleRewindCommand"),Yt=__name(async e=>{const{messageId:t,mode:n}=e;if(Et(!1),Dt.current)try{const e=Dt.current.listCheckpoints().find(e=>e.messageId===t);m("Restoring checkpoint...");const r=await Dt.current.restoreToCheckpoint({messageId:t,mode:n});if(r.success){const t=Dt.current.getSessionManager(),n=Dt.current.getMessages(),o=t.reconstructFeedFromMessages(n);ge(o),Ho(),se(e=>e+1),e&&e.userPrompt&&d(e.userPrompt);const s=[];r.filesRestored>0&&s.push(`${r.filesRestored} file${r.filesRestored>1?"s":""} restored`),r.filesDeleted>0&&s.push(`${r.filesDeleted} file${r.filesDeleted>1?"s":""} deleted`),r.messagesRemoved>0&&s.push(`${r.messagesRemoved} message${r.messagesRemoved>1?"s":""} removed`);const a=s.length>0?`Restored to checkpoint: ${s.join(", ")}.`:"Restored to checkpoint.";ge(e=>[...e,Er(a)]),m("Ready...")}else ge(e=>[...e,vr(`Failed to restore: ${r.error}`)]),m("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;ge(e=>[...e,vr(t)]),m("Ready...")}},"handleRewindSelect"),Qt=__name(()=>{Et(!1)},"handleRewindCancel"),Zt=__name(async()=>{if(Dt.current)if(Dt.current.isRequestInProgress())ge(e=>[...e,Er("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{m("Compacting conversation...");const e=await Dt.current.compactConversation();Ho(),se(e=>e+1);const t=e.messagesRemoved>0?`Compacted conversation, saved ~${e.tokensSaved.toLocaleString()} tokens.`:"Conversation is already compact.";ge(e=>[...e,Er(t)]),m("Ready..."),Ve({current:Dt.current.getContextTokensUsed()||0,limit:So})}catch(e){const t=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;ge(e=>[...e,vr(t)]),m("Ready...")}else ge(e=>[...e,Er("No active conversation to compact.")])},"handleCompactCommand"),Xt=__name(async e=>{if(e.startsWith("/resume:")){const t=e.substring(8);return void await dn(t)}const t=parseCommandInput({input:e});if(!t)return;const{commandName:n,rawArguments:r,positionalArgs:o}=t;switch(n){case"/exit":return void ze(!0);case"/clear":return void await Kt();case"/help":return void qt();case"/share":return void tn();case"/unshare":return void cn();case"/taste":return void C(!0);case"/learn-taste":return void await ln();case"/skills":return void T(!0);case"/provider":return void(isInternalTeamFlagEnforced()?P(!0):m("Provider selection not available"));case"/model":return void I(!0);case"/memory":return void D(!0);case"/init":return void nn();case"/agents":return void k(!0);case"/compact":return void await Zt();case"/rewind":return void Jt();case"/login":return void await rn();case"/logout":return void await an();case"/terminal-setup":return void Vt()}const s=getCustomCommandContent(n);if(s){const e=processCommandTemplate({template:s,rawArguments:r,positionalArgs:o});await Gt({input:e.content,role:"user"})}},"handleCommand"),en=__name(async()=>{const e=Dt.current?.getSessionManager();if(e){const t=await e.loadShareInfo();t&&Qe({url:t.url,secret:t.secret})}},"loadShareInfo"),tn=__name(async()=>{if(be){if(Ye)return await ii(Ye.url),m(""),rt(!0),void setTimeout(()=>{rt(!1)},3e3);try{m("Creating share link...");const e=Dt.current?.getMessages()||[],t=$n.sanitizeMessages(e,global.COMMAND_CODE_CWD||process.cwd()),n=new Bn({baseUrl:getApiBaseUrl()}),r=await n.post({endpoint:et.ALPHA.SHARE.CREATE,body:{sessionId:be,messages:t}}),o={url:r.url,secret:r.secret};Qe(o);const s=Dt.current?.getSessionManager();s&&await s.saveShareInfo({url:r.url,secret:r.secret}),await ii(r.url),m(""),rt(!0),setTimeout(()=>{rt(!1)},5e3)}catch(e){m(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else m("No active session to share")},"handleShareCommand"),nn=__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.`;ge(e=>[...e,Er(t)])}catch(e){const t=`Error: Failed to initialize AGENTS.md: ${e instanceof Error?e.message:"Unknown error"}`;ge(e=>[...e,Er(t)])}},"handleInitCommand"),rn=__name(async()=>{const e=lt();if(await getAuthKey(e)){let e="";try{const t=await loadCredentials();e=t?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const t=e&&"API Key"!==e&&"Manual API Key"!==e?` as ${e}`:"";return void ge(e=>[...e,Er(`Already logged in${t}`)])}kt(!0)},"handleLoginCommand"),on=B((e,t)=>{kt(!1),e?(ge(e=>[...e,Er(t)]),Dt.current&&Dt.current.refreshRequest()):ge(e=>[...e,vr(t)]),m("Ready...")},[]),sn=B(()=>{kt(!1),ge(e=>[...e,Er("Authentication cancelled.")]),m("Ready...")},[]),an=__name(async()=>{const e=await performLogout();e.success?(Dt.current&&Dt.current.refreshRequest(),e.wasAuthenticated?e.warnings.length>0?ge(t=>[...t,Er(`Successfully logged out from Command Code. Warnings: ${e.warnings.join(", ")}`)]):ge(e=>[...e,Er("Successfully logged out from Command Code.")]):ge(e=>[...e,Er("Not currently authenticated.")])):ge(t=>[...t,vr(`Logout failed: ${e.error}`)])},"handleLogoutCommand"),cn=__name(async()=>{if(be){if(!Ye)return at("NOT SHARED: Session is not currently shared"),void setTimeout(()=>at(""),5e3);try{m("Removing share link...");const e=new Bn({baseUrl:getApiBaseUrl()});await e.delete({endpoint:et.ALPHA.SHARE.DELETE,body:{sessionId:be,secret:Ye.secret}});const t=Dt.current?.getSessionManager();t&&await t.deleteShareInfo(),at("UNSHARED: Sharing has stopped"),m(""),Qe(null),setTimeout(()=>{at("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;m(t),setTimeout(()=>m(""),5e3)}}else m("No active session to unshare")},"handleUnshareCommand"),ln=__name(async()=>{je(!0),Me(!0);const e=Tr();_e(e.id),ge(t=>[...t,e])},"handleLearnCommand"),dn=__name(async e=>{const t=crypto.randomUUID();Ft.current=t;try{ge([]),he([]),Dt.current=null,mt(!1),ke(e),Ce(!1),Te(!0),Dt.current=new _o({onFeedUpdate:__name(e=>{if(Ft.current===t){const t=!0===e.metadata?.isAgent,n=e.metadata?.status;t&&"running"===n?he(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]}):t&&n&&"running"!==n?(he(t=>t.filter(t=>t.id!==e.id)),ge(t=>[...t,e])):ge(t=>[...t,e])}},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...$t.current];return $t.current=[],Ee([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{Ge(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{Ve(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{p(e)},"onRetryUpdate"),onProviderChange:__name(e=>{W(e)},"onProviderChange"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{Lt({params:e,resolve:t,reject:n}),m("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const t=tt.current;return t?{sessionId:e,secret:t.secret}:null},"getShareInfo")},e);const{feedEntries:n,corruptedLines:r,totalLines:o}=await Dt.current.loadSession(e);if(Ft.current!==t)return;await en();const s=[];if(0===n.length&&o>0?s.push(vr(`Session could not be loaded. ${o} lines could not be parsed.`)):0===n.length?s.push(Er("Session loaded but contains no messages.")):(r>0&&s.push(Er(`Warning: ${r} message(s) could not be loaded.`)),s.push(...n)),Ft.current!==t)return;ge(s),Ho(),se(e=>e+1)}catch(e){if(Ft.current!==t)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";ge([vr(`Failed to load session: ${n}. Starting fresh session.`)]),Ce(!1),Te(!1),ke(crypto.randomUUID())}},"handleSelectSession"),un=__name(async()=>{ge([]),he([]),Dt.current=null,mt(!1),ke(crypto.randomUUID()),Ce(!1),Te(!1)},"handleNewSession"),mn=__name(async()=>{try{await vo.initializeProject(),xe(!1),e?(console.log("No conversations found to resume."),ze(!0)):($e(!0),xt(),It())}catch(e){console.error("Failed to initialize project:",e),xe(!1),ze(!0)}},"handleTrust"),gn=__name(()=>{ze(!0)},"handleNoTrust"),pn=__name(async e=>{try{const t=getProviderConfig(e);if(t?.requiresAuth&&t.checkAuth&&!await t.checkAuth()&&t.authComponent)return void O({provider:e,Component:t.authComponent});await updateUserConfig({provider:e}),W(e),P(!1);const n=getProviderDisplayName(e);m(`Provider set to ${n}`),ne.current&&clearTimeout(ne.current),X(!0),ne.current=setTimeout(()=>{X(!1),ne.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),m("Failed to set provider"),P(!1)}},"handleProviderSelect"),hn=__name(()=>{P(!1)},"handleProviderCancel"),fn=__name(e=>{const t=Object.values(st).find(t=>t.id===e);return t?t.name:e},"getModelDisplayName"),yn=__name(async e=>{try{await setSelectedModel({model:e}),q(e),I(!1);const t=fn(e);m(`Model set to ${t}`),re.current&&clearTimeout(re.current),te(!0),re.current=setTimeout(()=>{te(!1),re.current=null},5e3)}catch(e){console.error("Failed to set model:",e),m("Failed to set model"),I(!1)}},"handleModelSelect"),wn=__name(()=>{I(!1)},"handleModelCancel"),En=__name(()=>{if(M){O(null),P(!1),W(M.provider);const e=getProviderDisplayName(M.provider);m(`${e} authentication successful`),ne.current&&clearTimeout(ne.current),X(!0),ne.current=setTimeout(()=>{X(!1),ne.current=null},5e3)}},"handleAuthSuccess"),bn=__name(()=>{O(null)},"handleAuthCancel");if(We)return null;if(Pe)return N.createElement(N.Fragment,null,N.createElement(ha,{staticKey:oe}),N.createElement(ti,{onTrust:mn,onExit:gn}));if(De)return null;if(Se)return N.createElement(wa,{onSelectSession:dn,onNewSession:un});if(!Ie)return null;if(Ot)return N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(ua,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:G}),N.createElement(z,{marginY:1},N.createElement(ai,{questions:Ot.params.questions,onResponse:e=>{Ot.resolve(e),Lt(null),m("Answers submitted")}})));if(Rt){if("shell_command"===Rt.toolName){const e=Rt.params;return N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(ua,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:G}),pe.map(e=>N.createElement(LiveAgentStatus,{key:e.id,entry:e})),N.createElement(z,{marginY:1},N.createElement(Ea,{request:e,onResponse:e=>{Ut(e);const t="no"!==e.value;Rt.resolve(t),Mt(null),t?(m("Shell command allowed"),dt||Wt("Use shift+tab to enable auto-accept")):m("Shell command denied")},onToggleAutoAccept:Ht})))}if("kill_shell"===Rt.toolName){const e=createKillShellPermissionRequest(Rt.params);return N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(ua,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:G}),N.createElement(z,{marginY:1},N.createElement(Ea,{request:e,onResponse:e=>{Ut(e);const t="no"!==e.value;Rt.resolve(t),Mt(null),t?(m("Process termination allowed"),dt||Wt("Use shift+tab to enable auto-accept")):m("Process termination denied")},onToggleAutoAccept:Ht})))}{const e={action:Rt.toolName.includes("edit")?"edit":Rt.toolName.includes("write")?"create":Rt.toolName.includes("delete")?"delete":"edit",filePath:Rt.params.filePath||Rt.params.file_path||Rt.params.path||Rt.params.absolutePath||Rt.params.notebook_path||"unknown",description:`Allow ${Rt.toolName} operation`,oldContent:"edit_file"===Rt.toolName?Rt.params.oldContent:void 0,newContent:"edit_file"===Rt.toolName?Rt.params.newContent:void 0};return N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(ua,{staticKey:oe,feed:me,showHeader:!0,expandedToolOutput:ae,currentModel:G}),pe.map(e=>N.createElement(LiveAgentStatus,{key:e.id,entry:e})),N.createElement(z,{marginY:1},N.createElement(ga,{request:e,onResponse:e=>{Ut(e);const t="no"!==e.value;Rt.resolve(t),Mt(null),t?(m("File operation allowed"),dt||Wt("Use shift+tab to enable auto-accept")):m("File operation denied")},onToggleAutoAccept:Ht})))}}return F?N.createElement(Vs,{onClose:()=>{R(!1),se(e=>e+1)}}):S?N.createElement(N.Fragment,null,N.createElement(ha,{staticKey:oe}),N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"Press Esc to return to conversation")),N.createElement(ka,{onClose:()=>C(!1),onSettingsChange:xt,staticKey:oe}))):v?N.createElement(N.Fragment,null,N.createElement(ha,{staticKey:oe}),N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(z,{marginBottom:1},N.createElement(H,{dimColor:!0},"Press Esc to return to conversation")),N.createElement(ba,{onClose:()=>T(!1),staticKey:oe}))):N.createElement(z,{flexDirection:"column",width:"100%"},N.createElement(ua,{staticKey:oe,feed:me.filter(e=>"taste-onboarding"!==e.role),showHeader:!0,expandedToolOutput:ae,currentModel:G}),Ne&&N.createElement(ei,{onComplete:Pt,autoLearn:Ue}),pe.map(e=>N.createElement(LiveAgentStatus,{key:e.id,entry:e})),N.createElement(RetryMessage,{attempt:g}),!A&&!x&&!M&&!$&&!b&&!wt&&!bt&&!Ne&&N.createElement(qs,{queuedMessages:we,isProcessing:fe,executionState:le,status:u,input:l,setInput:d,onSubmit:Gt,showFileList:w,setShowFileList:E,fileSearchQuery:de,setFileSearchQuery:ue,onCommand:Xt,outputTokens:He,contextUsage:qe,tasteLearning:it,shareInfo:Ye,showShareNotification:nt,unshareNotificationMessage:ot,updateStatus:h,updateFailedInfo:s,currentProvider:L,showProviderInfo:Z,autoAcceptMode:dt,onToggleAutoAccept:Ht,hintMessage:gt,historyManager:Ae.current,pendingExitKey:vt,onResetPendingExitKey:At,onDoubleEscapeEmpty:zt,retryAttempt:g}),A&&N.createElement(z,{marginY:1},N.createElement(pa,{onSelect:pn,onCancel:hn,currentProvider:L})),x&&N.createElement(z,{marginY:1},N.createElement(ma,{onSelect:yn,onCancel:wn,currentModel:G})),b&&N.createElement(z,{marginY:1},N.createElement(Rs,{onCancel:()=>k(!1)})),$&&N.createElement(z,{marginY:1},N.createElement(Ks,{onClose:()=>D(!1)})),wt&&Dt.current&&N.createElement(z,{marginY:1},N.createElement(ya,{checkpoints:Dt.current.listCheckpoints(),onSelect:Yt,onCancel:Qt})),M&&N.createElement(z,{marginY:1},N.createElement(M.Component,{onSuccess:En,onCancel:bn})),bt&&N.createElement(z,{marginY:1},N.createElement(ni,{onComplete:on,onCancel:sn})))},"InteractiveCLI"),li=__name(e=>e?{isValid:!0}:{isValid:!1,errorMessage:["Error: Interactive mode requires a TTY terminal.","Please run this command directly in your terminal, not through a pipe or redirect."].join("\n")},"validateTtyEnvironment"),di=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),ui=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),mi=__name(({options:e})=>({resume:e.resume,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding}),"buildInteractiveCLIProps"),gi=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),pi=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),hi=__name(()=>{pi()},"initializeTerminal"),fi=__name(async(e={})=>{const t=li(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),hi(),di(e)){const e=await vo.isProjectInitialized(),t=e?await vo.listSessions():[],n=ui({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=mi({options:e}),r=gi();q(N.createElement(ci,{...n}),r)},"interactiveMode"),yi=null,wi=!1,Ei=new Set([Vn,Kn,Zn]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(wi)return;wi=!0;const e=__name(e=>{yi?.abort(),process.stderr.write(`\n${e}\n`),process.exit(130)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(0),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(1)})}async function printMode(e={}){setupSignalHandlers(),yi=new AbortController;let t=e.query||"";if(!t){process.stdin.isTTY&&(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1));try{t=await readStdin()}catch(e){const t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`Error reading from stdin: ${t}\n`),process.exit(1)}}t.trim()||(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1)),await isAuthenticated()||(process.stderr.write('Error: Not authenticated. Please run "cmd login" first.\n'),process.exit(3)),e.dangerouslySkipPermissions&&process.stderr.write("Warning: Running with --dangerously-skip-permissions. File writes and shell commands will execute without prompts.\n");try{const n=await processQuery({query:t,signal:yi.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions});process.stdout.write(n),n.endsWith("\n")||process.stdout.write("\n"),process.exit(0)}catch(e){e instanceof Error&&"AbortError"===e.name&&(process.stderr.write("\nCancelled.\n"),process.exit(130)),e instanceof Mn&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof On&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof Un&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Fn&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof jn&&(process.stderr.write("Error: The API server encountered an error. Please try again later.\n"),process.exit(7));const t=e instanceof Error?e.message:"Unknown error";/permission denied|access denied|not permitted|unauthorized/i.test(t)&&(process.stderr.write(`Error: ${t}\n`),process.exit(4)),process.stderr.write(`Error: ${t}\n`),process.exit(1)}}__name(readStdin,"readStdin"),__name(isAuthenticated,"isAuthenticated"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode");var bi=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced();let r;t===rt&&(r=await ut.getValidAccessToken(),validateOAuthToken({token:r,provider:t}));const o=getEnvironmentContext(),s=await getMemoryContent([]),a=await getTasteContent(),i=generateSkillsXML(await loadAllSkillSummaries())||null,c=crypto.randomUUID(),l=await isTasteLearningEnabled(),d={[Ze]:vo.getCurrentProjectDirName(),[Xe]:l.toString(),[Ye]:n.toString()};return r&&(d[Qe]=`Bearer ${r}`),{tools:e,config:o,memory:s,taste:a,skills:i,headers:d,sessionId:c}}async function callApi(e,t,n,r){const o={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:`anthropic:${getConfiguredModel()}`},s={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:o,threadId:t.sessionId},a=await e.post({body:s,stream:!0,endpoint:et.ALPHA.GENERATE,headers:t.headers,signal:r});return Pe.fromReadableStream(a).finalMessage()}async function executeToolCall(e,t,n){if(Ei.has(e.name)&&!n)return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool "${e.name}" requires permissions. Use --dangerously-skip-permissions to enable file writes and shell commands in print mode.`,is_error:!0};try{const n=await executeTool(e.name,e.input,{abortSignal:t});return{type:"tool_result",tool_use_id:e.id,content:n}}catch(t){if(t instanceof Mn||t instanceof On||t instanceof Un||t instanceof Fn||t instanceof jn)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1}=e,o=getApiBaseUrl(),s=new Bn({baseUrl:o}),a=[{role:"user",content:t}],i=await setupConversationContext();let c=0,l="";for(;c<bi;){if(c++,n.aborted)throw new Error("Cancelled");const e=await callApi(s,i,a,n),t=e.content.filter(e=>"text"===e.type),o=e.content.filter(e=>"tool_use"===e.type),d=t.map(e=>e.text).join("");if(d&&(l+=d),0===o.length)break;const u=[];for(const e of o){if(n.aborted)throw new Error("Cancelled");const t=await executeToolCall(e,n,r);u.push(t)}a.push({role:"assistant",content:e.content}),a.push({role:"user",content:u})}return c>=bi&&process.stderr.write(`Warning: Reached maximum conversation turns (${bi}). The response may be incomplete. Consider breaking your query into smaller parts.\n`),l}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall"),__name(processQuery,"processQuery");var ki=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),Si=__name(async()=>{await checkAuthAndPromptLogin()||process.exit(1)},"ensureAuthenticated"),Ci=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),t},"buildRuntimeOptions"),vi=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),Ti=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(void 0!==t.print){const n=Ti(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions})}const n=ki(e);await Si();const r=Ci(t),o=vi({options:t,runtimeOptions:r,initialPrompt:n});fi(o)}__name(interactiveModeAction,"interactiveModeAction"),globalThis.COMMAND_CODE_CWD=process.cwd();var Ai=__name(()=>process.cwd(),"getCwd"),Pi=__name(()=>process.argv.slice(2),"getArgs"),xi=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),Ii=__name(()=>{const e=Ai(),t=Pi(),n=xi(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`)},"logStartupInfo");async function preRun(){Ii(),await maybeRunPendingUpdate(),checkForUpdateAsync()}__name(preRun,"preRun");var $i=getPackageJson();function displayCustomHelp(){const e=$i.version,n=getInvokedCommandName(),r=na.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(t.bold("Command Code")+t.gray(` v${e}`)),console.log(t.gray(Xs)),console.log(),console.log(t.bold("Usage")),console.log(` ${n} <command> [options]`),console.log(),console.log(t.bold("Options"));for(const e of ta){const r=e.key.replace(/^cmd/,n);console.log(" "+r.padEnd(20)+t.gray(e.description))}console.log(),console.log(t.bold("Commands"));for(const e of ra){const r=e.key.replace(/^cmd/,n);console.log(" "+r.padEnd(20)+t.gray(e.description))}console.log(),console.log(t.bold("Slash Commands"));for(const e of r)console.log(" "+e.key.padEnd(17)+t.gray(e.description));console.log(),console.log(t.bold("Keyboard Shortcuts"));for(const e of ea)console.log(" "+e.key.padEnd(15)+t.gray(e.description));console.log(),console.log(t.bold("Examples"));for(const e of sa)console.log(" "+e.replace(/^cmd/,n));console.log(),console.log(t.cyan("❯")+" "+t.gray(aa.replace(/cmd/,n))),console.log(),console.log(t.bold("Links"));for(const e of oa)console.log(" "+e.key.padEnd(20)+t.cyan(e.description));console.log()}function createProgram(){const e=new le;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version($i.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume","Resume a session (pick from history)").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").option("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").addOption(new de(Ke).hideHelp()).addOption(new de(Je).hideHelp()).addOption(new de("-d, --debug","Enable debug mode").hideHelp()).addOption(new de("--local","Use local server").hideHelp()).addOption(new de("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(r&&r!==n?`[cmd] subcommand: ${n}`:`[cmd] running: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const a=t.args;a.length>0&&dlog(`[cmd] arguments: ${a.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks");var Di=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=v.platform(),n=v.arch();let r,o,s,a;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,o=e.user?.id,s=e.org?.login,a=e.org?.id)}catch{}if(!o)try{const e=await loadCredentials();o=e?.userId}catch{}systemInfo({userName:r,userId:o,orgLogin:s,orgId:a,nodeVersion:e,platform:t,arch:n})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){Di||(Di=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal");var Fi=new le("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()}),Ri=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Mi=__name(e=>{const t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`},"formatUptime"),Oi=__name(({icon:e,label:t,children:n})=>N.createElement(H,null,N.createElement(H,{color:"cyan"},e," "),N.createElement(H,{dimColor:!0},t.padEnd(12)),n),"Row"),Li=__name(({title:e})=>N.createElement(H,null,N.createElement(H,{color:"gray"},"───"),N.createElement(H,{color:"white"}," ",e," "),N.createElement(H,{color:"gray"},"─".repeat(35))),"Header"),Ni=__name(({title:e,marginTop:t=0,children:n})=>N.createElement(z,{flexDirection:"column",marginTop:t},N.createElement(Li,{title:e}),N.createElement(z,{flexDirection:"column",paddingY:1},n)),"Section"),_i=__name(({cpuCount:e,totalMem:t})=>N.createElement(Ni,{title:"System Information"},N.createElement(Oi,{icon:ae.bullet,label:"Date"},N.createElement(H,null,formatDate())),N.createElement(Oi,{icon:ae.pointer,label:"Platform"},N.createElement(H,{color:"green"},Ri(v.platform())),N.createElement(H,{dimColor:!0}," ","(",v.platform(),", ",v.arch(),")")),N.createElement(Oi,{icon:ae.triangleUp,label:"Hostname"},N.createElement(H,null,v.hostname())),N.createElement(Oi,{icon:ae.bullet,label:"User"},N.createElement(H,{color:"yellow"},v.userInfo().username)),N.createElement(Oi,{icon:ae.bullet,label:"CPUs"},N.createElement(H,{color:"magenta"},e," cores")),N.createElement(Oi,{icon:ae.bullet,label:"Memory"},N.createElement(H,{color:"cyan"},t," GB")),N.createElement(Oi,{icon:ae.play,label:"Uptime"},N.createElement(H,null,Mi(v.uptime()))),N.createElement(Oi,{icon:ae.arrowRight,label:"Home"},N.createElement(H,{dimColor:!0},v.homedir())),N.createElement(Oi,{icon:ae.pointer,label:"Shell"},N.createElement(H,null,process.env.SHELL||"N/A")),N.createElement(Oi,{icon:ae.bullet,label:"Node"},N.createElement(H,{color:"green"},process.version))),"SystemInfoSection"),Ui=__name(({cpus:e})=>N.createElement(Ni,{title:"CPU Details",marginTop:1},e.map((e,t)=>N.createElement(Oi,{key:t,icon:ae.bullet,label:`Core ${t}`},N.createElement(H,null,e.model.trim()),N.createElement(H,{color:"yellow"}," @ ",e.speed," MHz")))),"CPUDetailsSection"),ji=__name(({networkInterfaces:e})=>N.createElement(Ni,{title:"Network",marginTop:1},Object.entries(e).map(([e,t])=>{const n=t?.filter(e=>"IPv4"===e.family&&!e.internal);return n&&0!==n.length?n.map((t,n)=>N.createElement(Oi,{key:`${e}-${n}`,icon:ae.bullet,label:e},N.createElement(H,{color:"green"},t.address))):null})),"NetworkSection"),Bi=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>N.createElement(z,{flexDirection:"column"},N.createElement(H,null,"System Information"),N.createElement(H,null,"─".repeat(40)),N.createElement(H,null,"Date ",formatDate()),N.createElement(H,null,"Platform ",Ri(v.platform())," (",v.platform(),","," ",v.arch(),")"),N.createElement(H,null,"Hostname ",v.hostname()),N.createElement(H,null,"User ",v.userInfo().username),N.createElement(H,null,"CPUs ",e.length," cores"),N.createElement(H,null,"Memory ",t," GB"),N.createElement(H,null,"Uptime ",Mi(v.uptime())),N.createElement(H,null,"Home ",v.homedir()),N.createElement(H,null,"Shell ",process.env.SHELL||"N/A"),N.createElement(H,null,"Node ",process.version),r&&N.createElement(N.Fragment,null,N.createElement(H,null,"\n","CPU Details"),N.createElement(H,null,"─".repeat(40)),e.map((e,t)=>N.createElement(H,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),N.createElement(H,null,"\n","Network"),N.createElement(H,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>N.createElement(H,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Wi=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>N.createElement(z,{flexDirection:"column"},N.createElement(_i,{cpuCount:e.length,totalMem:t}),r&&N.createElement(Ui,{cpus:e}),r&&N.createElement(ji,{networkInterfaces:n})),"StyledInfo"),zi=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=K();j(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=v.cpus(),o=v.networkInterfaces(),s=Math.round(v.totalmem()/1024/1024/1024);return t?N.createElement(Bi,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e}):N.createElement(Wi,{cpus:r,totalMem:s,networkInterfaces:o,verbose:e})},"InfoUI"),Hi=new le("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{const{waitUntilExit:t}=q(N.createElement(zi,{verbose:e.verbose,text:e.text}));await t()}),Gi=new le(ot).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{const{unmount:e}=q(N.createElement(Za,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:zt.LEARN_TASTE_COMMAND,heading:"Learn taste render failed"}}),dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),await shutdownTelemetry(),process.exit(1)}});function getTastePath(e){const{target:t}=e;switch(t){case"local-project":return y.join(process.cwd(),".commandcode","taste");case"local-global":return y.join(v.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 y.join(getTastePath({target:t}),"taste.md")}function getCategoryPath(e){const{target:t,category:n}=e;return y.join(getTastePath({target:t}),n)}function getCategoryTasteFile(e){const{target:t,category:n}=e;return y.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 s=[];for(const e of t){const t=parseLearning({line:e});t&&s.push(t)}s.length>0&&r.push({category:normalizeCategory({category:o}),learnings:s,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 qi=class{static{__name(this,"LocalProjectStorage")}target="local-project";async getAllBuckets(){const e=getTastePath({target:this.target});if(!d(e))return[];const t=[],n=getRootTasteFile({target:this.target});if(d(n)){let e=await x.readFile(n,"utf-8");const r=migrateHeader({content:e});r!==e&&(await x.writeFile(n,r,"utf-8"),e=r);const o=parseTasteBuckets({content:e,sourcePath:n});t.push(...o)}const r=await x.readdir(e,{withFileTypes:!0});for(const e of r)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(d(n)){let r=await x.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await x.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}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 x.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:this.target}),o=t.learnings.length,s=await this.removeBucket({category:t.category});o<=5?await this.writeToRoot({bucket:t,rootFile:r,categoryPosition:s}):await this.writeToSubdirectory({bucket:t,rootFile:r,categoryPosition:s})}async removeBucket(e){const{category:t}=e,n=getRootTasteFile({target:this.target});let r=null;if(d(n)){let e=await x.readFile(n,"utf-8");e=migrateHeader({content:e});const o=e.split("\n");let s=-1,a=-1;const i=new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i");for(let e=0;e<o.length;e++)if(i.test(o[e])){s=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--;a=n;break}-1===a&&(a=o.length-1);break}if(-1!==s){const e=o.slice(0,s),t=a<o.length-1?o.slice(a+1):[];r={before:e.join("\n").trim(),after:t.join("\n").trim()};const i=[...e,...t].join("\n").trim();""===i?await x.rm(n,{force:!0}):await x.writeFile(n,i+"\n","utf-8")}}const o=getCategoryTasteFile({target:this.target,category:t}),s=y.dirname(o);return d(s)&&await x.rm(s,{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(gs)&&(e=gs+"\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 x.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";d(n)&&(e=await x.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(gs)||(e=gs+"\n\n"+e):e=gs+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=o,await x.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}),s=y.dirname(o);await x.mkdir(s,{recursive:!0});const a=formatBucket({bucket:t});await x.writeFile(o,a,"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(gs)&&(e=gs+"\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 x.writeFile(n,e.trim()+"\n","utf-8")}else{let e="";d(n)&&(e=await x.readFile(n,"utf-8"),e=migrateHeader({content:e})),e?e.trim().startsWith(gs)||(e=gs+"\n\n"+e):e=gs+"\n\n",e&&!e.endsWith("\n\n")&&(e+=e.endsWith("\n")?"\n":"\n\n"),e+=i,await x.writeFile(n,e.trim()+"\n","utf-8")}}exists(){const e=getTastePath({target:this.target});return d(e)}},Vi=class{static{__name(this,"LocalGlobalStorage")}target="local-global";async getAllBuckets(){const e=getTastePath({target:this.target});if(!d(e))return[];const t=[],n=await x.readdir(e,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=getCategoryTasteFile({target:this.target,category:e.name});if(d(n)){let r=await x.readFile(n,"utf-8");const o=migrateHeader({content:r});o!==r&&(await x.writeFile(n,o,"utf-8"),r=o);const s=parseTasteBuckets({content:r,sourcePath:n});for(const t of s)t.category=e.name;t.push(...s)}}return t}async getBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t});if(!d(n))return null;let r=await x.readFile(n,"utf-8");const o=migrateHeader({content:r});return o!==r&&(await x.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 x.mkdir(n,{recursive:!0});const r=getCategoryTasteFile({target:this.target,category:t.category}),o=y.dirname(r);await x.mkdir(o,{recursive:!0});const s=formatBucket({bucket:t});await x.writeFile(r,s,"utf-8")}async deleteBucket(e){const{category:t}=e,n=getCategoryTasteFile({target:this.target,category:t}),r=y.dirname(n);d(r)&&await x.rm(r,{recursive:!0,force:!0})}async listBuckets(){const e=await this.getAllBuckets(),t=[];for(const n of e){let e;try{e=(await x.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 d(e)}};async function prepareUploadFormData(e){const{packageName:t,bucket:n,description:r,type:o="category",isPublic:s=!1}=e,a=new FormData;if(a.append("name",t),r&&a.append("description",r),a.append("type",o),a.append("isPublic",String(s)),"category"===o){const e=formatBucket({bucket:n}),t=new Blob([e],{type:"text/markdown"}),r=new File([t],"taste.md",{type:"text/markdown"});a.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"});a.append("files[taste.md]",r);const o=getTastePath({target:"local-project"}),s=y.join(o,n.category);if(d(s)){const e=getCategoryTasteFile({target:"local-project",category:n.category});if(d(e)){const t=await x.readFile(e,"utf-8"),r=new Blob([t],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});a.append(`files[${n.category}/taste.md]`,o)}}}return a}async function prepareMultiplePackagesUpload(e){const{buckets:t,projectName:n,description:r,isPublic:o=!1}=e,s=new FormData;s.append("name",n),r&&s.append("description",r),s.append("type","project"),s.append("isPublic",String(o));const a=getRootTasteFile({target:"local-project"});if(d(a)){const e=await x.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});s.append("files[taste.md]",n)}for(const e of t){const t=getCategoryTasteFile({target:"local-project",category:e.category});if(d(t)){const n=await x.readFile(t,"utf-8"),r=new Blob([n],{type:"text/markdown"}),o=new File([r],"taste.md",{type:"text/markdown"});s.append(`files[${e.category}/taste.md]`,o)}}return s}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 Ki=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()}${et.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{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"list_packages_error"}),context:{component:zt.TASTE_REMOTE_STORAGE,heading:"Failed to list taste packages","http.status":n.status}}),t}const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const s=[];for(const e of o)try{const t=await this.getBucket({category:e.name});t&&s.push(t)}catch(t){trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"download_package_error"}),context:{component:zt.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${t instanceof Error?t.message:String(t)}`)}return s}async downloadPackage(e){const{namespace:t,packageName:n}=e,r=getApiBaseUrl(),o=`${r}${et.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})`}const n=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_public_error"}),context:{component:zt.TASTE_REMOTE_STORAGE,heading:"Failed to download taste package (public)","http.status":e.status}}),n}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 s=await getAuthKey();if(!s)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");const a=`${r}${et.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",t).replace(":packageName",n)}`,i=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${s}`}});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{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"download_auth_error"}),context:{component:zt.TASTE_REMOTE_STORAGE,heading:"Failed to download taste package (authenticated)","http.status":i.status}}),t}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 s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async 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 s=await prepareUploadFormData({packageName:t.category,bucket:t,type:"category",isPublic:r}),a=`${getApiBaseUrl()}${et.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,i=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:s});if(!i.ok){let e="Failed to upload taste package";try{const t=await i.json();e=t.error?.message||t.message||e}catch{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"upload_package_error"}),context:{component:zt.TASTE_REMOTE_STORAGE,heading:"Failed to upload taste package","http.status":i.status}}),t}await i.json()}async writeBuckets(e){const{buckets:t,projectName:n,namespace:r,isPublic:o=!1}=e,s=await getAuthKey();if(!s)throw new Error("No API key found. Please authenticate with: cmd login");const a=await prepareMultiplePackagesUpload({buckets:t,projectName:n,isPublic:o}),i=`${getApiBaseUrl()}${et.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,c=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:a});if(!c.ok){let e="Failed to upload taste packages";try{const t=await c.json();e=t.error?.message||t.message||e}catch{}const n=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:n,label:"upload_packages_error"}),context:{component:zt.TASTE_REMOTE_STORAGE,heading:"Failed to upload taste packages","http.status":c.status,"package.count":t.length}}),n}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()}${et.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{}const t=new Error(e);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"list_buckets_error"}),context:{component:zt.TASTE_REMOTE_STORAGE,heading:"Failed to list buckets","http.status":n.status}}),t}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 s=new Map(o);for(const e of t){const t=o.get(e.text);t?e.confidence>t.confidence?(s.set(e.text,e),r.updated++):(e.confidence,t.confidence,r.unchanged++):(s.set(e.text,e),r.added++)}for(const e of n)t.some(t=>t.text===e.text)||r.unchanged++;return{merged:Array.from(s.values()),details:r}}__name(mergeLearnings,"mergeLearnings");var Ji=/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"),s=[];let a=0;for(;a<o.length;){const e=o[a],t=a+1,n=e.trim();if(n.startsWith("-"))if(Ji.test(n))s.push({text:e,originalLineNum:t}),a++;else{let n=e,r=a+1;for(;r<o.length;){const e=o[r].trim();if(e.startsWith("#")||e.startsWith("-"))break;if(e.length>0&&(n=n+" "+e),Ji.test(e)){r++;break}r++}s.push({text:n,originalLineNum:t}),a=r}else s.push({text:e,originalLineNum:t}),a++}let i=null,c=null,l=0;for(const{text:e,originalLineNum:t}of s){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(!Ji.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),a=s.length>0?s[s.length-1]:null;if(!a)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const i=a[1],c=parseFloat(i);if(isNaN(c))return r.push({line:n,severity:"error",message:`Confidence value "${i}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;c<0||c>1?r.push({line:n,severity:"error",message:`Confidence value ${c} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}):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=a&&void 0!==a.index?o.substring(0,a.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),s=0===r.length;let a;if(0===t.length)a=`✓ ${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":""}`),a=`${r.length>0?"✗":"⚠"} ${n} has ${e.join(", ")}`}return{valid:s,issues:t,summary:a}}function formatValidationIssues(e){const{result:n,verbose:r=!0}=e;if(0===n.issues.length){const e=n.summary.charAt(0),r=n.summary.substring(2);return`${t.green(e)} ${t.dim(r)}`}if(!r)return n.summary;const o=n.issues.filter(e=>"error"===e.severity),s=n.issues.filter(e=>"warning"===e.severity),a=[o.length>0?t.red(n.summary):t.yellow(n.summary),""];if(o.length>0){a.push(t.bold(t.red("Errors:")));for(const e of o){const n=e.line?t.dim(` Line ${e.line}: `):" ";a.push(`${n}${t.red(e.message)}`),e.suggestion&&a.push(t.dim(` → ${e.suggestion}`))}a.push("")}if(s.length>0){a.push(t.bold(t.yellow("Warnings:")));for(const e of s){const n=e.line?t.dim(` Line ${e.line}: `):" ";a.push(`${n}${t.yellow(e.message)}`),e.suggestion&&a.push(t.dim(` → ${e.suggestion}`))}a.push("")}return a.join("\n").trim()}async function promptMergeStrategy(e){const{packageName:n,namespace:r,localBucket:o,remoteLearningsCount:s}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${ae.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${ae.warning} Package '${n}' already exists locally\n`)),console.log(`Local: ${o.learnings.length} learnings`),console.log(`Remote: ${s} learnings (from ${r})\n`);const a=await ue.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${o.learnings.length} → ${s} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});return ue.isCancel(a)&&(ue.cancel("Operation cancelled"),process.exit(0)),a}async function promptPushStrategy(e){const{packageName:n,namespace:r,localLearningsCount:o,remoteBucket:s}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${ae.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${ae.warning} Package '${n}' already exists in ${r}\n`)),console.log(`Local: ${o} learnings`),console.log(`Remote: ${s.learnings.length} learnings (in ${r})\n`);const a=await ue.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${s.learnings.length} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"}],initialValue:"merge"});return ue.isCancel(a)&&(ue.cancel("Operation cancelled"),process.exit(0)),a}async function promptGlobalPushStrategy(e){const{packageName:n,localLearningsCount:r,globalBucket:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${ae.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${ae.warning} Package '${n}' already exists in global storage\n`)),console.log(`Local: ${r} learnings`),console.log(`Global: ${o.learnings.length} learnings\n`);const s=await ue.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${o.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});return ue.isCancel(s)&&(ue.cancel("Operation cancelled"),process.exit(0)),s}async function promptGlobalPullStrategy(e){const{packageName:n,localBucket:r,globalLearningsCount:o}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${ae.warning} Non-interactive terminal detected, using default merge strategy`)),"merge";console.log(t.yellow(`\n${ae.warning} Package '${n}' already exists locally\n`)),console.log(`Local: ${r.learnings.length} learnings`),console.log(`Global: ${o} learnings\n`);const s=await ue.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${r.learnings.length} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});return ue.isCancel(s)&&(ue.cancel("Operation cancelled"),process.exit(0)),s}async function promptTypeMismatchStrategy(e){const{packageName:n,namespace:r,localType:o,remoteType:s,localLearningsCount:a,remoteLearningsCount:i}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${ae.warning} Non-interactive terminal detected, skipping push`)),"skip";const c=`https://commandcode.ai/${r}/${n}`;console.log(t.yellow(`\n${ae.warning} Pushing local project taste to individual package '${n}'\n`)),console.log(`Local: ${n} (${a} learnings)`),console.log(`Remote: ${n} (${i} learnings) in ${r}\n`),console.log(`Review package: ${t.cyan(c)}\n`);const l=await ue.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});return ue.isCancel(l)&&(ue.cancel("Operation cancelled"),process.exit(0)),l}async function promptSameTypeStrategy(e){const{packageName:n,namespace:r,localLearningsCount:o,remoteLearningsCount:s}=e;if(!process.stdout.isTTY||!process.stdin.isTTY)return console.log(t.yellow(`\n${ae.warning} Non-interactive terminal detected, skipping push`)),"skip";const a=`https://commandcode.ai/${r}/taste/${n}`;console.log(t.yellow(`\n${ae.warning} Package '${n}' already exists in ${r}\n`)),console.log(`Local: ${o} learnings`),console.log(`Remote: ${s} learnings\n`),console.log(`Review taste package: ${t.cyan(a)}\n`);const i=await ue.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${s} → ${o} learnings)`}],initialValue:"skip"});return ue.isCancel(i)&&(ue.cancel("Operation cancelled"),process.exit(0)),i}async function push(e){const t=void 0!==e.isPublic,{buckets:n,target:r,overwrite:o=!1,isPublic:s=!1}=e,a=new qi,i={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return i.success=!1,i.errors.push({bucket:"all",error:"No taste directory found in project"}),i;const c=await a.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=y.basename(process.cwd()),n=new Ki;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 a="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(a=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"===a)return i;await n.writeBuckets({buckets:l,projectName:e,namespace:d,type:"project",isPublic:t?s:r?.isPublic??!1});for(const t of l)i.bucketsPushed.push(t.category),i.filePaths[t.category]=`${d}/${e}`,i.mergeDetails[t.category]={added:t.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 Vi;break;case"remote-project":case"remote-user":u=new Ki;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:s})}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:s})}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 qi,s={success:!0,bucketsPulled:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},a=__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 Vi;break;case"remote-project":case"remote-user":i=new Ki;break;default:return s.success=!1,s.errors.push({bucket:"all",error:`Invalid source: ${n}`}),s}try{c=await i.getAllBuckets()}catch(e){return s.success=!1,s.errors.push({bucket:"all",error:e instanceof Error?e.message:String(e)}),s}if(0===c.length)return s.success=!1,s.errors.push({bucket:"all",error:`No taste packages found in ${a}`}),s;for(const e of c){const t=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!t.valid){s.success=!1;const n=formatValidationIssues({result:t,verbose:!0});s.errors.push({bucket:e.category,error:`Validation failed for taste package in ${a}:\n${n}`})}if(t.issues.filter(e=>"warning"===e.severity).length>0&&t.valid){console.warn(`\nWarning: Taste package '${e.category}' in ${a} has validation warnings:\n`);const n=formatValidationIssues({result:t,verbose:!0});console.warn(n+"\n")}}if(s.errors.length>0)return s;const l=t.length>0?c.filter(e=>t.includes(e.category)):c;if(t.length>0&&0===l.length){s.success=!1;for(const e of t)s.errors.push({bucket:e,error:`Taste package not found in ${a}`});return s}for(const e of l)try{const t=await o.getBucket({category:e.category});let a;if(a=r?"overwrite":t&&"local-global"===n?await promptGlobalPullStrategy({packageName:e.category,localBucket:t,globalLearningsCount:e.learnings.length}):"merge","skip"===a)continue;if("overwrite"===a)await o.writeBucket({bucket:e}),s.bucketsPulled.push(e.category),s.overwritten.push(e.category);else{let n;if(t){const r=mergeLearnings({source:e.learnings,target:t.learnings});n={...e,learnings:r.merged},s.mergeDetails[e.category]=r.details}else n=e,s.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(e.category)}const i=getCategoryTasteFile({target:"local-project",category:e.category});s.filePaths[e.category]=i}catch(t){s.success=!1,s.errors.push({bucket:e.category,error:t instanceof Error?t.message:String(t)})}return s}async function pullRemote(e){const{namespace:t,packageName:n,overwrite:r=!1}=e,o=new qi,s=new Ki,a={success:!0,bucketsPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};try{const e=await s.downloadPackage({namespace:t,packageName:n});if(!e)return a.success=!1,a.errors.push({bucket:n,error:"Taste package not found in remote"}),a;const{type:i,files:c}=e;for(const e of c){const t=validateTasteFile({content:e.content,filePath:e.file});if(!t.valid){a.success=!1;const r=formatValidationIssues({result:t,verbose:!0});a.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(a.errors.length>0)return a;"project"===i?await pullProjectPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a}):await pullCategoryPackage({files:c,packageName:n,namespace:t,overwrite:r,targetStorage:o,result:a})}catch(e){a.success=!1,a.errors.push({bucket:n,error:e instanceof Error?e.message:String(e)})}return a}async function pullProjectPackage(e){const{files:t,packageName:n,namespace:r,overwrite:o,targetStorage:s,result:a}=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:s,result:a})}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:s,result:a})}}async function processBucket(e){const{bucket:t,namespace:n,overwrite:r,targetStorage:o,result:s}=e;try{const e=await o.getBucket({category:t.category});let a;if(a=r?"overwrite":e?await promptMergeStrategy({packageName:t.category,namespace:n,localBucket:e,remoteLearningsCount:t.learnings.length}):"merge","skip"===a)return void s.skipped.push(t.category);if("overwrite"===a)await o.writeBucket({bucket:t}),s.bucketsPulled.push(t.category),s.overwritten.push(t.category);else{let n;if(e){const r=mergeLearnings({source:t.learnings,target:e.learnings});n={...t,learnings:r.merged},s.mergeDetails[t.category]=r.details}else n=t,s.mergeDetails[t.category]={added:t.learnings.length,updated:0,unchanged:0};await o.writeBucket({bucket:n}),s.bucketsPulled.push(t.category)}const i=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=i}catch(e){s.success=!1,s.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:s,result:a}=e,i=t.find(e=>"taste.md"===e.file);if(!i)return a.success=!1,void a.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:s,result:a})}async function pushRemote(e){const t=void 0!==e.isPublic,{namespace:n,packageName:r,overwrite:o=!1,isPublic:s=!1}=e,a=new qi,i=new Ki,c={success:!0,bucketsPushed:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}};if(!a.exists())return c.success=!1,c.errors.push({bucket:r,error:"No taste directory found in project"}),c;try{const e=await a.getBucket({category:r});if(!e)return c.success=!1,c.errors.push({bucket:r,error:`Taste package '${r}' not found in local project`}),c;const l=validateTasteFile({content:formatBucket({bucket:e}),filePath:`${e.category}/taste.md`});if(!l.valid){c.success=!1;const e=formatValidationIssues({result:l,verbose:!0});return c.errors.push({bucket:r,error:`Validation failed:\n${e}`}),c}if(l.issues.filter(e=>"warning"===e.severity).length>0){console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`);const e=formatValidationIssues({result:l,verbose:!0});console.warn(e+"\n")}const d=await i.downloadPackageToBucket({namespace:n,packageName:r});let u;u=o?"overwrite":d?await promptPushStrategy({packageName:r,namespace:n,localLearningsCount:e.learnings.length,remoteBucket:d}):"merge";const m=t?s:d?.isPublic??!1;if("skip"===u)return c;if("overwrite"===u)await i.writeBucket({bucket:e,namespace:n,isPublic:m}),c.bucketsPushed.push(r),c.overwritten.push(r);else{let t;if(d){const n=mergeLearnings({source:e.learnings,target:d.learnings});t={...e,learnings:n.merged},c.mergeDetails[r]=n.details}else t=e,c.mergeDetails[r]={added:e.learnings.length,updated:0,unchanged:0};await i.writeBucket({bucket:t,namespace:n,isPublic:m}),c.bucketsPushed.push(r)}c.filePaths[r]=`${n}/${r}`}catch(e){c.success=!1,c.errors.push({bucket:r,error:e instanceof Error?e.message:String(e)})}return c}async function list(e){const{location:t}=e;let n;switch(t){case"local-project":n=new qi;break;case"local-global":n=new Vi;break;case"remote-project":case"remote-user":n=new Ki;break;default:throw new Error(`Invalid location: ${t}`)}return n instanceof Vi||n instanceof Ki?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 Vi;break;case"remote-project":case"remote-user":o=new Ki;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(!d(o))return r.success=!1,r.errors.push({file:"all",error:"No taste directory found in "+("local-global"===n?"global":"project")}),r;const s=[];if(t.length>0)for(const e of t){const t=getCategoryTasteFile({target:n,category:e});d(t)?s.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});d(e)&&s.push({path:e,displayName:"taste.md"});const t=await x.readdir(o,{withFileTypes:!0});for(const e of t)if(e.isDirectory()){const t=getCategoryTasteFile({target:n,category:e.name});d(t)&&s.push({path:t,displayName:`${e.name}/taste.md`})}}if(0===s.length&&r.errors.length>0)return r;if(0===s.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 s){let t=await x.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await x.writeFile(e.path,n,"utf-8"),t=n);const o=validateTasteFile({content:t,filePath:e.displayName}),s=o.issues.filter(e=>"error"===e.severity),a=o.issues.filter(e=>"warning"===e.severity);r.totalErrors+=s.length,r.totalWarnings+=a.length,o.valid||(r.success=!1);const i=formatValidationIssues({result:o});r.filesLinted.push({file:e.displayName,valid:o.valid,errors:s.length,warnings:a.length,formatted:i})}return r}async function open4(e){const{package:t,target:n}=e;try{let e;switch(n){case"local-project":e=new qi;break;case"local-global":e=new Vi;break;case"remote-project":case"remote-user":e=new Ki;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,s=await findCategoryLineNumber({filePath:o,category:t});return await je([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}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 x.readFile(t,"utf-8");if("taste.md"===y.basename(t)&&y.basename(y.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=We.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=y.join(v.homedir(),".commandcode","taste",".metadata.json");if(d(e))try{await x.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(open4,"open"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(runMigrations,"runMigrations"),__name(removeMetadataFile,"removeMetadataFile");var Yi=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 open4(e)}};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 ue.select({message:"Select namespace to push to\n",options:r,initialValue:t});return ue.isCancel(o)&&(ue.cancel("Operation cancelled"),process.exit(0)),o}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new Bn({baseUrl:e}),n=await t.get({endpoint:et.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}function createTasteCommand(){const e=new le("taste");e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments();const n=new Yi;return e.command("push").description("Push taste packages from project to remote or global storage (prompts on conflicts)").argument("[package]","Package name (optional if using --all)").option("--all","Push all packages").option("--remote","Push to remote (default)").option("-g, --global","Push to global storage").addOption(new de("--local","Use local server").hideHelp()).option("--public","Make this package publicly discoverable").option("--overwrite","Overwrite target without prompting (default: interactive merge)").addOption(new de("--staging","Push to staging environment").hideHelp()).action(async(e,r)=>{try{let o;if(r.global||r.remote||(r.remote=!0),r.global&&r.remote&&(console.error(t.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),e||r.all||(console.error(t.red("Error: Please specify a package name or use --all flag")),console.error(t.gray("Usage: cmd taste push <package> (pushes to remote by default)")),console.error(t.gray(" cmd taste push --all (pushes whole project)")),console.error(t.gray(" cmd taste push <package> -g (for global)")),process.exit(1)),e&&r.all&&(console.error(t.red("Error: Cannot use both package name and --all flag")),process.exit(1)),r.remote)if(r.all)o=await n.push({buckets:[],target:"remote-project",overwrite:r.overwrite,isPublic:r.public});else{let s,a;if(e&&e.includes("/")){const[n,r]=e.split("/");n&&r||(console.error(t.red("Error: Invalid namespace/package format")),console.error(t.gray("Usage: cmd taste push --remote username/packageName")),console.error(t.gray(" cmd taste push --remote org-name/packageName")),process.exit(1)),s=n,a=r}else{e||(console.error(t.red("Error: Please specify a package name")),console.error(t.gray("Usage: cmd taste push <namespace>/<package>")),console.error(t.gray(" or: cmd taste push <package> (interactive namespace selection)")),process.exit(1)),a=e;let r;(await n.list({location:"local-project"})).some(e=>e.category===a)||(console.error(t.red(`Error: Taste package '${a}' not found in local project`)),process.exit(1));try{r=await fetchUserNamespaces()}catch(e){throw e}s=r.orgs.length>0?await promptNamespaceSelection(r):r.userName}o=await n.pushRemote({namespace:s,packageName:a,overwrite:r.overwrite,isPublic:r.public})}else{const t="local-global",s=r.all?[]:[e];o=await n.push({buckets:s,target:t,overwrite:r.overwrite})}if(!o.success){for(const e of o.errors){const n=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(t.red(`Error: ${n}`))}process.exit(1)}let s=!1;if(r.all&&o.bucketsPushed.length>0){const e=o.filePaths?.[o.bucketsPushed[0]];if(e)if(r.overwrite)console.log(t.green(`✓ Replaced taste in ${e}`));else if(o.mergeDetails){let n=0,r=0,a=0;for(const e of Object.values(o.mergeDetails))n+=e.added??0,r+=e.updated??0,a+=e.unchanged??0;const i=[];n>0&&i.push(`${n} ${1===n?"learning":"learnings"} added`),r>0&&i.push(`${r} ${1===r?"learning":"learnings"} updated`),a>0&&i.push(`${a} ${1===a?"learning":"learnings"} unchanged`),i.length>0?console.log(t.green(`✓ Pushed taste to ${e} (${i.join(", ")})`)):console.log(t.green(`✓ Pushed taste to ${e}`)),(n>0||r>0)&&a>0&&(s=!0)}else console.log(t.green(`✓ Pushed taste to ${e}`));else console.log(t.green("✓ Pushed taste to remote"))}else if(1===o.bucketsPushed.length){const e=o.bucketsPushed[0],n=o.filePaths?.[e];if(r.overwrite)r.remote&&n?console.log(t.green(`✓ Replaced '${e}' taste package in ${n}`)):(console.log(t.green(`✓ Replaced '${e}' taste package in global`)),n&&console.log(t.gray(` Path: ${n}`)));else if(o.mergeDetails?.[e]){const a=o.mergeDetails[e],i=[];a.added>0&&i.push(`${a.added} ${1===a.added?"learning":"learnings"} added`),a.updated>0&&i.push(`${a.updated} ${1===a.updated?"learning":"learnings"} updated`),a.unchanged>0&&i.push(`${a.unchanged} ${1===a.unchanged?"learning":"learnings"} unchanged`),r.remote&&n?console.log(t.green(`✓ Pushed '${e}' taste package to ${n} (${i.join(", ")})`)):(console.log(t.green(`✓ Pushed '${e}' taste package to global (${i.join(", ")})`)),n&&console.log(t.gray(` Path: ${n}`))),(a.added>0||a.updated>0)&&a.unchanged>0&&(s=!0)}else r.remote&&n?console.log(t.green(`✓ Pushed '${e}' taste package to ${n}`)):(console.log(t.green(`✓ Pushed '${e}' taste package to global`)),n&&console.log(t.gray(` Path: ${n}`)))}else if(o.bucketsPushed.length>0){const e=r.remote?"remote":"global";if(console.log(t.green(`✓ Pushed ${o.bucketsPushed.length} taste packages (${o.bucketsPushed.join(", ")}) to ${e}`)),!r.overwrite&&o.mergeDetails)for(const e of Object.values(o.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){s=!0;break}}s&&console.log(t.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("pull").argument("[package]","Package name (optional if using --all)").option("-g, --global","Pull from global").addOption(new de("--local","Use local server").hideHelp()).option("--remote","Pull from remote").option("--all","Pull all packages").option("--overwrite","Overwrite local without prompting (default: interactive merge)").addOption(new de("--staging","Use staging environment").hideHelp()).description("Pull packages from storage to project (prompts on conflicts)").action(async(e,r)=>{try{let o,s;if(r.global||r.remote||(r.remote=!0),r.global&&r.remote&&(console.error(t.red("Error: Cannot use both --global and --remote flags")),process.exit(1)),r.remote&&r.all&&(console.error(t.red("Error: The --all flag is not supported for remote pull")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),r.remote&&!e&&(console.error(t.red("Error: Please provide both namespace and package name")),process.exit(1)),r.remote&&e&&!e.includes("/")&&(console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),e||r.all||(console.error(t.red("Error: Please specify a package name or use --all flag")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package> (remote by default)")),console.error(t.gray(" cmd taste pull <package> -g (from global)")),console.error(t.gray(" cmd taste pull --all -g (all from global)")),process.exit(1)),e&&r.all&&(console.error(t.red("Error: Cannot use both package name and --all flag")),process.exit(1)),r.remote){e.includes("/")||(console.error(t.red("Error: Package name must include namespace")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1));const[a,i]=e.split("/");a&&i||(console.error(t.red("Error: Invalid namespace/package format")),console.error(t.gray("Usage: cmd taste pull <namespace>/<package>")),process.exit(1)),s=a,o=await n.pullRemote({namespace:s,packageName:i,overwrite:r.overwrite})}else{const t="local-global",s=r.all?[]:[e];o=await n.pull({buckets:s,source:t,overwrite:r.overwrite})}const a=r.remote?s?`${s}`:"remote":"global";if(!o.success){for(const e of o.errors){const n=e.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${e.bucket}' `);console.error(t.red(`Error: ${n}`))}process.exit(1)}if(o.skipped&&o.skipped.length>0)for(const e of o.skipped)console.log(t.yellow(`⊘ Skipped '${e}' - kept local version`));let i=!1;if(1===o.bucketsPulled.length){const e=o.bucketsPulled[0],n=o.filePaths?.[e];if(r.overwrite)console.log(t.green(`✓ Replaced '${e}' taste package in project`)),n&&console.log(t.gray(` Saved to: ${n}`));else if(o.mergeDetails?.[e]){const r=o.mergeDetails[e],s=[];r.added>0&&s.push(`${r.added} ${1===r.added?"learning":"learnings"} added`),r.updated>0&&s.push(`${r.updated} ${1===r.updated?"learning":"learnings"} updated`),r.unchanged>0&&s.push(`${r.unchanged} ${1===r.unchanged?"learning":"learnings"} unchanged`),console.log(t.green(`✓ Pulled '${e}' taste package from ${a} (${s.join(", ")})`)),n&&console.log(t.gray(` Saved to: ${n}`)),(r.added>0||r.updated>0)&&r.unchanged>0&&(i=!0)}else console.log(t.green(`✓ Pulled '${e}' taste package from ${a}`)),n&&console.log(t.gray(` Saved to: ${n}`))}else if(o.bucketsPulled.length>0){const e=` (${o.bucketsPulled.join(", ")})`;if(console.log(t.green(`✓ Pulled ${o.bucketsPulled.length} taste packages${e} from ${a}`)),!r.overwrite&&o.mergeDetails)for(const e of Object.values(o.mergeDetails))if((e.added>0||e.updated>0)&&e.unchanged>0){i=!0;break}}i&&console.log(t.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("list").option("-g, --global","List global packages").addOption(new de("--local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new de("--staging","Use staging environment").hideHelp()).description("List available packages").action(async e=>{try{let r,o;e.global&&e.remote&&(console.error(t.red("Error: Cannot specify both --global and --remote flags")),process.exit(1)),e.remote?(r="remote-project",o="remote"):e.global?(r="local-global",o="global"):(r="local-project",o="project");const s=await n.list({location:r});if(0===s.length)return void console.log(t.yellow(`No taste packages found in ${o}`));let a;console.log(t.hex("#E4CCFF").bold("\nTaste Packages")),a="remote-project"===r?"Stored in your commandcode.ai account":"local-global"===r?"Stored globally in ~/.commandcode/taste":"Stored locally in .commandcode/taste",console.log(t.dim(a+"\n"));let i=0;const c=__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"),l=Math.max(...s.map(c));for(const e of s){i+=e.learningCount;const n=getTimeAgo(e.lastUpdated),r=" ".repeat(l-c(e)+2),o=t.white(e.category),s=e.isPublic?t.green(" [public]"):"",a=e.isPublic&&e.starCount?t.yellow(` ★${e.starCount}`):"",d=e.downloadCount?t.gray(` ↓${e.downloadCount}`):"";console.log(` ${o}${s}${a}${d}${r}${t.dim.gray(`(${e.learningCount} learnings, updated ${n})`)}`)}console.log(t.dim(`\nTotal: ${s.length} packages, ${i} learnings\n`))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.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,r)=>{try{e||r.all||(console.error(t.red("Error: Please specify a package name or use --all flag")),console.error(t.gray("Usage: cmd taste lint <package>")),console.error(t.gray(" cmd taste lint --all")),process.exit(1)),e&&r.all&&(console.error(t.red("Error: Cannot use both package name and --all flag")),process.exit(1));const o=await n.lint({packages:e?[e]:[],target:r.global?"local-global":"local-project"});if(o.errors.length>0){for(const e of o.errors)console.error(t.red(`Error: ${e.error}`));process.exit(1)}for(const e of o.filesLinted)console.log(e.formatted);if(o.filesLinted.length>1)if(console.log(""),0===o.totalErrors&&0===o.totalWarnings)console.log(t.green(`✓ All ${o.filesLinted.length} taste files are valid`));else{const e=[];o.totalErrors>0&&e.push(t.red(`${o.totalErrors} error${o.totalErrors>1?"s":""}`)),o.totalWarnings>0&&e.push(t.yellow(`${o.totalWarnings} warning${o.totalWarnings>1?"s":""}`)),console.log(`Summary: ${e.join(", ")} across ${o.filesLinted.length} files`)}o.success||process.exit(1)}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e.command("open").argument("<package>","Package name to open").option("-g, --global","Open from global").description("Open a package in your editor").action(async(e,r)=>{try{const o=r.global?"local-global":"local-project",s=await n.open({package:e,target:o});s.success||(console.error(t.red(s.error)),process.exit(1)),console.log(t.green(`✓ Opened '${e}' taste package from ${r.global?"global":"project"}`))}catch(e){console.error(t.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}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 formatVersion(e,t,n=!1){const r=n?Y.bold(Y.green(t)):Y.white(t);return`${Y.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${Y.bold(Y.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(Y.dim(`Run ${Y.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(Y.dim("Try updating manually:")),console.log(Y.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(Y.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=ke("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${Y.green(ae.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${Y.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=ke("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${ae.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),trackError({error:sanitizeErrorForTelemetry({error:new Error("Update failed"),label:"cli_update_failed"}),context:{component:zt.UPDATE_COMMAND,heading:"CLI update failed","update.current_version":t.currentVersion,"update.target_version":t.latestVersion}}),showManualUpdateHint(t.latestVersion),await shutdownTelemetry(),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${Y.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(promptNamespaceSelection,"promptNamespaceSelection"),__name(fetchUserNamespaces,"fetchUserNamespaces"),__name(createTasteCommand,"createTasteCommand"),__name(getTimeAgo,"getTimeAgo"),__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(checkAction,"checkAction"),__name(performUpdateAction,"performUpdateAction"),__name(updateAction,"updateAction");var Qi=new le("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction),Zi=__name((e,t)=>`${ae.info} ${e}: ${Y.cyan(t)}`,"formatInfoLine"),Xi=__name(e=>Y.bold(`${e}:`),"formatSectionHeader"),ec=__name(e=>Y.red(e),"formatError"),tc=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),nc=__name(e=>["",Xi("User Information"),Zi("Name",e.name),Zi("Email",e.email),Zi("Username",e.userName)],"buildUserOutput"),rc=__name(e=>["",Xi("Organization"),Zi("Name",e.name),Zi("Login",e.login)],"buildOrgOutput"),oc=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),sc=__name((e,t)=>{oc(nc(e)),t&&oc(rc(t)),console.log("")},"displayUserInfo"),ac=__name(e=>null!==e&&e.length>0,"validateApiKey"),ic=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=ke("Fetching user information...").start();try{const t=await getAuthKey();ac(t)||(e.fail(ec('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();ic(n)||(e.fail(ec("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),sc(n.user,n.org)}catch(t){e.fail(ec(`Error: ${tc(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var cc=new le("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);handleUnhandledErrors(),setupTelemetry(),await preRun();var lc=createProgram();lc.action(interactiveModeAction),lc.addCommand(Fi),lc.addCommand(Hi),lc.addCommand(cc),lc.addCommand(Qi),lc.addCommand(createTasteCommand()),lc.addCommand(Gi),lc.addCommand(rn),lc.addCommand(ln),lc.addCommand(hn),setupCommanderHooks(lc),lc.parse();