command-code 0.38.7 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import*as e from"path";import t,{join as n,dirname as r,parse as o,relative as s,isAbsolute as i,resolve as a,extname as l,basename as u}from"path";import{fileURLToPath as d,pathToFileURL as m,URL as g}from"url";import h,{z as f,ZodError as y}from"zod";import*as w from"os";import S,{tmpdir as E,homedir as v}from"os";import*as C from"fs/promises";import k,{mkdir as T,writeFile as _,rm as x,readFile as A,unlink as P,readdir as I}from"fs/promises";import*as M from"crypto";import R,{randomUUID as N,createHash as L}from"crypto";import*as $ from"fs";import D,{existsSync as O,promises as F,readFileSync as j,constants as U,mkdirSync as B,writeFileSync as q,statSync as z,readdirSync as H,createReadStream as W,appendFileSync as G}from"fs";import*as V from"http";import{createServer as K}from"http";import{Box as Q,Text as Y,Static as J,useStdout as X,useInput as Z,render as ee,useApp as te,Newline as ne}from"ink";import re,{memo as oe,useState as se,useRef as ie,useEffect as ae,useMemo as le,useCallback as ce}from"react";import ue from"chalk";import de from"picocolors";import me from"strip-ansi";import{Jimp as pe,JimpMime as ge}from"jimp";import he from"open";import fe from"@opentelemetry/sdk-node";import ye from"@opentelemetry/exporter-trace-otlp-http";import we from"@opentelemetry/resources";import Se from"@opentelemetry/semantic-conventions";import be from"@opentelemetry/sdk-trace-node";import{exec as Ee,spawn as ve,execSync as Ce,execFileSync as ke,execFile as Te,spawnSync as _e}from"child_process";import{trace as xe,context as Ae,SpanKind as Pe,SpanStatusCode as Ie}from"@opentelemetry/api";import{v4 as Me}from"uuid";import Re from"figures";import{Command as Ne,Option as Le,InvalidArgumentError as $e}from"commander";import De from"ora";import*as Oe from"net";import Fe from"net";import je from"tls";import Ue from"stream";import{performance as Be}from"perf_hooks";import qe from"gray-matter";import ze from"@sindresorhus/slugify";import{EventEmitter as He}from"events";import We from"ink-spinner";import*as Ge from"@clack/prompts";import{multiselect as Ve,confirm as Ke,note as Qe,cancel as Ye,select as Je,isCancel as Xe,password as Ze}from"@clack/prompts";import"dotenv/config";import et from"dedent";import tt from"log-symbols";import{minimatch as nt}from"minimatch";import{glob as rt}from"glob";import{parse as ot,quote as st}from"shell-quote";import it from"ignore";import{createRequire as at}from"module";import lt from"ansi-escapes";import ct from"string-width";import*as ut from"readline";import dt from"readline";import mt from"semver";import{promisify as pt}from"util";import{inflateRawSync as gt}from"zlib";import ht from"strip-json-comments";import ft from"ink-select-input";import{Marked as yt}from"marked";import wt from"marked-terminal";import*as St from"diff";import bt from"is-unicode-supported";import Et from"open-editor";import{wrapAnsi as vt}from"fast-wrap-ansi";import Ct from"terminal-link";import*as kt from"process";var Tt,_t,xt,At,Pt,It,Mt,Rt,Nt,Lt,$t,Dt,Ot,Ft,jt=Object.defineProperty,Ut=Object.getOwnPropertyNames,__name=(e,t)=>jt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[Ut(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)jt(e,n,{get:t[n],enumerable:!0})},Bt=__esm({"../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.12_tsx@4.21.0_typescript@5.9.3_yaml@2.8.3/node_modules/tsup/assets/esm_shims.js"(){}}),qt=__esm({"../shared/src/constants/tracing.ts"(){Bt(),Tt="command_code_cli_tracing"}});function isContentCaptureEnabled(){const e=process.env[Ft];return"1"===e||"true"===e}var zt,Ht,Wt,Gt,Vt,Kt,Qt,Yt,Jt,Xt,Zt,en,tn,nn,rn,on,sn,an,ln,cn,un,dn,mn,pn,gn,hn,fn,yn,wn,Sn,bn,En,vn,Cn,kn=__esm({"src/utils/telemetry/constants.ts"(){Bt(),qt(),_t="https://api.axiom.co/v1/traces",xt="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",At="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",Pt="xaat-add69148-8f73-4833-921d-bc843285c95f",It="command-code-cli",Mt=2e3,Rt=512,Nt=128,Lt=500,$t=5e3,Dt={PROVIDER_NAME:"gen_ai.provider.name",OPERATION_NAME:"gen_ai.operation.name",CONVERSATION_ID:"gen_ai.conversation.id",CAPABILITY_NAME:"gen_ai.capability.name",STEP_NAME:"gen_ai.step.name",TOOL_NAME:"gen_ai.tool.name",REQUEST_MODEL:"gen_ai.request.model",REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",REQUEST_TEMPERATURE:"gen_ai.request.temperature",REQUEST_TOP_P:"gen_ai.request.top_p",RESPONSE_MODEL:"gen_ai.response.model",RESPONSE_ID:"gen_ai.response.id",RESPONSE_FINISH_REASONS:"gen_ai.response.finish_reasons",USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",USAGE_CACHED_INPUT_TOKENS:"gen_ai.usage.cached_input_tokens"},Ot={ORG_LOGIN:"cmd.org.login",ORG_ID:"cmd.org.id",COMMAND_NAME:"cmd.command.name",COMMAND_ARGS:"cmd.command.args",SESSION_PROJECT_HASH:"cmd.session.project_hash",SESSION_BRANCH_HASH:"cmd.session.branch_hash",ITERATION_NUMBER:"cmd.iteration.number",ITERATION_OUTCOME:"cmd.iteration.outcome",ITERATION_TERMINAL_ERROR_TYPE:"cmd.iteration.terminal_error_type",ITERATION_TERMINAL_ERROR_MESSAGE:"cmd.iteration.terminal_error_message",ITERATION_INITIAL_MESSAGE_COUNT:"cmd.iteration.initial_message_count",PAYLOAD_MESSAGE_COUNT:"cmd.payload.message_count",PAYLOAD_USER_MESSAGE_COUNT:"cmd.payload.user_message_count",PAYLOAD_ASSISTANT_MESSAGE_COUNT:"cmd.payload.assistant_message_count",PAYLOAD_TOOL_MESSAGE_COUNT:"cmd.payload.tool_message_count",PAYLOAD_ASSISTANT_WITH_TOOL_USE_COUNT:"cmd.payload.assistant_with_tool_use_count",PAYLOAD_TOOL_USE_COUNT:"cmd.payload.tool_use_count",PAYLOAD_TOOL_RESULT_COUNT:"cmd.payload.tool_result_count",PAYLOAD_ORPHAN_TOOL_USE_COUNT:"cmd.payload.orphan_tool_use_count",PAYLOAD_ORPHAN_TOOL_RESULT_COUNT:"cmd.payload.orphan_tool_result_count",PAYLOAD_LAST_MESSAGE_ROLE:"cmd.payload.last_message_role",API_ATTEMPT_NUMBER:"cmd.api.attempt.number",API_ATTEMPT_DELAY_MS_BEFORE:"cmd.api.attempt.delay_ms_before",API_ATTEMPT_STATUS:"cmd.api.attempt.status",API_ATTEMPT_HTTP_STATUS:"cmd.api.attempt.http_status",API_ATTEMPT_IS_RETRYABLE:"cmd.api.attempt.is_retryable",API_ATTEMPT_ERROR_TYPE:"cmd.api.attempt.error_type",API_ATTEMPT_ERROR_MESSAGE:"cmd.api.attempt.error_message",SANITIZE_UNMATCHED_COUNT:"cmd.sanitize.unmatched_count",SANITIZE_TOOL_NAMES:"cmd.sanitize.tool_names",SANITIZE_NEXT_MESSAGE_ROLE:"cmd.sanitize.next_message_role",ERROR_FINGERPRINT:"cmd.error.fingerprint",ERROR_COMPONENT:"cmd.error.component",ERROR_HEADING:"cmd.error.heading",ERROR_CODE:"cmd.error.code"},Ft="COMMAND_CODE_TELEMETRY_CAPTURE_CONTENT",__name(isContentCaptureEnabled,"isContentCaptureEnabled")}});function getModelCategory({provider:e,model:t}){if(e===Qt.VERCEL_AI_GATEWAY)return Zt.has(t)?"premium":"opensource";if(e===Qt.CLOUDFLARE_AI_GATEWAY||e===Qt.OPENROUTER)return"opensource";const n=en[e];if(!n)return null;const r=`${e}:${t}`,o=n.find(e=>e.id===r);return o?.category??null}function getPlanDisplayName(e){return e.replace("individual-","").replace("teams-","Teams ").split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function getMinimumPlanForModel({fullModelId:e,category:t}){for(const n of on){const r=rn[n];if(!r)continue;const o=r.allowedCategories.includes(t),s=r.blockedModels?.includes(e)??!1;if(o&&!s)return n}return null}function buildModelGroups(e){const t=Object.values(pn).filter(e=>!e.hidden),n=[];for(const r of Object.values(Sn)){if(!("co"===e?r.visibleInCoMode:r.visibleInNormalMode))continue;const o=t.filter(e=>r.supportedModelProviders.includes(e.provider));o.length>0&&n.push({providerId:r.id,label:r.label,models:o})}return n}var Tn,_n=__esm({"../shared/src/constants.ts"(){Bt(),Ht="--xco",Wt={INTERNAL_TEAM_FLAG_HEADER:`x-${(zt="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",OAUTH_PROVIDER:"x-oauth-provider",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage",CLI_ENVIRONMENT:"x-cli-environment",CLI_VERSION:"x-command-code-version",OSS_PRIMARY_PROVIDER:"x-oss-primary-provider",SESSION_ID:"x-session-id",SYSTEM_PROMPT_BREAKDOWN:"x-system-prompt-breakdown",CMD_ZDR:"x-cmd-zdr"},Gt={V1:{CHAT_COMPLETIONS:"/provider/v1/chat/completions",MODELS:"/provider/v1/models",MESSAGES:"/provider/v1/messages"},ALPHA:{GENERATE:"/alpha/generate",WHOAMI:"/alpha/whoami",NAMESPACES:"/alpha/namespaces",AGENT:{GENERATE:"/alpha/agent/generate"},WEB_SEARCH:"/alpha/web-search",WEB_FETCH:"/alpha/web-fetch",SANDBOX:{START:"/alpha/sandbox/start",STREAM:"/alpha/sandbox/stream",STATUS:"/alpha/sandbox/status",STOP:"/alpha/sandbox/stop",SESSIONS:"/alpha/sandbox/sessions"},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"},BILLING:{CREDITS:"/alpha/billing/credits",SUBSCRIPTIONS:"/alpha/billing/subscriptions"},USAGE:{SUMMARY:"/alpha/usage/summary"},LIFECYCLE_EVENTS:{TRACK:"/alpha/lifecycle-events"},COURSES_LEAD:"/alpha/courses-lead",CONVERSIONS:{TRACK:"/alpha/conversions/track"},CONSENT:{SET:"/alpha/consent/set"}},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",BAN_USER:"/internal/admin/ban-user",BAN_ORG:"/internal/admin/ban-org",UNBAN_USER:"/internal/admin/unban-user",UNBAN_ORG:"/internal/admin/unban-org",DELETE_USER:"/internal/admin/delete-user",DELETE_ORG:"/internal/admin/delete-org",MIGRATE:{PLAN_IDS:"/internal/admin/migrations/plan-ids"}},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"},FINGERPRINT:{RECORD:"/internal/fingerprint/record"},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"},CHECKOUT_ELIGIBILITY:"/internal/billing/checkout/eligibility",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",CHARTS:"/internal/usage/charts"},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"}}}},Vt={ALPHA:{TASTE:{GET:new RegExp("/alpha/taste/[a-z0-9-]+"),UPDATE:new RegExp("/alpha/taste/[a-z0-9-]+/update"),DELETE:new RegExp("/alpha/taste/[a-z0-9-]+/rules/[a-z0-9-]+"),LIST:new RegExp("/alpha/taste/[a-z0-9-]+/rules")},PACKAGES:{FILES:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/download")}},BETA:{TASTE_PACKAGES:{UPLOAD:new RegExp("^/beta/taste/packages/[a-zA-Z0-9_-]+$"),FILES:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}},INTERNAL:{ORGS:{GET:new RegExp("/internal/orgs/[a-zA-Z0-9_-]+"),FOLLOW:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/followers")},USER:{FOLLOW:new RegExp("/internal/users/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/users/[a-zA-Z0-9-]+/followers"),FOLLOWING:new RegExp("/internal/users/[a-zA-Z0-9-]+/following")},TASTE:{PACKAGES:{GET:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),FILES:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),DOWNLOAD:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download"),UPDATE:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/update"),STAR:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/star"),PIN:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pin")}}}},Object.values(Vt.ALPHA.TASTE),Object.values(Vt.BETA.TASTE_PACKAGES),new RegExp("^/alpha/sandbox/status/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"),new RegExp("^/alpha/sandbox/stop/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"),new RegExp("^/alpha/sandbox/stream/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"),Gt.V1.CHAT_COMPLETIONS,Gt.V1.MESSAGES,Gt.ALPHA.GENERATE,Gt.ALPHA.AGENT.GENERATE,Gt.ALPHA.WHOAMI,Gt.ALPHA.WEB_SEARCH,Gt.ALPHA.WEB_FETCH,Gt.ALPHA.NAMESPACES,Gt.ALPHA.SANDBOX.START,Gt.ALPHA.SHARE.CREATE,Gt.ALPHA.SHARE.DELETE,Gt.ALPHA.SHARE.APPEND,Gt.ALPHA.DEVREL_THREAD.CREATE,Gt.ALPHA.DEVREL_THREAD.DELETE,Gt.ALPHA.DEVREL_THREAD.UPDATE,Gt.ALPHA.TASTE.LEARN,Gt.ALPHA.TASTE.DELETE,Gt.ALPHA.TASTE.GET,Gt.ALPHA.TASTE.UPDATE,Object.values(Gt.BETA.TASTE.PACKAGES),Gt.ALPHA.BILLING.CREDITS,Gt.ALPHA.BILLING.SUBSCRIPTIONS,Gt.ALPHA.USAGE.SUMMARY,Gt.ALPHA.LIFECYCLE_EVENTS.TRACK,Gt.INTERNAL.ADMIN.USERS,Gt.INTERNAL.ADMIN.ORGS,Gt.INTERNAL.ADMIN.ENTITY_TYPE,Gt.INTERNAL.USER.AVATAR,Gt.INTERNAL.USER.SETTINGS,Gt.INTERNAL.API_KEYS.LIST,Gt.INTERNAL.API_KEYS.CREATE,Gt.INTERNAL.API_KEYS.DELETE,Gt.INTERNAL.FINGERPRINT.RECORD,Gt.INTERNAL.USAGE.LIST,Gt.INTERNAL.USAGE.SUMMARY,Gt.INTERNAL.USAGE.CHARTS,Gt.INTERNAL.ADMIN.GRANT_CREDITS,Gt.INTERNAL.ADMIN.GRANT_ORG_CREDITS,Gt.INTERNAL.ADMIN.BAN_USER,Gt.INTERNAL.ADMIN.BAN_ORG,Gt.INTERNAL.ADMIN.UNBAN_USER,Gt.INTERNAL.ADMIN.UNBAN_ORG,Gt.INTERNAL.ADMIN.DELETE_USER,Gt.INTERNAL.ADMIN.DELETE_ORG,Gt.INTERNAL.BILLING.CREDITS.GET,Gt.INTERNAL.BILLING.CUSTOMERS.GET,Gt.INTERNAL.BILLING.CUSTOMERS.UPSERT,Gt.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,Gt.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,Gt.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,Gt.INTERNAL.BILLING.CUSTOMERS.INVOICES,Gt.INTERNAL.BILLING.SUBSCRIPTIONS.GET,Gt.INTERNAL.BILLING.CHECKOUT_ELIGIBILITY,Gt.INTERNAL.ORGS.LIST,Gt.INTERNAL.ORGS.GET,Gt.INTERNAL.ORGS.CREATE,Gt.INTERNAL.ORGS.UPDATE,Gt.INTERNAL.ORGS.DELETE,Gt.INTERNAL.ORGS.MEMBERS.LIST,Gt.INTERNAL.ORGS.MEMBERS.ADD,Gt.INTERNAL.ORGS.MEMBERS.UPDATE,Gt.INTERNAL.ORGS.MEMBERS.REMOVE,Gt.INTERNAL.ORGS.INVITATIONS.LIST,Gt.INTERNAL.ORGS.INVITATIONS.SEND,Gt.INTERNAL.ORGS.INVITATIONS.ACCEPT,Gt.INTERNAL.ORGS.INVITATIONS.CANCEL,Gt.INTERNAL.TASTE.PACKAGES.LIST,Gt.INTERNAL.ADMIN.MIGRATE.PLAN_IDS,Object.values(Vt.INTERNAL.ORGS),Object.values(Vt.INTERNAL.USER),Object.values(Vt.INTERNAL.TASTE.PACKAGES),Kt={INTERNAL:{PROFILE:{GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+"),PACKAGES:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages"),FOLLOWING:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/following"),FOLLOWERS:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/followers"),PACKAGE_GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+"),PACKAGE_DOWNLOAD:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+/download")}}},Object.values(Kt.INTERNAL.PROFILE),Yt={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},Jt=[(Qt={ANTHROPIC:"anthropic",OPENAI:"openai",BASETEN:"baseten",VERCEL_AI_GATEWAY:"vercel-ai-gateway",CLOUDFLARE_AI_GATEWAY:"cloudflare-ai-gateway",OPENROUTER:"openrouter",SPIDER_WEB:"spider_web"}).VERCEL_AI_GATEWAY,Qt.BASETEN,Qt.CLOUDFLARE_AI_GATEWAY,Qt.OPENROUTER],Xt=Jt[0],Qt.ANTHROPIC,Qt.OPENAI,Zt=new Set(["google/gemini-3.5-flash","google/gemini-3.1-flash-lite"]),en={[Qt.ANTHROPIC]:[{id:"anthropic:claude-sonnet-4-20250514",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-sonnet-4-5-20250929",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-opus-4-5-20251101",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-sonnet-4-6",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-fable-5",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:1},{id:"anthropic:claude-opus-4-8",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-7",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-6",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-haiku-4-5-20251001",provider:"Anthropic",category:"premium",promptCost:1,completionCost:5,cacheWrite5mCost:1.25,cacheWrite1hCost:2,cacheHitCost:.1}],[Qt.OPENAI]:[{id:"openai:gpt-5.5",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4",provider:"OpenAI",category:"premium",promptCost:2.5,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.25},{id:"openai:gpt-5.3-codex",provider:"OpenAI",category:"premium",promptCost:2,completionCost:8,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4-mini",provider:"OpenAI",category:"premium",promptCost:.75,completionCost:4.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.075}],[Qt.BASETEN]:[{id:"baseten:zai-org/GLM-5",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:3.15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.5",provider:"Baseten",category:"opensource",promptCost:.6,completionCost:3,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.6",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.16},{id:"baseten:MiniMaxAI/MiniMax-M2.5",provider:"Baseten",category:"opensource",promptCost:.5,completionCost:2,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0}],[Qt.VERCEL_AI_GATEWAY]:[],[Qt.OPENROUTER]:[]},__name(getModelCategory,"getModelCategory"),tn={"individual-go":{premium:0,opensource:10,total:10},"individual-pro":{premium:15,opensource:15,total:30},"individual-provider":{premium:15,opensource:0,total:15},"individual-max":{premium:100,opensource:50,total:150},"individual-ultra":{premium:200,opensource:100,total:300},"teams-pro":{premium:40,opensource:0,total:40}},nn={"individual-go":"Go","individual-pro":"Pro","individual-provider":"Provider","individual-max":"Max","individual-ultra":"Ultra","teams-pro":"Teams Pro"},rn={"individual-go":{allowedCategories:["opensource"]},"individual-pro":{allowedCategories:["premium","opensource"],blockedModels:["anthropic:claude-fable-5","anthropic:claude-opus-4-8","anthropic:claude-opus-4-7","anthropic:claude-opus-4-6","anthropic:claude-opus-4-5-20251101"]},"individual-provider":{allowedCategories:["premium","opensource"]},"individual-max":{allowedCategories:["premium","opensource"]},"individual-ultra":{allowedCategories:["premium","opensource"]},"teams-pro":{allowedCategories:["premium","opensource"]}},on=["individual-go","individual-pro","individual-provider","individual-max","individual-ultra","teams-pro"],__name(getPlanDisplayName,"getPlanDisplayName"),__name(getMinimumPlanForModel,"getMinimumPlanForModel"),sn=[50,75,90],h.enum(["owner","admin","member"]),an={LEARN_TASTE:"learn-taste",TASTE:"taste",TERMINAL_SETUP:"terminal-setup"},ln={MAX_PROMPT_TOKENS:25e3,MAX_PROMPT_CHARS:1e5,DB_PROMPT_MAX_WORDS:10},cn=["active","trialing","past_due"],un="chatComplete",dn="responses",mn="MiniMaxAI/MiniMax-M3-Free",(pn={SONNET_4_6:{id:"claude-sonnet-4-6",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Sonnet 4.6",name:"Claude Sonnet 4.6",description:"best combo of speed & intelligence (recommended)",reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5:{id:"claude-fable-5",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Fable 5",name:"Claude Fable 5",description:"most capable for demanding reasoning & long-horizon agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_8:{id:"claude-opus-4-8",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Opus 4.8",name:"Claude Opus 4.8",description:"most intelligent Opus for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_7:{id:"claude-opus-4-7",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Opus 4.7",name:"Claude Opus 4.7",description:"prev flagship, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},HAIKU_4_5:{id:"claude-haiku-4-5-20251001",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Haiku 4.5",name:"Claude Haiku 4.5",description:"fastest & most compact, great for quick tasks",contextWindow:2e5},GPT_5_5:{id:"gpt-5.5",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.5",name:"GPT-5.5",description:"latest frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"]},GPT_5_4:{id:"gpt-5.4",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.4",name:"GPT-5.4",description:"frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_3_CODEX:{id:"gpt-5.3-codex",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.3 Codex",name:"GPT-5.3 Codex",description:"frontier coding model",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_4_MINI:{id:"gpt-5.4-mini",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.4 Mini",name:"GPT-5.4 Mini",description:"fast, cost-effective model for everyday tasks",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:4e5},MINIMAX_M3_FREE:{id:mn,inputModalities:["text","image"],provider:Xt,spec:un,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",badge:"free",reasoning:!0,contextWindow:1e6},DEEPSEEK_V4_PRO:{id:"deepseek/deepseek-v4-pro",inputModalities:["text"],provider:Xt,spec:un,label:"DeepSeek V4 Pro",name:"DeepSeek V4 Pro",description:"hybrid-attention long-context reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH:{id:"deepseek/deepseek-v4-flash",inputModalities:["text"],provider:Xt,spec:un,label:"DeepSeek V4 Flash",name:"DeepSeek V4 Flash",description:"fast hybrid-attention reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},KIMI_K2_7_CODE:{id:"moonshotai/Kimi-K2.7-Code",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.7 Code",name:"Kimi K2.7 Code",description:"improved long-horizon coding with vision",reasoning:!0,contextWindow:256e3},KIMI_K2_7_CODE_HIGHSPEED:{id:"moonshotai/Kimi-K2.7-Code-Highspeed",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.7 Code HighSpeed",name:"Kimi K2.7 Code HighSpeed",description:"high-speed long-horizon coding with vision",reasoning:!0,contextWindow:262e3},KIMI_K2_6:{id:"moonshotai/Kimi-K2.6",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.6",name:"Kimi K2.6",description:"long-horizon coding with vision",contextWindow:256e3},KIMI_K2_5:{id:"moonshotai/Kimi-K2.5",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.5",name:"Kimi K2.5",description:"multimodal frontend coding",contextWindow:256e3},GLM_5_2:{id:"zai-org/GLM-5.2",inputModalities:["text"],provider:Xt,spec:un,label:"GLM-5.2",name:"GLM-5.2",description:"powerful coding with 1M context and long-horizon tasks",contextWindow:1e6},GLM_5_1:{id:"zai-org/GLM-5.1",inputModalities:["text"],provider:Xt,spec:un,label:"GLM-5.1",name:"GLM-5.1",description:"long-horizon autonomous coding agent"},GLM_5:{id:"zai-org/GLM-5",inputModalities:["text"],provider:Xt,spec:un,label:"GLM-5",name:"GLM-5",description:"multi-mode thinking & long-range planning",contextWindow:2e5},MINIMAX_M3:{id:"MiniMaxAI/MiniMax-M3",inputModalities:["text","image"],provider:Xt,spec:un,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",reasoning:!0,contextWindow:1e6},MINIMAX_M2_7:{id:"MiniMaxAI/MiniMax-M2.7",inputModalities:["text"],provider:Xt,spec:un,label:"MiniMax M2.7",name:"MiniMax M2.7",description:"end-to-end software engineering agent"},MINIMAX_M2_5:{id:"MiniMaxAI/MiniMax-M2.5",inputModalities:["text"],provider:Xt,spec:un,label:"MiniMax M2.5",name:"MiniMax M2.5",description:"cross-platform full-stack agentic dev",contextWindow:2e5},XIAOMI_MIMO_V2_5_PRO:{id:"xiaomi/mimo-v2.5-pro",inputModalities:["text"],provider:Xt,spec:un,label:"MiMo V2.5 Pro",name:"MiMo V2.5 Pro",description:"high-capability long-context agentic coding",contextWindow:1e6},XIAOMI_MIMO_V2_5:{id:"xiaomi/mimo-v2.5",inputModalities:["text","image"],provider:Xt,spec:un,label:"MiMo V2.5",name:"MiMo V2.5",description:"efficient long-context agentic coding",contextWindow:1e6},QWEN_3_6_MAX_PREVIEW:{id:"Qwen/Qwen3.6-Max-Preview",inputModalities:["text"],provider:Xt,spec:un,label:"Qwen 3.6 Max Preview",name:"Qwen 3.6 Max Preview",description:"vibe coding & efficient agent execution",reasoning:!0},QWEN_3_6_PLUS:{id:"Qwen/Qwen3.6-Plus",inputModalities:["text","image"],provider:Xt,spec:un,label:"Qwen 3.6 Plus",name:"Qwen 3.6 Plus",description:"agentic coding & reasoning",reasoning:!0},QWEN_3_7_MAX:{id:"Qwen/Qwen3.7-Max",inputModalities:["text"],provider:Xt,spec:un,label:"Qwen 3.7 Max",name:"Qwen 3.7 Max",description:"frontier coding & long-horizon agent execution",reasoning:!0,contextWindow:1e6},QWEN_3_7_PLUS:{id:"Qwen/Qwen3.7-Plus",inputModalities:["text","image"],provider:Xt,spec:un,label:"Qwen 3.7 Plus",name:"Qwen 3.7 Plus",description:"agentic coding & reasoning at lower cost",reasoning:!0,contextWindow:1e6},STEP_3_7_FLASH:{id:"stepfun/Step-3.7-Flash",inputModalities:["text","image"],provider:Xt,spec:un,label:"Step 3.7 Flash",name:"Step 3.7 Flash",description:"multimodal sparse-MoE reasoning",reasoning:!0,contextWindow:256e3},STEP_3_5_FLASH:{id:"stepfun/Step-3.5-Flash",inputModalities:["text"],provider:Xt,spec:un,label:"Step 3.5 Flash",name:"Step 3.5 Flash",description:"fast sparse-MoE agentic reasoning",reasoning:!0,contextWindow:1e6},GEMINI_3_5_FLASH:{id:"google/gemini-3.5-flash",inputModalities:["text","image"],provider:Xt,spec:un,label:"Gemini 3.5 Flash",name:"Gemini 3.5 Flash",description:"Pro-level coding proficiency, parallel agentic execution",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_1_FLASH_LITE:{id:"google/gemini-3.1-flash-lite",inputModalities:["text","image"],provider:Xt,spec:un,label:"Gemini 3.1 Flash Lite",name:"Gemini 3.1 Flash Lite",description:"high-volume workhorse model with implicit caching",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},NEMOTRON_3_ULTRA:{id:"nvidia/nemotron-3-ultra-550b-a55b",inputModalities:["text"],provider:Xt,spec:un,label:"Nemotron 3 Ultra",name:"Nemotron 3 Ultra",description:"open reasoning model for long-horizon autonomous agents",reasoning:!0,contextWindow:1e6}}).SONNET_4_6.id,pn.FABLE_5.id,pn.OPUS_4_8.id,pn.OPUS_4_7.id,pn.HAIKU_4_5.id,gn=[{canonicalId:"zai-org/GLM-5",providers:{[Qt.VERCEL_AI_GATEWAY]:"zai/glm-5",[Qt.BASETEN]:"zai-org/GLM-5"}},{canonicalId:"zai-org/GLM-5.2",providers:{[Qt.VERCEL_AI_GATEWAY]:"zai/glm-5.2"}},{canonicalId:"zai-org/GLM-5.1",providers:{[Qt.VERCEL_AI_GATEWAY]:"zai/glm-5.1"}},{canonicalId:"moonshotai/Kimi-K2.5",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.5",[Qt.BASETEN]:"moonshotai/Kimi-K2.5",[Qt.CLOUDFLARE_AI_GATEWAY]:"workers-ai/@cf/moonshotai/kimi-k2.5"}},{canonicalId:"moonshotai/Kimi-K2.6",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.6",[Qt.BASETEN]:"moonshotai/Kimi-K2.6",[Qt.CLOUDFLARE_AI_GATEWAY]:"workers-ai/@cf/moonshotai/kimi-k2.6"}},{canonicalId:"moonshotai/Kimi-K2.7-Code",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.7-code"}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.7-code-highspeed"}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m2.5",[Qt.BASETEN]:"MiniMaxAI/MiniMax-M2.5"}},{canonicalId:"deepseek/deepseek-v4-pro",providers:{[Qt.VERCEL_AI_GATEWAY]:"deepseek/deepseek-v4-pro"}},{canonicalId:"deepseek/deepseek-v4-flash",providers:{[Qt.VERCEL_AI_GATEWAY]:"deepseek/deepseek-v4-flash"}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen-3.6-max-preview"}},{canonicalId:"Qwen/Qwen3.6-Plus",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen3.6-plus"}},{canonicalId:"Qwen/Qwen3.7-Max",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen3.7-max"}},{canonicalId:"Qwen/Qwen3.7-Plus",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen3.7-plus"}},{canonicalId:"MiniMaxAI/MiniMax-M3",providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m3"}},{canonicalId:mn,providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m3"}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m2.7"}},{canonicalId:"stepfun/Step-3.7-Flash",providers:{[Qt.VERCEL_AI_GATEWAY]:"stepfun/step-3.7-flash"}},{canonicalId:"stepfun/Step-3.5-Flash",providers:{[Qt.OPENROUTER]:"stepfun/step-3.5-flash"}},{canonicalId:"xiaomi/mimo-v2.5-pro",providers:{[Qt.VERCEL_AI_GATEWAY]:"xiaomi/mimo-v2.5-pro"}},{canonicalId:"xiaomi/mimo-v2.5",providers:{[Qt.VERCEL_AI_GATEWAY]:"xiaomi/mimo-v2.5"}},{canonicalId:"google/gemini-3.5-flash",providers:{[Qt.VERCEL_AI_GATEWAY]:"google/gemini-3.5-flash"}},{canonicalId:"google/gemini-3.1-flash-lite",providers:{[Qt.VERCEL_AI_GATEWAY]:"google/gemini-3.1-flash-lite"}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",providers:{[Qt.VERCEL_AI_GATEWAY]:"nvidia/nemotron-3-ultra-550b-a55b"}}],hn={"claude-sonnet-4-20250514":pn.SONNET_4_6.id,"claude-sonnet-4-5-20250929":pn.SONNET_4_6.id,"claude-opus-4-5-20251101":pn.OPUS_4_7.id,"claude-opus-4-6":pn.OPUS_4_7.id,"claude-haiku-4-5":pn.HAIKU_4_5.id},fn=pn.DEEPSEEK_V4_FLASH.id,yn={[Qt.ANTHROPIC]:"Anthropic",[Qt.OPENAI]:"OpenAI",[Qt.BASETEN]:"Open Source",[Qt.VERCEL_AI_GATEWAY]:"Open Source"},wn=["Open Source","Anthropic","OpenAI","Google"],Sn={"command-code":{id:"command-code",label:"Command Code",shortLabel:"cmd",description:"recommended",supportedModelProviders:[Qt.ANTHROPIC,Qt.OPENAI,Qt.BASETEN,Qt.VERCEL_AI_GATEWAY],requiresAuth:!1,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},anthropic:{id:"anthropic",label:"Anthropic",shortLabel:"anth",description:"Claude Pro/Max",supportedModelProviders:[Qt.ANTHROPIC],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!1,showProviderLabelInSelector:!1},"github-copilot":{id:"github-copilot",label:"GitHub Copilot",shortLabel:"copilot",description:"Copilot subscription",supportedModelProviders:[Qt.ANTHROPIC,Qt.OPENAI],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!1,showProviderLabelInSelector:!0},codex:{id:"codex",label:"ChatGPT (Codex)",shortLabel:"codex",description:"ChatGPT Pro/Plus subscription",supportedModelProviders:[Qt.OPENAI],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!1,showProviderLabelInSelector:!1}},__name(buildModelGroups,"buildModelGroups"),bn=buildModelGroups("co"),En=buildModelGroups("normal"),new Set(["cc2@www3.in","cc3@www3.in","cc4@www3.in","cc5@www3.in","cc6@www3.in","cc7@www3.in","cc8@www3.in","cc9@www3.in","cc10@www3.in"].map(e=>e.toLowerCase())),vn=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],Cn={TIER_1_THRESHOLD:.5,TIER_2_THRESHOLD:.8,TIER_3_THRESHOLD:.9,TIER_1_KEEP_COUNT:20,TIER_2_KEEP_COUNT:10,KEEP_RECENT_TOKENS:3e4}}}),xn=__esm({"src/utils/env.ts"(){Bt(),Tn=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv")}});function getAuthDir(){return t.join(S.homedir(),".commandcode")}function getAuthFile(e){const n=e??Tn(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??Tn(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var An,Pn,In,Mn,Rn,Nn,Ln,$n,Dn,On,Fn,jn,Un=__esm({"src/utils/auth/auth-paths.ts"(){Bt(),_n(),xn(),__name(getAuthDir,"getAuthDir"),__name(getAuthFile,"getAuthFile"),__name(getConfigFile,"getConfigFile")}});function isWordLeftSequence(e){return!!An.has(e)||!!On.test(e)}function isWordRightSequence(e){return!!Pn.has(e)||!!Fn.test(e)}function isHomeSequence(e){return In.has(e)}function isEndSequence(e){return Mn.has(e)}function isForwardDeleteSequence(e){return Rn.has(e)}function isDeleteWordSequence(e){return Nn.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_U}function isAltP(e){return Dn.has(e)}function isCtrlKey({inputChar:e,key:t,letter:n,ctrlCode:r}){return!(!t.ctrl||e.toLowerCase()!==n.toLowerCase())||void 0!==r&&e.charCodeAt(0)===r}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)||jn.includes(t))}var Bn,qn,zn,Hn,Wn,Gn,Vn,Kn,Qn,Yn=__esm({"src/utils/keyboard-sequences.ts"(){Bt(),An=new Set(["","b","","",""]),Pn=new Set(["","f","","",""]),In=new Set(["","[1~","[7~","OH"]),Mn=new Set(["","[4~","[8~","OF"]),Rn=new Set(["[3~"]),Nn=new Set(["",""]),Ln={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},$n={ALT_P:112,ALT_P_NO_META:960},Dn=new Set([String.fromCharCode(27,$n.ALT_P),String.fromCharCode($n.ALT_P_NO_META),""]),On=/^\x1b\[1;[359]D$/,Fn=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey"),jn=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],__name(isNewlineShortcutKey,"isNewlineShortcutKey")}}),Jn=__esm({"src/auth/index.ts"(){Bt(),_n(),xn(),(e=>{e.OAuth=f.object({type:f.literal("oauth"),refresh:f.string(),access:f.string(),expires:f.number(),accountId:f.string().optional()}),e.ApiKey=f.object({type:f.literal("api"),key:f.string()}),e.Info=f.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(S.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=Tn(),r="local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json";return t.join(n(),r)},"getAuthFile");async function get(e){try{const t=await k.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await k.mkdir(o,{recursive:!0});let i={};try{const e=await k.readFile(s,"utf-8");i=JSON.parse(e)}catch{}i[e]=t,await k.writeFile(s,JSON.stringify(i,null,2)),await k.chmod(s,384)}async function remove(e){const t=r();try{const n=await k.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await k.unlink(t):(await k.writeFile(t,JSON.stringify(r,null,2)),await k.chmod(t,384))}catch{}}async function list2(){try{const e=await k.readFile(r(),"utf-8");return JSON.parse(e)}catch{return{}}}e.get=get,__name(get,"get"),e.set=set,__name(set,"set"),e.remove=remove,__name(remove,"remove"),e.list=list2,__name(list2,"list")})(Bn||(Bn={}))}}),Xn=__esm({"src/utils/constants.ts"(){Bt(),_n(),qn="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/billing",zn="OAuth authentication required. Please use /provider command\nSelect your provider and complete the OAuth setup.",Hn=">"}}),Zn=__esm({"src/auth/anthropic.ts"(){Bt(),Jn(),Xn(),Bs(),(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 exchangeCodeForTokens2(e,o,s){const i=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(!i.ok){const e=await i.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:Ls.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const a=await i.json();await Bn.set("anthropic",{type:"oauth",refresh:a.refresh_token,access:a.access_token,expires:Date.now()+1e3*a.expires_in})}async function refreshAccessToken2(){const e=await Bn.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 trackError({error:sanitizeErrorForTelemetry({error:new Error("OAuth token refresh failed"),label:"token_refresh_failed"}),context:{component:Ls.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}});const o=await r.json();return await Bn.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 trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:Ls.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}})}}}async function getValidAccessToken2(){const e=await Bn.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken2():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens2,__name(exchangeCodeForTokens2,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken")})(Wn||(Wn={}))}});function getIcon(e){if(Kn[e])return Kn[e];const t=e.split(":")[0];return Kn[t]?Kn[t]:Kn.default}function formatTime(e){return`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`}function parseMessage(e){const t=e.match(/^\[([^\]]+)\]\s*(.*)/);return t?{category:t[1],text:t[2]}:{category:"",text:e}}function showStartup(){if(!Qn){Qn=!0;try{$.mkdirSync(Gn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${Vn}\n════════════════════════════════════════════════════════════════\n\n`;$.appendFileSync(Vn,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${Kn.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",$.appendFileSync(Vn,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`;$.appendFileSync(Vn,t,"utf-8")}catch{}}}var er,tr,nr,rr,sr,ir=__esm({"src/utils/dlog.ts"(){Bt(),Gn=e.join(w.homedir(),".commandcode","logs"),Vn=e.join(Gn,"command.log"),Kn={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",MCP:"&",default:"-"},__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage"),Qn=!1,__name(showStartup,"showStartup"),"true"===process.env.DEBUG&&showStartup(),__name(dlog,"dlog"),__name(dlogSection,"dlogSection")}}),ar=__esm({"src/auth/codex.ts"(){Bt(),Jn(),Xn(),Bs(),ir(),(e=>{const t="app_EMoamEEZ73f0CkXaXp7hrann",n="https://auth.openai.com",r="openid profile email offline_access",o="http://localhost:1455/auth/callback";function base64UrlEncode(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function generateRandomString2(e){const t=R.randomBytes(e);let n="";for(let r=0;r<e;r++)n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[t[r]%66];return n}function generatePKCE2(){const e=generateRandomString2(64);return{verifier:e,challenge:base64UrlEncode(R.createHash("sha256").update(e).digest())}}function buildAuthorizeUrl(e,s){const i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:r,code_challenge:e.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:s,originator:"codex_cli_rs"});return`${n}/oauth/authorize?${i.toString()}`}function parseJwtClaims(e){const t=e.split(".");if(3===t.length)try{return JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"))}catch{return}}function extractAccountId(e){const t=[e.id_token,e.access_token].filter(Boolean);for(const e of t){const t=parseJwtClaims(e);if(!t)continue;const n=t.chatgpt_account_id||t["https://api.openai.com/auth"]?.chatgpt_account_id||t.organizations?.[0]?.id;if(n)return n}}async function exchangeCodeForTokens2(e,r,s){const i=await fetch(`${n}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:o,client_id:t,code_verifier:r.verifier}).toString(),signal:s});if(!i.ok){const e=await i.text();throw new Error(`Codex token exchange failed: ${i.status} ${e}`)}return i.json()}async function refreshTokens(e){const o=await fetch(`${n}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t,scope:r}).toString()});if(!o.ok){const e=await o.text();throw new Error(`Codex token refresh failed: ${o.status} ${e}`)}return o.json()}function waitForCallback(e){const{state:t,signal:n}=e;return new Promise((e,r)=>{let o,s,i=!1;const a=__name(()=>{if(s&&clearTimeout(s),o){if(o.listening)try{o.close(()=>{})}catch{}o=void 0}n?.removeEventListener("abort",u)},"cleanup"),l=__name((t,n)=>{i||(i=!0,a(),t?r(t):e(n))},"finish"),u=__name(()=>{l(new Error("Authentication cancelled"))},"onAbort");n?.aborted?r(new Error("Authentication cancelled")):(n?.addEventListener("abort",u,{once:!0}),o=K(__name((e,n)=>{try{const r=new URL(e.url||"/","http://localhost:1455");if("/auth/callback"!==r.pathname)return n.writeHead(404),void n.end("Not found");const o=r.searchParams.get("code"),s=r.searchParams.get("state"),i=r.searchParams.get("error"),a=r.searchParams.get("error_description");if(i){const e=a||i;return n.writeHead(400,{"Content-Type":"text/html"}),n.end(renderErrorPage(e)),void l(new Error(`Codex OAuth error: ${e}`))}if(!o||!s)return n.writeHead(400,{"Content-Type":"text/html"}),n.end(renderErrorPage("Missing code or state")),void l(new Error("Codex OAuth: missing code or state"));if(s!==t)return n.writeHead(400,{"Content-Type":"text/html"}),n.end(renderErrorPage("State mismatch — possible CSRF attempt")),void l(new Error("Codex OAuth: state mismatch"));n.writeHead(200,{"Content-Type":"text/html"}),n.end("<!doctype html>\n<html>\n <head><title>Command Code — Codex Authorization Successful</title>\n <style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0f0f0f;color:#eee}h1{color:#7ee787}</style>\n </head>\n <body><div><h1>Authorization successful</h1><p>You can close this window and return to Command Code.</p></div>\n <script>setTimeout(()=>window.close(),2000)<\/script></body>\n</html>"),l(null,o)}catch(e){n.writeHead(500),n.end("Internal error"),l(e instanceof Error?e:new Error(String(e)))}},"handler")),o.on("error",e=>l(e)),o.listen(1455,"127.0.0.1",()=>{s=setTimeout(()=>{l(new Error("Codex OAuth timed out waiting for browser callback"))},3e5)}))})}function renderSuccessPage(){return"<!doctype html>\n<html>\n <head><title>Command Code — Codex Authorization Successful</title>\n <style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0f0f0f;color:#eee}h1{color:#7ee787}</style>\n </head>\n <body><div><h1>Authorization successful</h1><p>You can close this window and return to Command Code.</p></div>\n <script>setTimeout(()=>window.close(),2000)<\/script></body>\n</html>"}function renderErrorPage(e){return`<!doctype html>\n<html>\n <head><title>Command Code — Codex Authorization Failed</title>\n <style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0f0f0f;color:#eee}h1{color:#ff7b72}</style>\n </head>\n <body><div><h1>Authorization failed</h1><p>${e.replace(/[&<>]/g,e=>"&"===e?"&amp;":"<"===e?"&lt;":"&gt;")}</p></div></body>\n</html>`}async function refreshAccessToken2(){const e=await Bn.get("codex");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return e.access;dlog("[Auth] codex: refreshing access token");try{const t=await refreshTokens(e.refresh),n=extractAccountId(t)??e.accountId;return await Bn.set("codex",{type:"oauth",refresh:t.refresh_token||e.refresh,access:t.access_token,expires:Date.now()+1e3*(t.expires_in??3600),...n?{accountId:n}:{}}),t.access_token}catch(e){return void trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"codex_token_refresh_exception"}),context:{component:Ls.CODEX_OAUTH,heading:"Codex token refresh exception"}})}}}async function getValidAccessToken2(){const e=await Bn.get("codex");if(e)return"api"===e.type?e.key:"oauth"===e.type?refreshAccessToken2():void 0}async function getAccountId(){const e=await Bn.get("codex");if(e&&"oauth"===e.type)return e.accountId}async function login(e){const{onAuth:t,onProgress:n,signal:r}=e;dlog("[Auth] codex: starting browser oauth flow");const o=generatePKCE2(),s=base64UrlEncode(R.randomBytes(32)),i=buildAuthorizeUrl(o,s),a=waitForCallback({state:s,signal:r});let l;t({authorizeUrl:i}),n?.("Waiting for authorization in browser...");try{l=await a}catch(e){const t=e instanceof Error?e:new Error(String(e));throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"codex_oauth_callback_failed"}),context:{component:Ls.CODEX_OAUTH,heading:"Codex oauth callback failed"}}),t}if(r?.aborted)throw new Error("Authentication cancelled");n?.("Exchanging authorization code...");const u=await exchangeCodeForTokens2(l,o,r);if(r?.aborted)throw new Error("Authentication cancelled");if(!u.refresh_token)throw new Error("Codex OAuth: issuer did not return a refresh_token");const d=extractAccountId(u);dlog("[Auth] codex: login success",{hasAccountId:!!d}),await Bn.set("codex",{type:"oauth",refresh:u.refresh_token,access:u.access_token,expires:Date.now()+1e3*(u.expires_in??3600),...d?{accountId:d}:{}})}__name(base64UrlEncode,"base64UrlEncode"),__name(generateRandomString2,"generateRandomString"),__name(generatePKCE2,"generatePKCE"),__name(buildAuthorizeUrl,"buildAuthorizeUrl"),e.parseJwtClaims=parseJwtClaims,__name(parseJwtClaims,"parseJwtClaims"),e.extractAccountId=extractAccountId,__name(extractAccountId,"extractAccountId"),__name(exchangeCodeForTokens2,"exchangeCodeForTokens"),__name(refreshTokens,"refreshTokens"),__name(waitForCallback,"waitForCallback"),__name(renderSuccessPage,"renderSuccessPage"),__name(renderErrorPage,"renderErrorPage"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken"),e.getAccountId=getAccountId,__name(getAccountId,"getAccountId"),e.login=login,__name(login,"login")})(er||(er={}))}}),lr=__esm({"src/auth/copilot.ts"(){Bt(),Jn(),Xn(),_n(),Bs(),ir(),(e=>{const t=atob("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),n=["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"];async function startDeviceFlow(e){const n=e?.domain||"github.com",r=`https://${n}/login/device/code`;dlog("[Auth] startDeviceFlow",{domain:n,url:r});const o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,scope:"read:user"})});if(!o.ok){const e=await o.text(),t=new Error(`Device code request failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"device_flow_start_failed"}),context:{component:Ls.COPILOT_OAUTH,heading:"Device code flow start failed"}}),t}const s=await o.json();return dlog("[Auth] startDeviceFlow success",{userCode:s.user_code,interval:s.interval,expiresIn:s.expires_in}),s}async function pollForGitHubAccessToken(e){const{deviceCode:n,interval:r,expiresIn:o,signal:s}=e,i=e.domain||"github.com",a=`https://${i}/login/oauth/access_token`,l=Date.now()+1e3*o;let u=1e3*r;for(dlog("[Auth] pollForGitHubAccessToken started",{domain:i,pollInterval:u,deadline:new Date(l).toISOString()});Date.now()<l;){if(s?.aborted)throw new Error("Authentication cancelled");if(await new Promise((e,t)=>{if(!s)return void setTimeout(e,u);const n=__name(()=>{clearTimeout(r),t(new Error("Authentication cancelled"))},"onAbort"),r=setTimeout(()=>{s.removeEventListener("abort",n),e()},u);s.addEventListener("abort",n,{once:!0})}),s?.aborted)throw new Error("Authentication cancelled");const e=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,device_code:n,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})}),r=await e.json();if("error"in r){if(dlog("[Auth] poll response error",r.error),"authorization_pending"===r.error)continue;if("slow_down"===r.error){u+=5e3,dlog("[Auth] poll slow_down, new interval",u);continue}if("expired_token"===r.error)throw new Error("Device code expired. Please try again.");if("access_denied"===r.error)throw new Error("Authorization was denied. Please try again.");throw new Error(`GitHub OAuth error: ${r.error}`)}if("access_token"in r)return dlog("[Auth] pollForGitHubAccessToken success, got access_token"),r}throw new Error("Device code expired. Please try again.")}async function refreshCopilotToken(e){const{refreshToken:t,enterpriseDomain:n}=e;dlog("[Auth] refreshCopilotToken called",{hasRefreshToken:!!t,enterpriseDomain:n});let r="https://api.github.com/copilot_internal/v2/token";n&&(r=`https://${n}/api/v3/copilot_internal/v2/token`);const o=await fetch(r,{method:"GET",headers:{Authorization:`token ${t}`,Accept:"application/json",...Yt}});if(!o.ok){const e=await o.text(),t=new Error(`Copilot token refresh failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"copilot_token_refresh_failed"}),context:{component:Ls.COPILOT_OAUTH,heading:"Copilot token refresh failed"}}),t}const s=await o.json(),i=1e3*s.expires_at-3e5;return dlog("[Auth] refreshCopilotToken success",{expiresAt:new Date(i).toISOString(),refreshIn:s.refresh_in}),{token:s.token,expires:i}}async function refreshAccessToken2(){const e=await Bn.get("github-copilot");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return dlog("[Auth] refreshAccessToken: token still valid",{expires:new Date(e.expires).toISOString()}),e.access;dlog("[Auth] refreshAccessToken: token expired, refreshing...");try{const t=await refreshCopilotToken({refreshToken:e.refresh});return await Bn.set("github-copilot",{type:"oauth",refresh:e.refresh,access:t.token,expires:t.expires}),t.token}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"copilot_token_refresh_exception"}),context:{component:Ls.COPILOT_OAUTH,heading:"Copilot token refresh exception"}}),void dlog("[Auth] refreshAccessToken: refresh failed, keeping auth for retry")}}else dlog("[Auth] refreshAccessToken: no copilot oauth auth found")}async function getValidAccessToken2(){dlog("[Auth] getValidAccessToken called for copilot");const e=await Bn.get("github-copilot");if(e){if(dlog("[Auth] getValidAccessToken: found stored auth",{type:e.type}),"api"===e.type)return e.key;if("oauth"===e.type)return await refreshAccessToken2()}dlog("[Auth] getValidAccessToken: no stored auth, checking env vars");for(const e of n){const t=process.env[e];if(t)try{const e=await refreshCopilotToken({refreshToken:t});return await Bn.set("github-copilot",{type:"oauth",refresh:t,access:e.token,expires:e.expires}),e.token}catch{continue}}}async function login(e){const{onAuth:t,onProgress:n,signal:r}=e;dlog("[Auth] login: starting copilot device code flow"),n?.("Starting device code flow...");const o=await startDeviceFlow();t({userCode:o.user_code,verificationUri:o.verification_uri}),n?.("Waiting for authorization...");const s=await pollForGitHubAccessToken({deviceCode:o.device_code,interval:o.interval,expiresIn:o.expires_in,signal:r});n?.("Getting Copilot access...");const i=await refreshCopilotToken({refreshToken:s.access_token});dlog("[Auth] login: storing copilot tokens"),await Bn.set("github-copilot",{type:"oauth",refresh:s.access_token,access:i.token,expires:i.expires}),dlog("[Auth] login: copilot login complete")}e.startDeviceFlow=startDeviceFlow,__name(startDeviceFlow,"startDeviceFlow"),e.pollForGitHubAccessToken=pollForGitHubAccessToken,__name(pollForGitHubAccessToken,"pollForGitHubAccessToken"),e.refreshCopilotToken=refreshCopilotToken,__name(refreshCopilotToken,"refreshCopilotToken"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken"),e.login=login,__name(login,"login")})(tr||(tr={}))}});function startEarlyInputCapture(){nr||(nr=!0,rr=[],sr=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&rr.push(t)},"earlyInputHandler"),process.stdin.on("data",sr))}function stopEarlyInputCapture(){nr&&sr&&(process.stdin.off("data",sr),sr=null,nr=!1)}function consumeBufferedInput(){const e=rr.join("");return rr=[],e}function hasBufferedInput(){return rr.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}var cr,ur=__esm({"src/utils/early-input-buffer.ts"(){Bt(),nr=!1,rr=[],sr=null,__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip")}});function isWordBoundary(e){return!e||0===e.length||cr.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),i=o-s;return s+Math.min(r,i)}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,i=findLineEnd(e,s)-s;return s+Math.min(o,i)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}var dr,mr,pr,gr=__esm({"src/utils/text-navigation.ts"(){Bt(),cr=/\s|[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/,__name(isWordBoundary,"isWordBoundary"),__name(findPreviousWordBoundary,"findPreviousWordBoundary"),__name(findNextWordBoundary,"findNextWordBoundary"),__name(deleteWordBackwards,"deleteWordBackwards"),__name(clampCursor,"clampCursor"),__name(findLineStart,"findLineStart"),__name(findLineEnd,"findLineEnd"),__name(moveCursorUp,"moveCursorUp"),__name(moveCursorDown,"moveCursorDown"),__name(insertTextAt,"insertTextAt"),__name(deleteCharBefore,"deleteCharBefore"),__name(deleteCharAt,"deleteCharAt")}});function stripBracketedPaste(e){return e.includes(dr)||e.includes(mr)?e.replaceAll(dr,"").replaceAll(mr,""):null}function processBracketedPasteInput({input:e,value:t,cursor:n}){const r=stripBracketedPaste(e);if(null===r)return{value:t,cursor:n,handled:!1};if(0===r.length)return{value:t,cursor:n,handled:!0};const o=insertTextAt(t,n,r);return{value:o.text,cursor:o.cursor,handled:!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 processBackspaceRun(e,t,n){let r=t,o=n;for(let t=0;t<e.length;t++){const e=deleteCharBefore(r,o);r=e.text,o=e.cursor}return{value:r,cursor:o,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-\x09\x0B\x0C\x0E-\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):pr.test(e)?processBackspaceRun(e,t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var hr=__esm({"src/tui/text/input-handlers.ts"(){Bt(),Yn(),gr(),dr="[200~",mr="[201~",__name(stripBracketedPaste,"stripBracketedPaste"),__name(processBracketedPasteInput,"processBracketedPasteInput"),__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"),pr=/^[\u007f\b]{2,}$/,__name(processBackspaceRun,"processBackspaceRun"),__name(processCursorLeft,"processCursorLeft"),__name(processCursorRight,"processCursorRight"),__name(processCursorUp,"processCursorUp"),__name(processCursorDown,"processCursorDown"),__name(processCharacterInput,"processCharacterInput"),__name(processRawInput,"processRawInput"),__name(isIgnoredKey,"isIgnoredKey"),__name(processInkInput,"processInkInput")}});function useCursorState({value:e,focus:t,showCursor:n,initialCursor:r}){const[o,s]=se(r??(e||"").length),i=ie(o),a=ie(e);ae(()=>{const r=a.current;if(a.current=e,e===r)return;if(!t)return;if(!n)return;const l=(e||"").length;o>l&&(s(l),i.current=l)},[e,t,n,o]);const l=ce(e=>{s(e),i.current=e},[]);return{cursor:o,setCursor:l,cursorRef:i}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o,stripBracketedPaste:s=!1}){const i=ie(!1);ae(()=>{if(!e)return;const a=process.stdin,l=__name(e=>{o(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>o(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(s){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current});if(e.handled)return void l(e)}const o=processRawInput(r,t.current,n.current);o.handled&&l(o)},"handleRawInput");if(a.on("data",u),!i.current&&hasBufferedInput()){i.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",u)}},[e,t,n,r,o,s])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:i}){Z((e,a)=>{if(o())return;if(isIgnoredKey(e,a))return;if(a.return)return void i?.(n.current);const l=processInkInput(e,a,n.current,r.current,t);if(!l.handled)return;const u=clampCursor(l.cursor,l.value.length);s(l.value,u)},{isActive:e})}function useSyncedRef(e){const t=ie(e);return t.current=e,t}function useEchoAwareValueRef(e){const t=ie(e),n=ie([]),r=n.current.indexOf(e);return-1!==r?n.current.splice(0,r+1):t.current!==e&&(t.current=e,n.current=[]),{valueRef:t,noteEmittedValue:ce(e=>{n.current.push(e),n.current.length>64&&n.current.shift()},[])}}var fr,yr,wr,Sr,br,Er,vr,Cr,kr,Tr,_r,xr,Ar,Pr,Ir,Mr,Rr,Nr,Lr,$r,Dr,Or,Fr,jr,Ur,Br,qr,zr,Hr=__esm({"src/tui/text/hooks.ts"(){Bt(),ur(),gr(),hr(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(useEchoAwareValueRef,"useEchoAwareValueRef")}});function isLightTheme(){return"light"===Sr}function applyTuiTheme(e){const t=wr[e];Sr=e,Object.assign(br,t.PALETTE),Er=t.ACCENT,Object.assign(vr,t.TASTE_COLORS),Cr=t.THINKING_COLOR,kr=t.QUEUED_COLOR,Object.assign(Tr,t.DIFF_COLORS),Object.assign(_r,t.TOOL_BADGE_COLORS),Object.assign(xr,t.STATUS_PILL_COLORS),Object.assign(Ar,t.AGENT_BADGE_COLORS),Object.assign(Pr,t.STATUS_COLORS),Ir=t.IDE_COLOR,Mr=t.MUTED,Object.assign(Rr,t.USER_MSG_COLORS),Nr=t.AI_ICON_COLOR,Lr=t.PLAN_MODE_COLOR,$r=t.ACCEPT_EDITS_COLOR,Object.assign(Dr,t.PR_COLORS),Or=t.RETRY_COLOR,Object.assign(Fr,t.MARKDOWN_COLORS),jr.splice(0,jr.length,...t.SHIMMER_COLORS),Ur=t.SHIMMER_DEFAULT,Object.assign(Br,t.LOGO_BANNER_COLORS),qr=br.DIM,zr=t.HIGHLIGHT_BAR_BG}var Wr,Gr,Vr=__esm({"src/tui/colors.ts"(){Bt(),fr={PALETTE:{CYAN:"#7AD4D6",GREEN:"#2EBD8E",GRAY:"#8A94A8",WHITE:"#E5E5E5",YELLOW:"#F5B731",RED:"#E84057",BLUE:"#5945B1",MAGENTA:"#F2608A",DIM:"#8A94A8",DIMMER:"#4C556A",DIMMEST:"#353D50"},ACCENT:"#E4CCFF",TASTE_COLORS:{BADGE_BG:"#08575B",BADGE_FG:"#f4f4f4",TEXT:"#02888E"},THINKING_COLOR:"#E4CCFF",QUEUED_COLOR:"#F5B731",DIFF_COLORS:{REMOVED_BG:"#5C0112",ADDED_BG:"#04473A",REMOVED_TEXT:"#E16B7A",ADDED_TEXT:"#4CC88E",REMOVED_HIGHLIGHT_BG:"#7D2233",ADDED_HIGHLIGHT_BG:"#2E6B4A",LINE_NUM:"#8A94A8"},TOOL_BADGE_COLORS:{BG:"#5945B1",FG:"#f4f4f4"},STATUS_PILL_COLORS:{BG:"#2D2B55",FG:"#E4CCFF"},AGENT_BADGE_COLORS:{BG:"#6943FF",FG:"#f4f4f4"},STATUS_COLORS:{SUCCESS:"#35AD68",ERROR:"#E84057",WARNING:"#F5B731",IN_PROGRESS:"#E4CCFF"},IDE_COLOR:"#B1BAF9",MUTED:"#8A94A8",USER_MSG_COLORS:{BG:"#2D2B55",POINTER:"#A599E9",FG:"#E5E5E5"},HIGHLIGHT_BAR_BG:"#2D2B55",AI_ICON_COLOR:"#A599E9",PLAN_MODE_COLOR:"#F5B731",ACCEPT_EDITS_COLOR:"#8367F4",PR_COLORS:{OPEN:"#F5B731",MERGED:"#A78BFA"},RETRY_COLOR:"#F49D2A",MARKDOWN_COLORS:{CODE:"#B1BAF9",HEADING:"#A599E9"},SHIMMER_COLORS:["#A599E9","#E4CCFF","#ABA5CE","#CCC7E1","#FFFFFF","#EADAFF","#ABA5CE","#E4CCFF","#A599E9"],SHIMMER_DEFAULT:"#6E61A3",LOGO_BANNER_COLORS:{TEXT:"#B1BAF9",BG:"#2B2758"}},yr={...fr,PALETTE:{...fr.PALETTE,CYAN:"#0F6B6D",GREEN:"#047857",GRAY:"#4B5563",WHITE:"#111827",YELLOW:"#92600A",RED:"#BE123C",MAGENTA:"#BE185D",DIM:"#4B5563"},ACCENT:"#5B21B6",TASTE_COLORS:{...fr.TASTE_COLORS,TEXT:"#0F6B6D"},THINKING_COLOR:"#5B21B6",QUEUED_COLOR:"#92600A",DIFF_COLORS:{...fr.DIFF_COLORS,REMOVED_BG:"#FEE2E2",ADDED_BG:"#CCFBF1",REMOVED_TEXT:"#BE123C",ADDED_TEXT:"#0F766E",REMOVED_HIGHLIGHT_BG:"#FECDD3",ADDED_HIGHLIGHT_BG:"#99F6E4"},STATUS_PILL_COLORS:{BG:"#4A4570",FG:"#E4CCFF"},STATUS_COLORS:{...fr.STATUS_COLORS,SUCCESS:"#047857",ERROR:"#BE123C",WARNING:"#92600A",IN_PROGRESS:"#5B21B6"},IDE_COLOR:"#4338CA",MUTED:"#4B5563",USER_MSG_COLORS:{...fr.USER_MSG_COLORS,BG:"#4A4570",POINTER:"#E4CCFF",FG:"#FFFFFF"},HIGHLIGHT_BAR_BG:"#DDD6FE",AI_ICON_COLOR:"#5B21B6",PLAN_MODE_COLOR:"#92600A",PR_COLORS:{OPEN:"#92600A",MERGED:"#6D28D9"},RETRY_COLOR:"#92600A",MARKDOWN_COLORS:{CODE:"#4338CA",HEADING:"#5B21B6"},SHIMMER_COLORS:["#D8B4FE","#E4CCFF","#F5F3FF","#FFFFFF","#F5F3FF","#E4CCFF","#D8B4FE","#F5F3FF","#FFFFFF"],SHIMMER_DEFAULT:"#E4CCFF",LOGO_BANNER_COLORS:{TEXT:"#B1BAF9",BG:"#2B2758"}},wr={dark:fr,light:yr},Sr="dark",br={...fr.PALETTE},Er=fr.ACCENT,vr={...fr.TASTE_COLORS},Cr=fr.THINKING_COLOR,kr=fr.QUEUED_COLOR,Tr={...fr.DIFF_COLORS},_r={...fr.TOOL_BADGE_COLORS},xr={...fr.STATUS_PILL_COLORS},Ar={...fr.AGENT_BADGE_COLORS},Pr={...fr.STATUS_COLORS},Ir=fr.IDE_COLOR,Mr=fr.MUTED,Rr={...fr.USER_MSG_COLORS},Nr=fr.AI_ICON_COLOR,Lr=fr.PLAN_MODE_COLOR,$r=fr.ACCEPT_EDITS_COLOR,Dr={...fr.PR_COLORS},Or=fr.RETRY_COLOR,Fr={...fr.MARKDOWN_COLORS},jr=[...fr.SHIMMER_COLORS],Ur=fr.SHIMMER_DEFAULT,Br={...fr.LOGO_BANNER_COLORS},qr=br.DIM,zr=fr.HIGHLIGHT_BAR_BG,__name(isLightTheme,"isLightTheme"),__name(applyTuiTheme,"applyTuiTheme")}});function stripBracketedPasteMarkers(e){return e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"").replace(/\x1B\[201~/g,"").replace(/\[201~/g,"")}function processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};const r=stripBracketedPasteMarkers(e);let o,s,i;if(t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){o=e.slice(0,t.index);const r=e.slice(t.index+t[0].length);if(n){const e=r.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(s=r.slice(0,e.index))}else s=r}}if(n){const t=e.match(/(\x1B)?\[201~/);t&&void 0!==t.index&&(i=e.slice(t.index+t[0].length))}return{isPasteStart:t,isPasteEnd:n,cleanedContent:r,textBeforePaste:o,pastedContent:s,textAfterPaste:i}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}function pastedLineCount(e){return(e.endsWith("\n")?e.slice(0,-1):e).split("\n").length}function pastedTextPreview(e){const t=e.trim().split(/\s+/).filter(Boolean);if(0===t.length)return"";const n=t.slice(0,3).join(" "),r=n.slice(0,Wr).trimEnd();return t.length>3||r.length<n.length?`${r}…`:r}function pastedTextToken(e){const t=pastedLineCount(e),n=pastedTextPreview(e);return n?`[${n} +${t}L]`:`[+${t}L]`}var Kr,Qr=__esm({"src/utils/bracketed-paste.ts"(){Bt(),__name(stripBracketedPasteMarkers,"stripBracketedPasteMarkers"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode"),__name(pastedLineCount,"pastedLineCount"),Wr=10,__name(pastedTextPreview,"pastedTextPreview"),__name(pastedTextToken,"pastedTextToken"),Gr=/\[[^\[\]]*\+\d+L\]/g}});function pastedTokenRanges(e){const t=[],n=new RegExp(Gr.source,"g");let r;for(;null!==(r=n.exec(e));)t.push([r.index,r.index+r[0].length]);return t}function renderPlainSpan(e,t,n,r,o){let s="";for(let i=t;i<n;i++){const t=e[i];s+=o&&i===r?"\n"===t?de.inverse(" ")+"\n":de.inverse(t):t}return s}function renderTokenSpan(e,t,n,r,o){return o&&r>=t&&r<n?Kr(e.slice(t,r))+de.inverse(e[r])+Kr(e.slice(r+1,n)):Kr(e.slice(t,n))}function renderPlaceholder(e,t){return t?0===e.length?de.inverse(" "):de.inverse(e[0])+Kr(e.slice(1)):Kr(e)}function renderValue(e,t,n){const r=pastedTokenRanges(e);if(!n&&0===r.length)return e;if(n&&0===e.length)return de.inverse(" ");let o="",s=0;for(const[i,a]of r)o+=renderPlainSpan(e,s,i,t,n),o+=renderTokenSpan(e,i,a,t,n),s=a;return o+=renderPlainSpan(e,s,e.length,t,n),n&&t===e.length&&(o+=de.inverse(" ")),o}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(me(e).length<=s)return e;const i=e.split(/(\s+)/);let a="",l=0,u=!0;for(const e of i){const t=me(e).length;if(l+t>(u?s:o)&&l>0&&(a+="\n"+r,l=n,u=!1),a+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=me(t).length,u=!0}}return a}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var Yr,Jr=__esm({"src/tui/text/render-utils.ts"(){Bt(),Vr(),Qr(),Kr=ue.hex(br.DIM),__name(pastedTokenRanges,"pastedTokenRanges"),__name(renderPlainSpan,"renderPlainSpan"),__name(renderTokenSpan,"renderTokenSpan"),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n,r){return(o,s)=>{e(s),o!==t.current&&(r(o),t.current=o,n.current(o))}}function createInkUpdateHandler(e,t,n,r){return(o,s)=>{e(s),o!==t.current&&(r(o),t.current=o,n.current(o))}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:i,onCursorChange:a,prefix:l="",prefixColor:u,singleLine:d=!1,maxWidth:m,stripBracketedPaste:g=!1,initialCursor:h}){const f=ie(!1),{valueRef:y,noteEmittedValue:w}=useEchoAwareValueRef(e),S=useSyncedRef(s),{cursor:E,setCursor:v,cursorRef:C}=useCursorState({value:e,focus:n,showCursor:o,initialCursor:h});re.useEffect(()=>{a?.(E)},[E,a]);const k=ce(createStdinUpdateHandler(v,y,S,w),[v,y,S,w]),T=ce(createInkUpdateHandler(v,y,S,w),[v,y,S,w]),_=ce(e=>{f.current=e},[]),x=ce(()=>f.current,[]);useRawStdinHandler({focus:n,valueRef:y,cursorRef:C,onUpdate:k,setHandled:_,stripBracketedPaste:g}),useInkInputHandler({focus:n,showCursor:o,valueRef:y,cursorRef:C,isHandledByStdin:x,onUpdate:T,onSubmit:i});const{stdout:A}=X(),P=A?.columns??80,I=getMaskedValue(e,r),M=u?Yr[u]:void 0,R=l?M?M(l):l:"",N=getDisplayValue(I,t,E,o,n),L=l?.length??0,$=R+N;if(d){const e=$.replace(/\n/g," ");return null!=m?re.createElement(Q,{width:m},re.createElement(Y,{wrap:"truncate"},e)):re.createElement(Y,{wrap:"truncate"},e)}const D=wrapWithIndent($,P,L);return re.createElement(Y,{wrap:"wrap"},D)}var Xr=__esm({"src/tui/text/text-input.tsx"(){Bt(),Hr(),Jr(),gr(),Yr={white:de.white,green:de.green,red:de.red,blue:de.blue,yellow:de.yellow,cyan:de.cyan,magenta:de.magenta,gray:de.gray,grey:de.gray},__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput")}});function bitmapHasAlpha(e){for(let t=3;t<e.length;t+=4)if((e[t]??255)<255)return!0;return!1}async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=await pe.fromBuffer(n),{width:s,height:i}=o.bitmap;if(!s||!i)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=bitmapHasAlpha(o.bitmap.data),l=1200;let u,d,m=s,g=i;(s>l||i>l)&&(s>i?(g=Math.round(i*l/s),m=l):(m=Math.round(s*l/i),g=l),o.resize({w:m,h:g})),t.includes("png")&&a?(u=await o.getBuffer(ge.png),d="image/png"):(u=await o.getBuffer(ge.jpeg,{quality:95}),d="image/jpeg");const h=u.length;return{compressedBase64:u.toString("base64"),mediaType:d,originalSizeBytes:r,compressedSizeBytes:h,compressionRatio:r/h}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var Zr,eo,to,no=__esm({"src/utils/image-compression.ts"(){Bt(),__name(bitmapHasAlpha,"bitmapHasAlpha"),__name(compressImageForSharing,"compressImageForSharing")}}),ro={};function isClipboardAvailable(){if(void 0!==Zr)return Zr;const e=process.platform;return Zr="darwin"===e||"win32"===e||"linux"===e&&isLinuxClipboardAvailable()}function isLinuxClipboardAvailable(){const e=process.env.DISPLAY;if(e){const t=e.match(/^:(\d+)/);return!t||D.existsSync(`/tmp/.X11-unix/X${t[1]}`)}return!1}function _resetClipboardAvailableCacheForTests(){Zr=void 0}async function detectDroppedImageFile(e){try{if(!e||0===e.trim().length)return null;let t=e.trim();if((t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),t=t.replace(/\\(.)/g,"$1"),t.includes("\n")||t.includes("\r"))return null;const n=l(t).toLowerCase(),r=eo[n];if(!r)return null;const o=a(t);if(!D.existsSync(o))return null;const s=D.readFileSync(o).toString("base64");if(!s||0===s.length)return null;if(s.length>32e6)return null;const i=await compressImageForSharing(s,r);return i?{data:i.compressedBase64,mediaType:i.mediaType}:to.has(n)?{data:s,mediaType:r}:null}catch(e){return null}}async function detectClipboardImage(){try{if(!isClipboardAvailable())return null;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{if(!isClipboardAvailable())return null;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}}__export(ro,{_resetClipboardAvailableCacheForTests:()=>_resetClipboardAvailableCacheForTests,detectClipboardImage:()=>detectClipboardImage,detectClipboardText:()=>detectClipboardText,detectDroppedImageFile:()=>detectDroppedImageFile,isClipboardAvailable:()=>isClipboardAvailable});var oo,so=__esm({"src/utils/clipboard-image.ts"(){Bt(),no(),__name(isClipboardAvailable,"isClipboardAvailable"),__name(isLinuxClipboardAvailable,"isLinuxClipboardAvailable"),__name(_resetClipboardAvailableCacheForTests,"_resetClipboardAvailableCacheForTests"),eo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/png",".tiff":"image/png"},to=new Set([".png",".jpg",".jpeg",".gif",".webp"]),__name(detectDroppedImageFile,"detectDroppedImageFile"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText")}});function isCliTheme(e){return"string"==typeof e&&oo.has(e)}var io,ao,lo,co=__esm({"src/utils/cli-theme.ts"(){Bt(),oo=new Set(["dark","light"]),__name(isCliTheme,"isCliTheme")}});function getSupportedEfforts(e){return findModelById(e)?.reasoningEfforts??null}function modelSupportsReasoningEffort(e){return null!==getSupportedEfforts(e)}function getContextLimit(e){const t=getCanonicalModelId(e);return findModelById(t)?.contextWindow??io}function findModelById(e){return Object.values(pn).find(t=>t.id===e)}function getProviderFromModel(e){return findModelById(e)?.provider??Qt.ANTHROPIC}function getAllModelOptions(){return Object.values(pn)}function getModelGroupLabel(e){return e.vendorLabel??yn[e.provider]??e.provider}function groupModelsByDisplayOrder(e){const t=new Map;for(const n of e){const e=getModelGroupLabel(n),r=t.get(e)??[];r.push(n),t.set(e,r)}return[...wn.filter(e=>t.has(e)),...[...t.keys()].filter(e=>!wn.includes(e))].map(e=>({label:e,models:t.get(e)}))}function getModelGroupsInOrder(){return groupModelsByDisplayOrder(getAllModelOptions().filter(e=>!e.hidden))}function resolveKnownModelId(e){const t=getCanonicalModelId(e);return findModelById(t)?t:void 0}function modelSupportsVision(e){const t=findModelById(getCanonicalModelId(e));return!t?.inputModalities||t.inputModalities.includes("image")}function ossEntryMatches(e,t){return e.canonicalId.toLowerCase()===t||Object.values(e.providers).some(e=>"string"==typeof e&&e.toLowerCase()===t)}function tryResolveCanonical(e){const t=(hn[e.toLowerCase()]??e).toLowerCase(),n=Object.values(pn).find(e=>e.id.toLowerCase()===t);if(n)return n.id;const r=gn.find(e=>ossEntryMatches(e,t));return r?.canonicalId}function getCanonicalModelId(e){if(!e)return e;const t=e.startsWith(lo)?e.slice(lo.length):e,n=tryResolveCanonical(t);if(n)return n;const r=t.replace(ao,"");return r===t?t:tryResolveCanonical(r)??t}function getModelDisplayName(e){const t=getCanonicalModelId(e),n=Object.values(pn).find(e=>e.id===t);return n?.name??e}var uo,mo,po,ho,fo,yo,wo,So,bo=__esm({"../shared/src/utils/models.ts"(){Bt(),_n(),__name(getSupportedEfforts,"getSupportedEfforts"),__name(modelSupportsReasoningEffort,"modelSupportsReasoningEffort"),io=2e5,__name(getContextLimit,"getContextLimit"),__name(findModelById,"findModelById"),__name(getProviderFromModel,"getProviderFromModel"),__name(getAllModelOptions,"getAllModelOptions"),__name(getModelGroupLabel,"getModelGroupLabel"),__name(groupModelsByDisplayOrder,"groupModelsByDisplayOrder"),__name(getModelGroupsInOrder,"getModelGroupsInOrder"),__name(resolveKnownModelId,"resolveKnownModelId"),__name(modelSupportsVision,"modelSupportsVision"),ao=/[-@]\d{8}$/,lo="workers-ai/@cf/",__name(ossEntryMatches,"ossEntryMatches"),__name(tryResolveCanonical,"tryResolveCanonical"),__name(getCanonicalModelId,"getCanonicalModelId"),__name(getModelDisplayName,"getModelDisplayName")}});async function loadUserConfig(){try{const e=getConfigFile();return parseJSON(await C.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();$.writeFileSync(t,JSON.stringify(e,null,2)),$.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=t.model,r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isOAuthEnforced(){if(null!==uo)return uo;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),uo=!1,!1;if(isInternalTeamFlagPresent()){dlog("[Auth] OAuth enabled via --co flag");const e=await loadUserConfig(),t=await resolveOAuthProvider({currentProvider:e.provider});return dlog("[Auth] --co resolved provider",t),await updateUserConfig({provider:t,forceOAuth:!0}),uo=!0,!0}const e=await loadUserConfig();return(uo=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),uo}async function resolveOAuthProvider(e){const{currentProvider:t}=e;if(t&&ho.includes(t))return t;const n=await Bn.get("github-copilot"),r=await Bn.get("codex"),o=(await Bn.get("anthropic"),n?"github-copilot":r?"codex":"anthropic");return dlog("[Auth] resolveOAuthProvider fallback",{from:t,to:o}),o}function validateOAuthToken(e){const{token:t,provider:n}=e;if(n&&ho.includes(n)&&!t)throw new Error(zn)}async function getOAuthCredentials(e){const{provider:t}=e;return"anthropic"===t?{token:await Wn.getValidAccessToken(),oauthProvider:"anthropic"}:"github-copilot"===t?{token:await tr.getValidAccessToken(),oauthProvider:"github-copilot"}:"codex"===t?{token:await er.getValidAccessToken(),oauthProvider:"codex"}:{token:void 0,oauthProvider:void 0}}function readDiskDefaultModel(){if(null!==fo)return fo;try{const e=getConfigFile(),t=parseJSON($.readFileSync(e,"utf-8"))||{};fo=t.model??fn}catch{fo=fn}return fo}async function getSelectedModel(){return yo||So||readDiskDefaultModel()}function setModelOverride(e){yo=e}function clearModelOverride(){yo=void 0}function setGoalMaxTurnsOverride(e){wo=e}function getGoalMaxTurnsOverride(){return wo}function setSessionModel(e){So=e}function hasRuntimeModelSelection(){return void 0!==yo||void 0!==So}function shouldAdoptResumedModel(e){const{inTuiResume:t}=e;return t||!hasRuntimeModelSelection()}function getConfiguredModel(){return yo||So||readDiskDefaultModel()}function setSelectedModel(e){setSessionModel(e.model)}async function persistDefaultModel(e){await updateUserConfig({model:e.model}),fo=e.model}function getReasoningEffort(e){try{const t=getConfigFile(),n=parseJSON($.readFileSync(t,"utf-8"))||{};return n.reasoningEffort?.[e]}catch{return}}async function setReasoningEffort(e){const{modelId:t,effort:n}=e,r={...(await loadUserConfig()).reasoningEffort??{}};if(void 0===n)return delete r[t],void await updateUserConfig({reasoningEffort:r});r[t]=n,await updateUserConfig({reasoningEffort:r})}function getCliTheme(){if(null!==po)return po;try{const e=getConfigFile(),t=parseJSON($.readFileSync(e,"utf-8"))||{};return po=isCliTheme(t.theme)?t.theme:"dark"}catch{return po="dark","dark"}}async function setCliTheme(e){const{theme:t}=e;await updateUserConfig({theme:t}),po=t}async function setThemeOnboarded(e){await updateUserConfig({themeOnboarded:e.themeOnboarded})}function isExperimentalEnabled(){return process.argv.includes("--experimental")}async function migrateDeprecatedModel(){try{const e=await loadUserConfig();if(!e.model)return;const t=hn[e.model];if(!t)return;dlog(`[Migration] Upgrading model ${e.model} → ${t}`),await saveUserConfig({...e,model:t}),fo=t}catch(e){dlog(`[Migration] Failed to migrate model: ${e}`)}}function getCompactMode(){if(null!==mo)return mo;try{const e=getConfigFile(),t=(parseJSON($.readFileSync(e,"utf-8"))||{}).compactMode;return mo="default"===t||"fast"===t?t:"default"}catch{return mo="default","default"}}async function setCompactMode(e){const{mode:t}=e;mo=t,await updateUserConfig({compactMode:t})}var Eo,vo,Co=__esm({"src/utils/user-config.ts"(){Bt(),_n(),Un(),Jn(),Zn(),ar(),lr(),Xn(),co(),ir(),Ro(),No(),bo(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),uo=null,mo=null,po=null,__name(isOAuthEnforced,"isOAuthEnforced"),ho=["anthropic","github-copilot","codex"],__name(resolveOAuthProvider,"resolveOAuthProvider"),__name(validateOAuthToken,"validateOAuthToken"),__name(getOAuthCredentials,"getOAuthCredentials"),fo=null,__name(readDiskDefaultModel,"readDiskDefaultModel"),__name(getSelectedModel,"getSelectedModel"),__name(setModelOverride,"setModelOverride"),__name(clearModelOverride,"clearModelOverride"),__name(setGoalMaxTurnsOverride,"setGoalMaxTurnsOverride"),__name(getGoalMaxTurnsOverride,"getGoalMaxTurnsOverride"),__name(setSessionModel,"setSessionModel"),__name(hasRuntimeModelSelection,"hasRuntimeModelSelection"),__name(shouldAdoptResumedModel,"shouldAdoptResumedModel"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel"),__name(persistDefaultModel,"persistDefaultModel"),__name(getReasoningEffort,"getReasoningEffort"),__name(setReasoningEffort,"setReasoningEffort"),__name(getCliTheme,"getCliTheme"),__name(setCliTheme,"setCliTheme"),__name(setThemeOnboarded,"setThemeOnboarded"),__name(isExperimentalEnabled,"isExperimentalEnabled"),__name(migrateDeprecatedModel,"migrateDeprecatedModel"),__name(getCompactMode,"getCompactMode"),__name(setCompactMode,"setCompactMode")}}),ko=__esm({"src/tui/terminal-link.tsx"(){Bt(),Vr(),Eo=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const o=`]8;;${e}${t}]8;;`,s=r??(n?br.DIM:void 0);return re.createElement(Y,{dimColor:n&&!!r,color:s},o)},"TerminalLink")}}),To=__esm({"src/tui/anthropic-auth.tsx"(){Bt(),Xr(),Zn(),Xn(),so(),Qr(),Co(),Vr(),ko(),vo=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=se(""),[s,i]=se(null),[a,l]=se(!1),[u,d]=se(null),[m,g]=se(!0),[h,f]=se(!1),[y,w]=se(!1);ae(()=>{const{url:e,verifier:t,state:n}=Wn.createAuthorizationUrl();i({url:e,verifier:t,state:n})},[]);const S=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||y){if(!y||t.isPasteEnd){if(y&&t.isPasteEnd){w(!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(w(!0),t.isPasteEnd){w(!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}},[y]);Z((e,n)=>{if(n.escape&&t(),m&&!h)if(n.return||"y"===e||"Y"===e){if(!s)return;he(s.url).then(()=>{f(!0),g(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),f(!0),g(!1)})}else"n"!==e&&"N"!==e||t()});const E=__name(async()=>{if(r.trim()&&s&&!a){l(!0),d(null);try{const t=r.split("#")[0].trim();await Wn.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),l(!1),n&&n(t)}}},"handleSubmit");return m&&!h?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"Anthropic Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Open the Anthropic auth page?",re.createElement(Y,{color:br.DIM}," (Y/n)")))):re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"Anthropic Authentication")),s&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Login: "),re.createElement(Eo,{url:s.url,text:"Open auth page ↗",color:br.CYAN})),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"After authorizing, copy the code and paste it below:")),u&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},"Error: ",u)),re.createElement(Q,null,re.createElement(Y,null,"Authorization code: "),re.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:S,onSubmit:E,placeholder:"Paste code here..."})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function createOSC8Link(e,t,n=!0){return`${n?"":""}]8;;${e}${t||e}]8;;${n?"":""}`}var _o,xo,Ao,Po=__esm({"src/utils/osc8-link.ts"(){Bt(),__name(createOSC8Link,"createOSC8Link")}}),Io=__esm({"src/tui/codex-auth.tsx"(){Bt(),ar(),Xn(),Co(),Po(),Vr(),_o=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=se("confirm"),[s,i]=se(""),[a,l]=se(null),[u,d]=se(""),m=ie(null),g=ce(async()=>{const t=new AbortController;m.current=t;try{await er.login({onAuth:__name(({authorizeUrl:e})=>{i(e),o("waiting"),he(e).catch(()=>{})},"onAuth"),onProgress:__name(e=>{d(e),e.startsWith("Exchanging")&&o("exchanging")},"onProgress"),signal:t.signal}),await updateUserConfig({provider:"codex"}),o("success"),e()}catch(e){if(t.signal.aborted)return;const r=e instanceof Error?e.message:"Authentication failed";l(r),o("error"),n?.(r)}},[e,n]);return ae(()=>()=>{m.current?.abort()},[]),Z((e,n)=>{if(n.escape)return m.current?.abort(),void t();if("confirm"===r){if(n.return||"y"===e||"Y"===e)return void g();"n"!==e&&"N"!==e||t()}}),"confirm"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"ChatGPT (Codex) Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"This will open your browser to sign in with ChatGPT.")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Continue?",re.createElement(Y,{color:br.DIM}," (Y/n)")))):"waiting"===r||"exchanging"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"ChatGPT (Codex) Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,createOSC8Link(s,"Open auth page ↗"))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},u||"Waiting for authorization...")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to cancel"))):"error"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"ChatGPT (Codex) Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},"Error: ",a)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to go back"))):null},"CodexAuth")}}),Mo=__esm({"src/tui/copilot-auth.tsx"(){Bt(),lr(),Xn(),Co(),Vr(),xo=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=se("confirm"),[s,i]=se(""),[a,l]=se(""),[u,d]=se(null),[m,g]=se(""),h=ie(null),f=ce(async()=>{const t=new AbortController;h.current=t;try{await tr.login({onAuth:__name(({userCode:e,verificationUri:t})=>{i(e),l(t),o("device-code"),he(t).catch(()=>{})},"onAuth"),onProgress:__name(e=>{g(e),"Waiting for authorization..."===e&&o("polling")},"onProgress"),signal:t.signal}),await updateUserConfig({provider:"github-copilot"}),o("success"),e()}catch(e){if(t.signal.aborted)return;const r=e instanceof Error?e.message:"Authentication failed";d(r),o("error"),n&&n(r)}},[e,n]);return ae(()=>()=>{h.current?.abort()},[]),Z((e,n)=>{if(n.escape)return h.current?.abort(),void t();if("confirm"===r){if(n.return||"y"===e||"Y"===e)return void f();"n"!==e&&"N"!==e||t()}}),"confirm"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"GitHub Copilot Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"This will open GitHub to authorize Copilot access.")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Continue?",re.createElement(Y,{color:br.DIM}," (Y/n)")))):"device-code"===r||"polling"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"GitHub Copilot Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Enter this code on GitHub:"," ",re.createElement(Y,{bold:!0,color:br.GREEN},s))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Open: ",a)),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"polling"===r?"Waiting for authorization...":m||"Starting...")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to cancel"))):"error"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"GitHub Copilot Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},"Error: ",u)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to go back"))):null},"CopilotAuth")}});function getProviderDisplayName(e){return e?Sn[e]?.label??e:"None"}function getProviderConfig(e){return Ao[e]}function isInternalTeamFlagPresent(){return process.argv.includes(zt)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(Ht)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON($.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(Ao).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var Ro=__esm({"src/utils/provider-config.ts"(){Bt(),_n(),Zn(),ar(),lr(),To(),Io(),Mo(),Un(),No(),(Ao=Object.fromEntries(Object.values(Sn).map(e=>[e.id,{id:e.id,displayName:e.label,description:e.description,requiresAuth:e.requiresAuth,hidden:!e.visibleInNormalMode}]))).anthropic&&(Ao.anthropic.authComponent=vo,Ao.anthropic.checkAuth=async()=>!!await Wn.getValidAccessToken()),Ao["github-copilot"]&&(Ao["github-copilot"].authComponent=xo,Ao["github-copilot"].checkAuth=async()=>!!await tr.getValidAccessToken()),Ao.codex&&(Ao.codex.authComponent=_o,Ao.codex.checkAuth=async()=>!!await er.getValidAccessToken()),__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalTeamFlagPresent,"isInternalTeamFlagPresent"),__name(isInternalTeamDisableFlagPresent,"isInternalTeamDisableFlagPresent"),__name(isInternalTeamFlagEnforced,"isInternalTeamFlagEnforced"),__name(getProviderOptions,"getProviderOptions")}});function isInternalTeamDisableOAuthFlagPresent(){return process.argv.includes(Ht)}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 k.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();if(isInternalTeamDisableOAuthFlagPresent())return await updateUserConfig({provider:Sn["command-code"].id,forceOAuth:!1}),Sn["command-code"].id;if(s||o){if(r)return await updateUserConfig({forceOAuth:!0}),r;const e=await resolveOAuthProvider({currentProvider:r});return await updateUserConfig({provider:e,forceOAuth:!0}),e}return r}catch{return null}}function getIsExpandToolShortcut(e,t){return isCtrlKey({inputChar:t,key:e,letter:"o",ctrlCode:15})}function formatTime2(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function formatTokens(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}var No=__esm({"src/utils/utils.ts"(){Bt(),_n(),Un(),Yn(),Ro(),Co(),__name(isInternalTeamDisableOAuthFlagPresent,"isInternalTeamDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut"),__name(formatTime2,"formatTime"),__name(formatTokens,"formatTokens")}});function isLocalDevelopmentBuild(){try{const e=process.argv[1];if(!e)return!1;if(e.includes("/usr/local/bin/dmd"))return!0;const t=D.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var Lo=__esm({"src/utils/is-local-dev.ts"(){Bt(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":Tn()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return At;case"local":return Pt;default:return xt}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON($.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var $o=__esm({"src/utils/telemetry/config.ts"(){Bt(),Un(),No(),xn(),Lo(),kn(),kn(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),Do={};function getPackageJson(){const e=import.meta.url,t=d(e);let s=r(t);const{root:i}=o(s);for(;;){const e=n(s,"package.json");if(O(e))return JSON.parse(j(e,"utf8"));if(s===i)throw new Error("Could not find package.json");s=r(s)}}__export(Do,{getPackageJson:()=>getPackageJson});var Oo,Fo,jo,Uo,Bo,qo,zo,Ho,Wo,Go=__esm({"src/utils/package.ts"(){Bt(),__name(getPackageJson,"getPackageJson")}});function parseRetryAfter(e){if(!e)return null;const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.min(1e3*t,Wo);const n=Date.parse(e);if(Number.isFinite(n)){const e=n-Date.now();if(e>0)return Math.min(e,Wo)}return null}function installOtlpRetryFetch(){const e=globalThis.fetch;if(!e||e.__commandcodeOtlpWrapped)return;const t=__name(async(t,n)=>{const r="string"==typeof t?t:t.url??"";if("string"!=typeof r||!r.includes(_t))return e(t,n);let o,s=0;for(;s<=Ho;){const r=await e(t,n);if(o=r,429!==r.status&&430!==r.status)return r;if(s===Ho)break;const i=parseRetryAfter(r.headers.get("retry-after")),a=Math.min(200*Math.pow(2,s),Wo),l=i??a;await new Promise(e=>setTimeout(e,l)),s++}return o},"wrapped");t.__commandcodeOtlpWrapped=!0,globalThis.fetch=t}function createAxiomExporter(){return installOtlpRetryFetch(),new Fo({url:_t,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":Tt}})}function createServiceResource(){const e=getPackageJson(),n=process.execPath,r=t.basename(n)||"unknown";return jo({[Uo]:It,[Bo]:e.version,"process.executable.name":r,"process.runtime.name":"node","process.runtime.version":process.version,"process.pid":process.pid})}function createTelemetrySDK(){const e=createAxiomExporter(),t=createServiceResource(),n="1"===process.env.COMMAND_CODE_TELEMETRY_SYNC?new zo(e):new qo(e,{maxQueueSize:Rt,maxExportBatchSize:Nt,scheduledDelayMillis:Lt,exportTimeoutMillis:$t});return new Oo({resource:t,spanProcessors:[n],autoDetectResources:!1})}var Vo=__esm({"src/utils/telemetry/sdk-factory.ts"(){Bt(),kn(),$o(),Go(),({NodeSDK:Oo}=fe),({OTLPTraceExporter:Fo}=ye),({resourceFromAttributes:jo}=we),({ATTR_SERVICE_NAME:Uo,ATTR_SERVICE_VERSION:Bo}=Se),({BatchSpanProcessor:qo,SimpleSpanProcessor:zo}=be),Ho=2,Wo=1500,__name(parseRetryAfter,"parseRetryAfter"),__name(installOtlpRetryFetch,"installOtlpRetryFetch"),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function resolveNearestAncestor(e){let n=t.dirname(e),r=t.basename(e);for(;n!==t.dirname(n);)try{return t.join(D.realpathSync(n),r)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code){r=t.join(t.basename(n),r),n=t.dirname(n);continue}return null}return null}function resolveSymlinks(e){try{return D.realpathSync(e)}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))return null}try{if(D.lstatSync(e).isSymbolicLink())return null}catch{}return resolveNearestAncestor(e)}function resolvePlansDir(e){try{return D.realpathSync(e)}catch{return e}}function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=S.homedir(),o=n.startsWith("~/")?t.join(r,n.slice(2)):n,s=resolveSymlinks(t.resolve(o));if(!s)return!1;const i=resolvePlansDir(t.join(r,".commandcode","plans"));return s.startsWith(i+t.sep)||s===i}var Ko,Qo,Yo,Jo=__esm({"src/utils/plan-path-validator.ts"(){Bt(),_n(),__name(resolveNearestAncestor,"resolveNearestAncestor"),__name(resolveSymlinks,"resolveSymlinks"),__name(resolvePlansDir,"resolvePlansDir"),__name(isPlanPath,"isPlanPath")}});function setCurrentPermissionMode(e){Yo=e}function normalizePathForComparison(e){const n=t.normalize(e);return"win32"===process.platform?n.toLowerCase():n}function areSamePath(e,t){return normalizePathForComparison(e)===normalizePathForComparison(t)}function getCanonicalPath(e){try{return D.realpathSync(e)}catch(n){const r=n.code;return"ENOENT"!==r&&console.error(`Warning: Could not resolve canonical path for "${e}" (${r}). Path comparison may be less reliable.`),t.normalize(e)}}function canonicalizeForLookup(e){try{let n=t.resolve(e);const r=[];for(;!D.existsSync(n);){const o=t.dirname(n);if(o===n)return t.normalize(e);r.unshift(t.basename(n)),n=o}return t.join(getCanonicalPath(n),...r)}catch{return t.normalize(e)}}function formatDirectoryForDisplay(e){const n=canonicalizeForLookup(t.normalize(e)),r=getCanonicalPath(process.cwd()),o=S.homedir();if(isPathInDirectory(n,r)){const e=t.relative(r,n);return e?`./${e}`:"."}if(o&&isPathInDirectory(n,o)){const e=t.relative(o,n);return e?`~/${e}`:"~"}return n}function isPathInDirectory(e,n){const r=normalizePathForComparison(e),o=normalizePathForComparison(n),s=o.endsWith(t.sep)?o:o+t.sep;return r===o||r.startsWith(s)}function findSensitiveDirectoryConflict(e){const n=[t.normalize(e),getCanonicalPath(e)];for(const e of Ko){const r=[t.normalize(e),getCanonicalPath(e)];for(const e of n)for(const t of r)if(isPathInDirectory(e,t)||isPathInDirectory(t,e))return t}return null}function resolveDirectoryPath(e){let n=e.trim();return n.startsWith("~")&&(n=t.join(S.homedir(),n.slice(1))),t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),t.normalize(n)}function createSkippedResult(e){const{inputPath:t,absolutePath:n,code:r}=e,o=formatDirectoryForDisplay(n);return{status:"skipped",inputPath:t,absolutePath:n,displayPath:o,code:r,message:"ALREADY_IN_WORKSPACE"===r?`${o} is already accessible from the current workspace`:`${o} is already added`}}function createErrorResult(e){const{inputPath:t,code:n,message:r}=e;return{status:"error",inputPath:t,code:n,message:r}}function addDirectory(e){const t=e.trim();if(!t)return createErrorResult({inputPath:e,code:"EMPTY_PATH",message:"Directory path cannot be empty"});const n=resolveDirectoryPath(e);let r,o;try{r=D.statSync(n)}catch(n){return"ENOENT"===n.code?createErrorResult({inputPath:e,code:"NOT_FOUND",message:`Directory does not exist: ${t}`}):createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}if(!r.isDirectory())return createErrorResult({inputPath:e,code:"NOT_A_DIRECTORY",message:`${formatDirectoryForDisplay(n)} is not a directory`});try{D.accessSync(n,D.constants.R_OK),o=getCanonicalPath(n)}catch{return createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}const s=findSensitiveDirectoryConflict(o);if(s)return createErrorResult({inputPath:e,code:"SENSITIVE_DIRECTORY",message:`Cannot add ${formatDirectoryForDisplay(o)} because it overlaps sensitive path ${formatDirectoryForDisplay(s)}`});const i=getCanonicalPath(process.cwd());return isPathInDirectory(o,i)?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_IN_WORKSPACE"}):Qo.some(e=>isPathInDirectory(o,e)||isPathInDirectory(e,o))?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_ADDED"}):(Qo.push(o),{status:"added",inputPath:e,absolutePath:o,displayPath:formatDirectoryForDisplay(o)})}function getAdditionalDirectories(){return[...Qo]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Qo.findIndex(e=>areSamePath(t,e));return-1!==n&&(Qo.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Qo.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return!("plan"!==Yo||!isPlanPath({filePath:t}))||(isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t))}function getWorkspaceDirectories(){return[t.resolve(process.cwd()),...getAdditionalDirectories()]}var Xo=__esm({"src/utils/additional-dirs.ts"(){Bt(),Jo(),Ko=new Set(["/etc","/root","/proc","/sys","/dev",t.join(S.homedir(),".ssh"),t.join(S.homedir(),".gnupg"),t.join(S.homedir(),".aws")]),Qo=[],Yo="standard",__name(setCurrentPermissionMode,"setCurrentPermissionMode"),__name(normalizePathForComparison,"normalizePathForComparison"),__name(areSamePath,"areSamePath"),__name(getCanonicalPath,"getCanonicalPath"),__name(canonicalizeForLookup,"canonicalizeForLookup"),__name(formatDirectoryForDisplay,"formatDirectoryForDisplay"),__name(isPathInDirectory,"isPathInDirectory"),__name(findSensitiveDirectoryConflict,"findSensitiveDirectoryConflict"),__name(resolveDirectoryPath,"resolveDirectoryPath"),__name(createSkippedResult,"createSkippedResult"),__name(createErrorResult,"createErrorResult"),__name(addDirectory,"addDirectory"),__name(getAdditionalDirectories,"getAdditionalDirectories"),__name(removeAdditionalDirectory,"removeAdditionalDirectory"),__name(isPathInAdditionalDirs,"isPathInAdditionalDirs"),__name(isPathInWorkspace,"isPathInWorkspace"),__name(getWorkspaceDirectories,"getWorkspaceDirectories")}});function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${S.platform()}-${S.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 D.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function getAccessibleDirectoryStructure(){return[...getRootDirectoryStructure(),...getAdditionalDirectories().map(e=>`scope:${formatDirectoryForDisplay(e)}`)]}function isGitRepository(){try{return Ce("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return Ce("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){const e=getCurrentWorkingDirectory();try{const t=Ce("git symbolic-ref --short refs/remotes/origin/HEAD",{encoding:"utf8",cwd:e,stdio:["pipe","pipe","ignore"]}).trim().replace(/^origin\//,"");if(t)return t}catch{}try{const t=Ce("git branch -r",{encoding:"utf8",cwd:e,stdio:["pipe","pipe","ignore"]});return t.includes("origin/main")?"main":t.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=Ce("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,i=[];return n>0&&i.push(`M ${n}`),r>0&&i.push(`A ${r}`),o>0&&i.push(`D ${o}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=Ce("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository(),t=getAdditionalDirectories();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getAccessibleDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[],...t.length>0?{additionalDirectories:t}:{}}}var Zo,es,ts,ns,rs,os=__esm({"src/utils/environment.ts"(){Bt(),Xo(),__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(getAccessibleDirectoryStructure,"getAccessibleDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext")}});function generateSessionId(){return`sess_${Me().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return M.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(),[Ot.SESSION_PROJECT_HASH]:hashPath(n),[Ot.SESSION_BRANCH_HASH]:r?hashPath(r):"unknown","session.cli_version":o,"session.platform":`${w.platform()}-${w.arch()}`,"session.node_version":process.version}}function startSession(){rs={},ns=null,ts=null,Zo=generateSessionId(),es=Date.now();try{const e=xe.getTracer(It),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:Zo,projectPath:n,gitBranch:r,cliVersion:t}),s=e.startSpan("session:cli",{attributes:o});ts=s.spanContext(),s.end()}catch{}return Zo}function getSessionId(){return Zo}function setActiveIterationSpanContext(e){ns=e}function getActiveIterationSpanContext(){return ns}function getTraceId(){return ns?ns.traceId:null}function getSessionContext(){return ns?xe.setSpanContext(Ae.active(),ns):Ae.active()}function endSession(e={}){const{status:t="success"}=e;if(es)try{const e=xe.getTracer(It),n=ts?[{context:ts,attributes:{"cmd.session.link_kind":"session_cli"}}]:void 0,r=e.startSpan("session:end",{attributes:{"session.id":Zo||"unknown","session.end_time":(new Date).toISOString(),"session.status":t,...rs},links:n,root:!0},xe.deleteSpan(Ae.active()));r.setStatus({code:"error"===t?Ie.ERROR:Ie.OK}),r.end()}catch{}ns=null,ts=null,Zo=null,es=null,rs={}}function updateSessionContext(e){es&&(rs={...rs,...e})}var ss,as,ls=__esm({"src/utils/telemetry/session.ts"(){Bt(),kn(),Go(),os(),Zo=null,es=null,ts=null,ns=null,rs={},__name(generateSessionId,"generateSessionId"),__name(hashPath,"hashPath"),__name(getCliVersion,"getCliVersion"),__name(buildSessionAttributes,"buildSessionAttributes"),__name(startSession,"startSession"),__name(getSessionId,"getSessionId"),__name(setActiveIterationSpanContext,"setActiveIterationSpanContext"),__name(getActiveIterationSpanContext,"getActiveIterationSpanContext"),__name(getTraceId,"getTraceId"),__name(getSessionContext,"getSessionContext"),__name(endSession,"endSession"),__name(updateSessionContext,"updateSessionContext")}});function getStatus(e){if("number"==typeof e.status)return e.status;if("number"==typeof e.statusCode)return e.statusCode;const t=(e.message||"").match(/\b(\d{3})\b/);if(t){const e=Number(t[1]);if(e>=400&&e<600)return e}}function categorizeError(e){if(!e||"object"!=typeof e)return ss.UNKNOWN;const t=e,n="string"==typeof t.code?t.code.toUpperCase():void 0,r=(t.name||"").toLowerCase(),o=(t.message||"").toLowerCase(),s=getStatus(t);return n&&as.has(n)?ss.NETWORK:"ETIMEDOUT"===n||o.includes("timeout")||o.includes("timed out")?ss.TIMEOUT:"ENOENT"===n||404===s?ss.NOT_FOUND:"EACCES"===n||"EPERM"===n?ss.PERMISSION:"ABORT_ERR"===n||"aborterror"===r||o.includes("abort")?ss.CANCELLED:401===s||403===s||o.includes("unauthorized")||o.includes("forbidden")?ss.AUTH:429===s||o.includes("rate limit")||o.includes("too many requests")?ss.RATE_LIMIT:void 0!==s&&s>=500&&s<600?ss.INTERNAL:void 0!==s&&s>=400&&s<500||r.includes("zod")||r.includes("validation")||o.includes("invalid")?ss.VALIDATION:"fetcherror"===r||o.includes("fetch failed")||o.includes("network")?ss.NETWORK:ss.UNKNOWN}function normalizeStackFrame(e){return e.replace(/0x[0-9a-fA-F]+/g,"0xN").replace(/:\d+:\d+/g,":N:N").replace(/file:\/\/\/[^\s)]+/g,"file:///N").replace(/(\/[^\s:)]+\/)+/g,"/N/").replace(/\b\d{4,}\b/g,"N")}function errorFingerprint(e){const t=e||{},n=t.name||"Error",r=(t.stack||"").split("\n").slice(1).map(e=>e.trim()).find(e=>e.startsWith("at ")&&!e.includes("node:internal")),o=r?`${n}|${normalizeStackFrame(r)}`:`${n}|${(t.message||"").slice(0,120)}`;return M.createHash("sha1").update(o).digest("hex").substring(0,16)}var cs=__esm({"src/utils/telemetry/error-categorization.ts"(){Bt(),ss={NETWORK:"network",AUTH:"auth",RATE_LIMIT:"rate_limit",TIMEOUT:"timeout",VALIDATION:"validation",NOT_FOUND:"not_found",PERMISSION:"permission",INTERNAL:"internal",CANCELLED:"cancelled",UNKNOWN:"unknown"},as=new Set(["ENOTFOUND","ECONNRESET","ECONNREFUSED","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE"]),__name(getStatus,"getStatus"),__name(categorizeError,"categorizeError"),__name(normalizeStackFrame,"normalizeStackFrame"),__name(errorFingerprint,"errorFingerprint")}});function setSpanStatus(e,t){"error"===t?e.setStatus({code:Ie.ERROR}):e.setStatus({code:Ie.OK})}function applyErrorAttributes(e,t){e.setAttribute("error.type",categorizeError(t)),e.setAttribute(Ot.ERROR_FINGERPRINT,errorFingerprint(t))}function createSpan(e){const{name:t,attributes:n}=e,r=xe.getTracer(It),o=Ae.active(),s=void 0!==xe.getSpan(o)?o:getSessionContext();return r.startSpan(t,{attributes:n},s)}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:Ie.ERROR,message:n.message}),applyErrorAttributes(t,n),r)for(const[e,n]of Object.entries(r))void 0!==n&&t.setAttribute(e,n)}var us,ds,ms=__esm({"src/utils/telemetry/spans.ts"(){Bt(),kn(),ls(),cs(),__name(setSpanStatus,"setSpanStatus"),__name(applyErrorAttributes,"applyErrorAttributes"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});async function initAxiomAITelemetry(){if(!us&&!ds)try{const e=await import("axiom/ai").catch(e=>(ds=e instanceof Error?e.message:String(e),null));if(!e)return void dlog("[telemetry] axiom/ai not available — falling back to plain OTel");const t=xe.getTracer(It),n=isContentCaptureEnabled()?e.RedactionPolicy?.AxiomDefault:e.RedactionPolicy?.AxiomStrict??e.RedactionPolicy?.AxiomDefault;e.initAxiomAI?.({tracer:t,redactionPolicy:n}),us=!0}catch(e){ds=e instanceof Error?e.message:String(e)}}var ps,gs,hs,fs,ys,ws,Ss,bs,Es,vs,Cs,ks,Ts,_s,xs,As,Ps,Is,Ms=__esm({"src/utils/telemetry/axiom-ai.ts"(){Bt(),kn(),ir(),us=!1,ds=null,__name(initAxiomAITelemetry,"initAxiomAITelemetry")}});function dedentText(e){const t=e.split("\n");let n=1/0;for(const e of t){if(0===e.trim().length)continue;const t=e.length-e.trimStart().length;t>0&&t<n&&(n=t)}return n===1/0||0===n?e:t.map(e=>0===e.trim().length?e:e.length-e.trimStart().length>=n?e.slice(n):e).join("\n")}function getEffectiveWidth({padding:e=ws}={}){let t=80;return process.stdout.columns?t=process.stdout.columns:process.stderr.columns?t=process.stderr.columns:process.env.COLUMNS&&(t=Number(process.env.COLUMNS)),Math.max(40,t-e)}function truncateString({text:e,maxChars:t}){return e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`}function truncateCommand({command:e}){const t=e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~").replace(/C:\\Users\\[^\\]+/g,"~");if(t.length<=Ss)return t;if(t.includes(" && ")){const e=t.split(" && ")[0].trim();return e.length<=Ss-5?`${e} && ...`:truncateString({text:e,maxChars:Ss})}return truncateString({text:t,maxChars:Ss})}function truncateToVisualLines({output:e,maxVisualLines:t=ps,padding:n=ws,maxChars:r}){const o=getEffectiveWidth({padding:n}),s=r??t*o,i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim().split("\n");let a=0,l=i.length;for(let e=0;e<i.length;e++){const n=i[e];if(0===n.trim().length)continue;const r=Math.max(1,Math.ceil(n.length/o));if(!(a+r<=t)){l=Math.max(1,e);break}a+=r}const u=l<i.length,d=i.slice(l).reduce((e,t)=>e+Math.max(1,Math.ceil(t.length/o)),0),m=i.slice(0,l).filter(e=>e.trim().length>0).join("\n");if(m.length>s){const e=m.slice(0,s-3).trimEnd(),t=e.lastIndexOf("\n"),n=t>0?e.slice(0,t):e;return{text:u?n:`${n}...`,isTruncated:!0,remainingLines:d}}return{text:m,isTruncated:u,remainingLines:d}}var Rs=__esm({"src/utils/truncation.ts"(){Bt(),ps=2,gs=10,hs=10,fs=10,ys=20,ws=4,Ss=100,bs=100,Es=50,vs=100,Cs=100,ks=60,Ts=80,_s=2,xs=1e5,As=5e4,Ps=25e3,Is=1e3,__name(dedentText,"dedentText"),__name(getEffectiveWidth,"getEffectiveWidth"),__name(truncateString,"truncateString"),__name(truncateCommand,"truncateCommand"),__name(truncateToVisualLines,"truncateToVisualLines")}});function normalizeError(e){return e instanceof Error?e:new Error(String(e))}function sanitizeErrorForTelemetry(e){const{error:t,label:n="error"}=e,r=scrubPII(t.message),o=r.length>0?`${n}: ${r}`:n,s=new Error(o);s.name=t.name||"Error";const i=t.code;return void 0!==i&&(s.code=i),s}function scrubPII(e){return e.replace(/[A-Z]:[/\\](?:Users|Documents and Settings)[/\\][^\s:'"`,)}\]]+/gi,"[path]").replace(/\/(?:Users|home|root)\/[^\s:'"`,)}\]]+/g,"[path]").replace(/~\/[^\s:'"`,)}\]]+/g,"[path]").replace(/\b[0-9a-f]{32,}\b/gi,"[token]").replace(/\b(?:sk|key|token|pat|ghp|gho|ghs|ghu|ghr)-[A-Za-z0-9_-]{10,}\b/g,"[apikey]")}function sanitizeEndpoint(e){return e.split("?")[0]}var Ns=__esm({"src/utils/telemetry/sanitization.ts"(){Bt(),kn(),Rs(),__name(normalizeError,"normalizeError"),__name(sanitizeErrorForTelemetry,"sanitizeErrorForTelemetry"),__name(scrubPII,"scrubPII"),__name(sanitizeEndpoint,"sanitizeEndpoint")}});function createTrackingHandle(e){const{span:t}=e;return{span:t,end:__name(e=>{if("status"in e)e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r}=e;t.setAttribute("http.status_code",n),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}=e;return createTrackingHandle({span:createSpan({name:`execute_tool ${t}`,attributes:{[Dt.TOOL_NAME]:t}})})}function buildContextAttributes(e){const{component:t,heading:n,code:r,...o}=e,s={[Ot.ERROR_COMPONENT]:t,[Ot.ERROR_HEADING]:n};void 0!==r&&(s[Ot.ERROR_CODE]=String(r));for(const[e,t]of Object.entries(o))null!=t&&"object"!=typeof t&&(s[e]=String(t));return s}function trackError(e){const{error:t,context:n}=e,r=normalizeError(t),o=buildContextAttributes(n);o["error.type"]=categorizeError(t),o[Ot.ERROR_FINGERPRINT]=errorFingerprint(t);const s=createSpan({name:`error:${r.name}`,attributes:o});recordError({span:s,error:r}),s.end()}function trackEvent(e){const{name:t,context:n}=e;endSpan({span:createSpan({name:t,attributes:buildContextAttributes(n)}),status:"success"})}function trackAPICallStart(e){const{method:t,endpoint:n,cliVersion:r}=e,o=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${o}`,attributes:{"http.method":t,"http.url":o,...r?{"cli.version":r}:{}}})})}function getDisplayTraceId(){return getTraceId()||"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,platform:s,arch:i}=e,a={"os.type":s,"os.arch":i};t&&(a["user.name"]=t),n&&(a["user.id"]=n),r&&(a[Ot.ORG_LOGIN]=r),o&&(a[Ot.ORG_ID]=o),updateSessionContext(a)}var Ls,$s,Ds,Os,Fs=__esm({"src/utils/telemetry/events.ts"(){Bt(),kn(),cs(),Ns(),ls(),ms(),Ns(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(buildContextAttributes,"buildContextAttributes"),__name(trackError,"trackError"),__name(trackEvent,"trackEvent"),__name(trackAPICallStart,"trackAPICallStart"),__name(getDisplayTraceId,"getDisplayTraceId"),__name(systemInfo,"systemInfo")}}),js=__esm({"src/utils/telemetry/components.ts"(){Bt(),Ls={AUTH_FLOW:"auth-flow",ANTHROPIC_OAUTH:"anthropic-oauth",COPILOT_OAUTH:"copilot-oauth",CODEX_OAUTH:"codex-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",UPDATER:"updater",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",AGENT_LOOP:"agent-loop",CLI_ERROR_HANDLER:"cli-error-handler",TOOL_REPAIR:"tool-repair"}}});function initTelemetry(){if(Ds)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return($s=createTelemetrySDK()).start(),Ds=!0,initAxiomAITelemetry(),!0}catch{return $s=null,Ds=!1,!1}}async function shutdownTelemetry(){if($s&&Ds)try{endSession(),await Promise.allSettled(Os),await Promise.race([$s.shutdown(),new Promise(e=>setTimeout(e,Mt))])}catch{}finally{$s=null,Ds=!1}}function shutdownTelemetrySync(){if(Ds)try{endSession()}catch{}}function isTelemetryInitialized(){return Ds}function registerStartupTask(e){Os.push(e)}var Us,Bs=__esm({"src/utils/telemetry/telemetry.ts"(){Bt(),Vo(),$o(),ls(),ms(),kn(),Ms(),Fs(),js(),cs(),$s=null,Ds=!1,Os=[],__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized"),__name(registerStartupTask,"registerStartupTask")}});function getApiKeyFromEnv(){const e=process.env[Us]?.trim();return e&&e.length>0?e:null}async function readAuthFile(e){try{const t=getAuthFile(e),n=await k.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async function getAuthKey(e){const t=getApiKeyFromEnv();if(t)return t;const n=await readAuthFile(e);return n&&n.apiKey||null}async function getPersistedAuth(e){const t=await readAuthFile(e);return t?.apiKey?{authenticated:!0,userName:t.userName,apiKey:t.apiKey}:{authenticated:!1}}async function getUserName(e){const t=await readAuthFile(e);return t&&t.userName||""}async function checkAuthStatus(e){const t=getApiKeyFromEnv();if(t)return{authenticated:!0,apiKey:t,fromEnv:!0};const n=await readAuthFile(e);return n&&n.apiKey?{authenticated:!0,apiKey:n.apiKey,userName:n.userName}:{authenticated:!1,apiKey:null}}var qs=__esm({"src/utils/auth/auth-file.ts"(){Bt(),Un(),Us="COMMAND_CODE_API_KEY",__name(getApiKeyFromEnv,"getApiKeyFromEnv"),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getPersistedAuth,"getPersistedAuth"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus")}});function isGenericUserName(e){return!e||"API Key"===e||"Manual API Key"===e}function formatUserSuffix(e){return isGenericUserName(e)?"":` as ${e}`}function formatColoredUserSuffix(e){return isGenericUserName(e)?"":` as ${de.cyan(e)}`}function formatAlreadyLoggedIn(e){return`Already logged in${formatUserSuffix(e)}`}function getStartedLine(){return`${de.dim("Run")} ${de.cyan("cmd")} ${de.dim("to get started.")}`}function getLoginSuccessSuffix(e,t){return isGenericUserName(e)?t?"":" successfully":formatColoredUserSuffix(e)}function formatLoginSuccessStyled(e){const{userName:t,authFileName:n,providerLabel:r,providerWarning:o}=e,s=getLoginSuccessSuffix(t,r),i=r?` with ${de.cyan(r)}`:"",a=[`${de.green(Re.tick)} ${de.bold("Logged in")}${s}${i}`];return o&&a.push(` ${de.yellow(Re.warning)} ${de.yellow(o)}`),a.push("",`${de.dim("API key stored in")} ${de.cyan(`~/.commandcode/${n}`)}`,getStartedLine()),a.join("\n")}function formatAlreadyLoggedInStyled(e){const t=formatColoredUserSuffix(e);return[`${de.green(Re.tick)} ${de.bold("Already logged in")}${t}`,"",getStartedLine()].join("\n")}function formatLogoutSuccess(e){return isGenericUserName(e)?"Logged out successfully":`Logged out as ${e}`}function formatNotAuthenticated(){return"Not currently authenticated"}function formatLogoutFailed(e){return`Logout failed: ${e}`}function formatLogoutWarnings(e){return 0===e.length?"":`Warnings: ${e.join(", ")}`}function formatAuthCancelled(){return"Authentication cancelled"}var zs,Hs=__esm({"src/utils/auth/auth-messages.ts"(){Bt(),_n(),__name(isGenericUserName,"isGenericUserName"),__name(formatUserSuffix,"formatUserSuffix"),__name(formatColoredUserSuffix,"formatColoredUserSuffix"),__name(formatAlreadyLoggedIn,"formatAlreadyLoggedIn"),__name(getStartedLine,"getStartedLine"),__name(getLoginSuccessSuffix,"getLoginSuccessSuffix"),__name(formatLoginSuccessStyled,"formatLoginSuccessStyled"),__name(formatAlreadyLoggedInStyled,"formatAlreadyLoggedInStyled"),__name(formatLogoutSuccess,"formatLogoutSuccess"),__name(formatNotAuthenticated,"formatNotAuthenticated"),__name(formatLogoutFailed,"formatLogoutFailed"),__name(formatLogoutWarnings,"formatLogoutWarnings"),__name(formatAuthCancelled,"formatAuthCancelled")}});function detectConfigParseError(){try{const e=getConfigFile();if(!$.existsSync(e))return null;const t=$.readFileSync(e,"utf-8");return""===t.trim()?null:null===parseJSON(t)?`config.json at ${e} is not valid JSON`:null}catch{return null}}async function buildStatusJson(e){const t=getPackageJson().version;if(e.error)return{authenticated:!1,version:t,error:e.error};if(!e.authenticated)return{authenticated:!1,version:t};const n=detectConfigParseError();if(n)return{authenticated:!0,version:t,error:n};const r={authenticated:!0,version:t};e.userName&&!isGenericUserName(e.userName)&&(r.user=e.userName);try{const e=await getConfiguredProvider();e&&(r.provider=e)}catch{}try{const e=getConfiguredModel();if(e){r.model=e;const t=findModelById(getCanonicalModelId(e))?.contextWindow;t&&(r.context_window=t)}}catch{}return r}async function statusAction(e){if(e.json){const e=Tn();let t;try{t=await checkAuthStatus(e)}catch(e){t={authenticated:!1,apiKey:null,error:e instanceof Error?e.message:"Unknown error"}}const n=await buildStatusJson(t),r=!n.authenticated||n.error?1:0;return void process.stdout.write(`${JSON.stringify(n)}\n`,()=>process.exit(r))}const t=De("Checking authentication status...").start();try{const e=Tn(),n=await checkAuthStatus(e);n.error&&(t.fail(de.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(t.fail(de.red("Not authenticated")),console.log(""),console.log(`${de.dim("Run")} ${de.cyan("cmd auth login")} ${de.dim("to authenticate.")}`),console.log(""),process.exit(1));const r=isGenericUserName(n.userName)?"":` as ${de.cyan(n.userName)}`;t.succeed("Authentication verified"),console.log(`${de.green(Re.tick)} ${de.bold("Authenticated")}${r}`),console.log(` ${de.dim("Provider:")} ${de.cyan("Command Code")}`),n.fromEnv&&console.log(` ${de.dim("Source:")} ${de.cyan(`$${Us}`)} ${de.dim("(env var)")}`),console.log(""),process.exit(0)}catch(e){t.fail(de.red(`Status check failed: ${e instanceof Error?e.message:"Unknown error"}`)),process.exit(1)}}var Ws,Gs,Vs,Ks,Qs,Ys,Js,Xs,Zs,ei,ti,ni,ri=__esm({"src/commands/auth/status.ts"(){Bt(),_n(),bo(),xn(),qs(),Un(),Hs(),Co(),No(),Go(),No(),qs(),__name(detectConfigParseError,"detectConfigParseError"),__name(buildStatusJson,"buildStatusJson"),__name(statusAction,"statusAction"),zs=new Ne("status").description("Show authentication status").option("--json","Output status as JSON for automation").allowUnknownOption().allowExcessArguments().action(statusAction)}}),oi=__esm({"src/api/errors.ts"(){Bt(),Ws=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,null!=o?.status&&(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 Gs({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Vs(e,o,n,r);case 401:return new Ks(e,o,n,r);case 403:return new Qs(e,o,n,r);case 404:return new Ys(e,o,n,r);case 409:return new Js(e,o,n,r);case 422:return new Xs(e,o,n,r);case 429:return new Zs(e,o,n,r);default:return e>=500?new ei(e,o,n,r):new _APIError(e,o,n,r)}}},Gs=class extends Ws{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)}},Vs=class extends Ws{static{__name(this,"BadRequestError")}status=400},Ks=class extends Ws{static{__name(this,"AuthenticationError")}status=401},Qs=class extends Ws{static{__name(this,"PermissionDeniedError")}status=403},Ys=class extends Ws{static{__name(this,"NotFoundError")}status=404},Js=class extends Ws{static{__name(this,"ConflictError")}status=409},Xs=class extends Ws{static{__name(this,"UnprocessableEntityError")}status=422},Zs=class extends Ws{static{__name(this,"RateLimitError")}status=429},ei=class extends Ws{static{__name(this,"InternalServerError")}}}}),si=__esm({"../shared/src/types/share.ts"(){Bt(),ti=f.object({messageId:f.string().optional(),timestamp:f.string(),model:f.string().optional(),duration:f.number().optional(),usage:f.object({inputTokens:f.number(),outputTokens:f.number(),totalTokens:f.number(),cacheReadTokens:f.number().optional(),cacheWriteTokens:f.number().optional(),estimatedCost:f.number().optional()}).optional(),source:f.string().optional(),entrypoint:f.string().optional(),context:f.object({sessionId:f.string().optional(),threadId:f.string().optional(),userId:f.string().optional()}).optional(),highlight:f.boolean().optional(),isSummary:f.boolean().optional(),isAutomated:f.boolean().optional(),isMeta:f.boolean().optional(),hookContexts:f.record(f.string(),f.object({preToolUse:f.string().optional(),postToolUse:f.string().optional()})).optional()}),f.object({message:f.any(),meta:ti}),f.object({sessionId:f.string().uuid("sessionId must be a UUID"),messages:f.array(f.any()).optional()}),f.object({secret:f.string(),url:f.string()}),f.object({sessionId:f.string().uuid("sessionId must be a UUID"),secret:f.string()}),f.object({sessionId:f.string(),secret:f.string(),key:f.string(),content:f.any()}),f.object({sessionId:f.string().uuid("sessionId must be a UUID"),secret:f.string(),message:f.any()}),ni=/^[a-f0-9]{8}$/,f.object({shortId:f.string().regex(ni,"Invalid shortId")}),f.object({info:f.any().optional(),messages:f.array(f.any())})}}),ii=__esm({"../shared/src/types/whoami.ts"(){Bt()}});function parseModelString(e){if(e.includes(":")){const t=e.indexOf(":");return{provider:e.slice(0,t),modelId:e.slice(t+1)}}return{provider:"anthropic",modelId:e}}var ai,li=__esm({"../shared/src/types/messages.ts"(){Bt(),__name(parseModelString,"parseModelString")}}),ci=__esm({"../shared/src/types/email.ts"(){Bt(),f.object({to:f.union([f.email(),f.array(f.email())]),subject:f.string(),html:f.string().optional(),text:f.string().optional(),template:f.string().optional(),templateData:f.record(f.any(),f.any()).optional(),cc:f.array(f.email()).optional(),bcc:f.array(f.email()).optional(),replyTo:f.array(f.email()).optional(),tags:f.array(f.object({name:f.string(),value:f.string()})).optional()}),f.object({success:f.boolean(),messageId:f.string().optional(),error:f.string().optional()})}});function is(e,t){if(!e||"object"!=typeof e)return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,ai))throw new Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(ai in n&&n[ai]===t[ai])return!0;n=Object.getPrototypeOf(n)}return!1}var ui,di,mi,pi,gi,hi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/entity.js"(){Bt(),ai=Symbol.for("drizzle:entityKind"),__name(is,"is")}}),fi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/column.js"(){Bt(),hi(),ui=class{static{__name(this,"Column")}constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[ai]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}}}),yi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/column-builder.js"(){Bt(),hi(),di=class{static{__name(this,"ColumnBuilder")}static[ai]="ColumnBuilder";config;constructor(e,t,n){this.config={name:e,keyAsName:""===e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){""===this.config.name&&(this.config.name=e)}}}}),wi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/table.utils.js"(){Bt(),mi=Symbol.for("drizzle:Name")}}),Si=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/foreign-keys.js"(){Bt(),hi(),wi(),pi=class{static{__name(this,"ForeignKeyBuilder")}static[ai]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){this.reference=()=>{const{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new gi(e,this)}},gi=class{static{__name(this,"ForeignKey")}constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[ai]="PgForeignKey";reference;onUpdate;onDelete;getName(){const{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),o=n.map(e=>e.name),s=[this.table[mi],...r,n[0].table[mi],...o];return e??`${s.join("_")}_fk`}}}});function iife(e,...t){return e(...t)}var bi,Ei,vi,Ci=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/tracing-utils.js"(){Bt(),__name(iife,"iife")}});function unique(e){return new Ei(e)}function uniqueKeyName(e,t){return`${e[mi]}_${t.join("_")}_unique`}var ki=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/unique-constraint.js"(){Bt(),hi(),wi(),__name(unique,"unique"),__name(uniqueKeyName,"uniqueKeyName"),bi=class{static{__name(this,"UniqueConstraintBuilder")}constructor(e,t){this.name=t,this.columns=e}static[ai]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new vi(e,this.columns,this.nullsNotDistinctConfig,this.name)}},Ei=class{static{__name(this,"UniqueOnConstraintBuilder")}static[ai]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new bi(e,this.name)}},vi=class{static{__name(this,"UniqueConstraint")}constructor(e,t,n,r){this.table=e,this.columns=t,this.name=r??uniqueKeyName(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static[ai]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}}});function parsePgArrayValue(e,t,n){for(let r=t;r<e.length;r++){const o=e[r];if("\\"!==o){if('"'===o)return[e.slice(t,r).replace(/\\/g,""),r+1];if(!n&&(","===o||"}"===o))return[e.slice(t,r).replace(/\\/g,""),r]}else r++}return[e.slice(t).replace(/\\/g,""),e.length]}function parsePgNestedArray(e,t=0){const n=[];let r=t,o=!1;for(;r<e.length;){const s=e[r];if(","===s){(o||r===t)&&n.push(""),o=!0,r++;continue}if(o=!1,"\\"===s){r+=2;continue}if('"'===s){const[t,o]=parsePgArrayValue(e,r+1,!0);n.push(t),r=o;continue}if("}"===s)return[n,r+1];if("{"===s){const[t,o]=parsePgNestedArray(e,r+1);n.push(t),r=o;continue}const[i,a]=parsePgArrayValue(e,r,!1);n.push(i),r=a}return[n,r]}function parsePgArray(e){const[t]=parsePgNestedArray(e,1);return t}function makePgArray(e){return`{${e.map(e=>Array.isArray(e)?makePgArray(e):"string"==typeof e?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}var Ti,_i,xi,Ai,Pi,Ii,Mi,Ri,Ni,Li,$i,Di=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/utils/array.js"(){Bt(),__name(parsePgArrayValue,"parsePgArrayValue"),__name(parsePgNestedArray,"parsePgNestedArray"),__name(parsePgArray,"parsePgArray"),__name(makePgArray,"makePgArray")}}),Oi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/common.js"(){Bt(),yi(),fi(),hi(),Si(),Ci(),ki(),Di(),Ti=class extends di{static{__name(this,"PgColumnBuilder")}foreignKeyConfigs=[];static[ai]="PgColumnBuilder";array(e){return new Pi(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>iife((n,r)=>{const o=new pi(()=>{const t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&o.onUpdate(r.onUpdate),r.onDelete&&o.onDelete(r.onDelete),o.build(t)},n,r))}buildExtraConfigColumn(e){return new xi(e,this.config)}},_i=class extends ui{static{__name(this,"PgColumn")}constructor(e,t){t.uniqueName||(t.uniqueName=uniqueKeyName(e,[t.name])),super(e,t),this.table=e}static[ai]="PgColumn"},xi=class extends _i{static{__name(this,"ExtraConfigColumn")}static[ai]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}},Ai=class{static{__name(this,"IndexedColumn")}static[ai]="IndexedColumn";constructor(e,t,n,r){this.name=e,this.keyAsName=t,this.type=n,this.indexConfig=r}name;keyAsName;type;indexConfig},Pi=class extends Ti{static{__name(this,"PgArrayBuilder")}static[ai]="PgArrayBuilder";constructor(e,t,n){super(e,"array","PgArray"),this.config.baseBuilder=t,this.config.size=n}build(e){const t=this.config.baseBuilder.build(e);return new Ii(e,this.config,t)}},Ii=class _PgArray extends _i{static{__name(this,"PgArray")}constructor(e,t,n,r){super(e,t),this.baseColumn=n,this.range=r,this.size=t.size}size;static[ai]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=parsePgArray(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,t=!1){const n=e.map(e=>null===e?null:is(this.baseColumn,_PgArray)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return t?n:makePgArray(n)}}}});function isPgEnum(e){return!!e&&"function"==typeof e&&Ni in e&&!0===e[Ni]}function pgEnum(e,t){return Array.isArray(t)?pgEnumWithSchema(e,[...t],void 0):pgEnumObjectWithSchema(e,t,void 0)}function pgEnumWithSchema(e,t,n){const r=Object.assign(e=>new Li(e??"",r),{enumName:e,enumValues:t,schema:n,[Ni]:!0});return r}function pgEnumObjectWithSchema(e,t,n){const r=Object.assign(e=>new Mi(e??"",r),{enumName:e,enumValues:Object.values(t),schema:n,[Ni]:!0});return r}var Fi,ji,Ui,Bi,qi,zi,Hi,Wi,Gi,Vi,Ki,Qi,Yi,Ji=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/enum.js"(){Bt(),hi(),Oi(),Mi=class extends Ti{static{__name(this,"PgEnumObjectColumnBuilder")}static[ai]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn"),this.config.enum=t}build(e){return new Ri(e,this.config)}},Ri=class extends _i{static{__name(this,"PgEnumObjectColumn")}static[ai]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},Ni=Symbol.for("drizzle:isPgEnum"),__name(isPgEnum,"isPgEnum"),Li=class extends Ti{static{__name(this,"PgEnumColumnBuilder")}static[ai]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn"),this.config.enum=t}build(e){return new $i(e,this.config)}},$i=class extends _i{static{__name(this,"PgEnumColumn")}static[ai]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},__name(pgEnum,"pgEnum"),__name(pgEnumWithSchema,"pgEnumWithSchema"),__name(pgEnumObjectWithSchema,"pgEnumObjectWithSchema")}}),Xi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/subquery.js"(){Bt(),hi(),Fi=class{static{__name(this,"Subquery")}static[ai]="Subquery";constructor(e,t,n,r=!1,o=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:n,isWith:r,usedTables:o}}},ji=class extends Fi{static{__name(this,"WithSubquery")}static[ai]="WithSubquery"}}}),Zi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/version.js"(){Bt()}}),ea=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/tracing.js"(){Bt(),Ci(),Zi(),Ui={startActiveSpan:(e,t)=>t()}}}),ta=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/view-common.js"(){Bt(),Bi=Symbol.for("drizzle:ViewBaseConfig")}});function getTableName(e){return e[mi]}function getTableUniqueName(e){return`${e[qi]??"public"}.${e[mi]}`}var na,ra,oa,sa,ia,aa,la,ca,ua,da=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/table.js"(){Bt(),hi(),wi(),qi=Symbol.for("drizzle:Schema"),zi=Symbol.for("drizzle:Columns"),Hi=Symbol.for("drizzle:ExtraConfigColumns"),Wi=Symbol.for("drizzle:OriginalName"),Gi=Symbol.for("drizzle:BaseName"),Vi=Symbol.for("drizzle:IsAlias"),Ki=Symbol.for("drizzle:ExtraConfigBuilder"),Qi=Symbol.for("drizzle:IsDrizzleTable"),Yi=class{static{__name(this,"Table")}static[ai]="Table";static Symbol={Name:mi,Schema:qi,OriginalName:Wi,Columns:zi,ExtraConfigColumns:Hi,BaseName:Gi,IsAlias:Vi,ExtraConfigBuilder:Ki};[mi];[Wi];[qi];[zi];[Hi];[Gi];[Vi]=!1;[Qi]=!0;[Ki]=void 0;constructor(e,t,n){this[mi]=this[Wi]=e,this[qi]=t,this[Gi]=n}},__name(getTableName,"getTableName"),__name(getTableUniqueName,"getTableUniqueName")}});function isSQLWrapper(e){return null!=e&&"function"==typeof e.getSQL}function mergeQueries(e){const t={sql:"",params:[]};for(const n of e)t.sql+=n.sql,t.params.push(...n.params),n.typings?.length&&(t.typings||(t.typings=[]),t.typings.push(...n.typings));return t}function isDriverValueEncoder(e){return"object"==typeof e&&null!==e&&"mapToDriverValue"in e&&"function"==typeof e.mapToDriverValue}function sql(e,...t){const n=[];(t.length>0||e.length>0&&""!==e[0])&&n.push(new na(e[0]));for(const[r,o]of t.entries())n.push(o,new na(e[r+1]));return new ra(n)}var ma,pa,ga=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/sql.js"(){Bt(),hi(),Ji(),Xi(),ea(),ta(),fi(),da(),class{static{__name(this,"FakePrimitiveParam")}static[ai]="FakePrimitiveParam"},__name(isSQLWrapper,"isSQLWrapper"),__name(mergeQueries,"mergeQueries"),na=class{static{__name(this,"StringChunk")}static[ai]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new ra([this])}},ra=class _SQL{static{__name(this,"SQL")}constructor(e){this.queryChunks=e;for(const t of e)if(is(t,Yi)){const e=t[Yi.Symbol.Schema];this.usedTables.push(void 0===e?t[Yi.Symbol.Name]:e+"."+t[Yi.Symbol.Name])}}static[ai]="SQL";decoder=sa;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return Ui.startActiveSpan("drizzle.buildSQL",t=>{const n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){const n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:r,escapeName:o,escapeParam:s,prepareTyping:i,inlineParams:a,paramStartIndex:l}=n;return mergeQueries(e.map(e=>{if(is(e,na))return{sql:e.value.join(""),params:[]};if(is(e,oa))return{sql:o(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){const t=[new na("(")];for(const[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(new na(", "));return t.push(new na(")")),this.buildQueryFromSourceParams(t,n)}if(is(e,_SQL))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:a||e.shouldInlineParams});if(is(e,Yi)){const t=e[Yi.Symbol.Schema],n=e[Yi.Symbol.Name];return{sql:void 0===t||e[Vi]?o(n):o(t)+"."+o(n),params:[]}}if(is(e,ui)){const n=r.getColumnCasing(e);if("indexes"===t.invokeSource)return{sql:o(n),params:[]};const s=e.table[Yi.Symbol.Schema];return{sql:e.table[Vi]||void 0===s?o(e.table[Yi.Symbol.Name])+"."+o(n):o(s)+"."+o(e.table[Yi.Symbol.Name])+"."+o(n),params:[]}}if(is(e,ua)){const t=e[Bi].schema,n=e[Bi].name;return{sql:void 0===t||e[Bi].isAlias?o(n):o(t)+"."+o(n),params:[]}}if(is(e,aa)){if(is(e.value,la))return{sql:s(l.value++,e),params:[e],typings:["none"]};const t=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(is(t,_SQL))return this.buildQueryFromSourceParams([t],n);if(a)return{sql:this.mapInlineParam(t,n),params:[]};let r=["none"];return i&&(r=[i(e.encoder)]),{sql:s(l.value++,t),params:[t],typings:r}}return is(e,la)?{sql:s(l.value++,e),params:[e],typings:["none"]}:is(e,_SQL.Aliased)&&void 0!==e.fieldAlias?{sql:o(e.fieldAlias),params:[]}:is(e,Fi)?e._.isWith?{sql:o(e._.alias),params:[]}:this.buildQueryFromSourceParams([new na("("),e._.sql,new na(") "),new oa(e._.alias)],n):isPgEnum(e)?e.schema?{sql:o(e.schema)+"."+o(e.enumName),params:[]}:{sql:o(e.enumName),params:[]}:isSQLWrapper(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new na("("),e.getSQL(),new na(")")],n):a?{sql:this.mapInlineParam(e,n),params:[]}:{sql:s(l.value++,e),params:[e],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return t(e);if("object"==typeof e){const n=e.toString();return t("[object Object]"===n?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new _SQL.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},oa=class{static{__name(this,"Name")}constructor(e){this.value=e}static[ai]="Name";brand;getSQL(){return new ra([this])}},__name(isDriverValueEncoder,"isDriverValueEncoder"),sa={mapFromDriverValue:__name(e=>e,"mapFromDriverValue")},ia={mapToDriverValue:__name(e=>e,"mapToDriverValue")},aa=class{static{__name(this,"Param")}constructor(e,t=ia){this.value=e,this.encoder=t}static[ai]="Param";brand;getSQL(){return new ra([this])}},__name(sql,"sql"),(e=>{function empty(){return new ra([])}function fromList(e){return new ra(e)}function raw(e){return new ra([new na(e)])}function join30(e,t){const n=[];for(const[r,o]of e.entries())r>0&&void 0!==t&&n.push(t),n.push(o);return new ra(n)}function identifier(e){return new oa(e)}function placeholder2(e){return new la(e)}function param2(e,t){return new aa(e,t)}__name(empty,"empty"),e.empty=empty,__name(fromList,"fromList"),e.fromList=fromList,__name(raw,"raw"),e.raw=raw,__name(join30,"join"),e.join=join30,__name(identifier,"identifier"),e.identifier=identifier,__name(placeholder2,"placeholder2"),e.placeholder=placeholder2,__name(param2,"param2"),e.param=param2})(sql||(sql={})),(e=>{class Aliased{static{__name(this,"Aliased")}constructor(e,t){this.sql=e,this.fieldAlias=t}static[ai]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Aliased(this.sql,this.fieldAlias)}}e.Aliased=Aliased})(ra||(ra={})),la=class{static{__name(this,"Placeholder")}constructor(e){this.name=e}static[ai]="Placeholder";getSQL(){return new ra([this])}},ca=Symbol.for("drizzle:IsDrizzleView"),ua=class{static{__name(this,"View")}static[ai]="View";[Bi];[ca]=!0;constructor({name:e,schema:t,selectedFields:n,query:r}){this[Bi]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new ra([this])}},ui.prototype.getSQL=function(){return new ra([this])},Yi.prototype.getSQL=function(){return new ra([this])},Fi.prototype.getSQL=function(){return new ra([this])}}});function aliasedTable(e,t){return new Proxy(e,new pa(t,!1))}function aliasedTableColumn(e,t){return new Proxy(e,new ma(new Proxy(e.table,new pa(t,!1))))}function mapColumnsInAliasedSQLToAlias(e,t){return new ra.Aliased(mapColumnsInSQLToAlias(e.sql,t),e.fieldAlias)}function mapColumnsInSQLToAlias(e,t){return sql.join(e.queryChunks.map(e=>is(e,ui)?aliasedTableColumn(e,t):is(e,ra)?mapColumnsInSQLToAlias(e,t):is(e,ra.Aliased)?mapColumnsInAliasedSQLToAlias(e,t):e))}var ha,fa,ya=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/alias.js"(){Bt(),fi(),hi(),ga(),da(),ta(),ma=class{static{__name(this,"ColumnAliasProxyHandler")}constructor(e){this.table=e}static[ai]="ColumnAliasProxyHandler";get(e,t){return"table"===t?this.table:e[t]}},pa=class{static{__name(this,"TableAliasProxyHandler")}constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[ai]="TableAliasProxyHandler";get(e,t){if(t===Yi.Symbol.IsAlias)return!0;if(t===Yi.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Yi.Symbol.OriginalName)return this.alias;if(t===Bi)return{...e[Bi],name:this.alias,isAlias:!0};if(t===Yi.Symbol.Columns){const t=e[Yi.Symbol.Columns];if(!t)return t;const n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new ma(new Proxy(e,this)))}),n}const n=e[t];return is(n,ui)?new Proxy(n,new ma(new Proxy(e,this))):n}},class{static{__name(this,"RelationTableAliasProxyHandler")}constructor(e){this.alias=e}static[ai]="RelationTableAliasProxyHandler";get(e,t){return"sourceTable"===t?aliasedTable(e.sourceTable,this.alias):e[t]}},__name(aliasedTable,"aliasedTable"),__name(aliasedTableColumn,"aliasedTableColumn"),__name(mapColumnsInAliasedSQLToAlias,"mapColumnsInAliasedSQLToAlias"),__name(mapColumnsInSQLToAlias,"mapColumnsInSQLToAlias")}}),wa=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/alias.js"(){Bt()}});function check(e,t){return new ha(e,t)}var Sa,ba=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/checks.js"(){Bt(),hi(),ha=class{static{__name(this,"CheckBuilder")}constructor(e,t){this.name=e,this.value=t}static[ai]="PgCheckBuilder";brand;build(e){return new fa(e,this)}},fa=class{static{__name(this,"Check")}constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[ai]="PgCheck";name;value},__name(check,"check")}});function orderSelectedFields(e,t){return Object.entries(e).reduce((e,[n,r])=>{if("string"!=typeof n)return e;const o=t?[...t,n]:[n];return is(r,ui)||is(r,ra)||is(r,ra.Aliased)||is(r,Fi)?e.push({path:o,field:r}):is(r,Yi)?e.push(...orderSelectedFields(r[Yi.Symbol.Columns],o)):e.push(...orderSelectedFields(r,o)),e},[])}function haveSameKeys(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const[e,t]of n.entries())if(t!==r[e])return!1;return!0}function mapUpdateSet(e,t){const n=Object.entries(t).filter(([,e])=>void 0!==e).map(([t,n])=>is(n,ra)||is(n,ui)?[t,n]:[t,new aa(n,e[Yi.Symbol.Columns][t])]);if(0===n.length)throw new Error("No values to set");return Object.fromEntries(n)}function applyMixins(e,t){for(const n of t)for(const t of Object.getOwnPropertyNames(n.prototype))"constructor"!==t&&Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)||Object.create(null))}function getTableColumns(e){return e[Yi.Symbol.Columns]}function getTableLikeName(e){return is(e,Fi)?e._.alias:is(e,ua)?e[Bi].name:is(e,ra)?void 0:e[Yi.Symbol.IsAlias]?e[Yi.Symbol.Name]:e[Yi.Symbol.BaseName]}function getColumnNameAndConfig(e,t){return{name:"string"==typeof e&&e.length>0?e:"",config:"object"==typeof e?e:t}}var Ea,va,Ca,ka,Ta,_a=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/utils.js"(){Bt(),fi(),hi(),ga(),Xi(),da(),ta(),__name(orderSelectedFields,"orderSelectedFields"),__name(haveSameKeys,"haveSameKeys"),__name(mapUpdateSet,"mapUpdateSet"),__name(applyMixins,"applyMixins"),__name(getTableColumns,"getTableColumns"),__name(getTableLikeName,"getTableLikeName"),__name(getColumnNameAndConfig,"getColumnNameAndConfig"),Sa="undefined"==typeof TextDecoder?null:new TextDecoder}}),xa=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/int.common.js"(){Bt(),hi(),Oi(),Ea=class extends Ti{static{__name(this,"PgIntColumnBaseBuilder")}static[ai]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(e){if(e){const{name:t,...n}=e;this.config.generatedIdentity={type:"always",sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){const{name:t,...n}=e;this.config.generatedIdentity={type:"byDefault",sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}}});function bigint(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"number"===r.mode?new va(n):new ka(n)}var Aa,Pa,Ia,Ma,Ra=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/bigint.js"(){Bt(),hi(),_a(),Oi(),xa(),va=class extends Ea{static{__name(this,"PgBigInt53Builder")}static[ai]="PgBigInt53Builder";constructor(e){super(e,"number","PgBigInt53")}build(e){return new Ca(e,this.config)}},Ca=class extends _i{static{__name(this,"PgBigInt53")}static[ai]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}},ka=class extends Ea{static{__name(this,"PgBigInt64Builder")}static[ai]="PgBigInt64Builder";constructor(e){super(e,"bigint","PgBigInt64")}build(e){return new Ta(e,this.config)}},Ta=class extends _i{static{__name(this,"PgBigInt64")}static[ai]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(e){return BigInt(e)}},__name(bigint,"bigint")}});function bigserial(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"number"===r.mode?new Aa(n):new Ia(n)}var Na,La,$a=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/bigserial.js"(){Bt(),hi(),_a(),Oi(),Aa=class extends Ti{static{__name(this,"PgBigSerial53Builder")}static[ai]="PgBigSerial53Builder";constructor(e){super(e,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Pa(e,this.config)}},Pa=class extends _i{static{__name(this,"PgBigSerial53")}static[ai]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}},Ia=class extends Ti{static{__name(this,"PgBigSerial64Builder")}static[ai]="PgBigSerial64Builder";constructor(e){super(e,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(e){return new Ma(e,this.config)}},Ma=class extends _i{static{__name(this,"PgBigSerial64")}static[ai]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(e){return BigInt(e)}},__name(bigserial,"bigserial")}});function boolean(e){return new Na(e??"")}var Da,Oa,Fa=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/boolean.js"(){Bt(),hi(),Oi(),Na=class extends Ti{static{__name(this,"PgBooleanBuilder")}static[ai]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new La(e,this.config)}},La=class extends _i{static{__name(this,"PgBoolean")}static[ai]="PgBoolean";getSQLType(){return"boolean"}},__name(boolean,"boolean")}});function char(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new Da(n,r)}var ja,Ua,Ba=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/char.js"(){Bt(),hi(),_a(),Oi(),Da=class extends Ti{static{__name(this,"PgCharBuilder")}static[ai]="PgCharBuilder";constructor(e,t){super(e,"string","PgChar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new Oa(e,this.config)}},Oa=class extends _i{static{__name(this,"PgChar")}static[ai]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"char":`char(${this.length})`}},__name(char,"char")}});function cidr(e){return new ja(e??"")}var qa,za,Ha=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/cidr.js"(){Bt(),hi(),Oi(),ja=class extends Ti{static{__name(this,"PgCidrBuilder")}static[ai]="PgCidrBuilder";constructor(e){super(e,"string","PgCidr")}build(e){return new Ua(e,this.config)}},Ua=class extends _i{static{__name(this,"PgCidr")}static[ai]="PgCidr";getSQLType(){return"cidr"}},__name(cidr,"cidr")}});function customType(e){return(t,n)=>{const{name:r,config:o}=getColumnNameAndConfig(t,n);return new qa(r,o,e)}}var Wa,Ga,Va,Ka,Qa,Ya=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/custom.js"(){Bt(),hi(),_a(),Oi(),qa=class extends Ti{static{__name(this,"PgCustomColumnBuilder")}static[ai]="PgCustomColumnBuilder";constructor(e,t,n){super(e,"custom","PgCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new za(e,this.config)}},za=class extends _i{static{__name(this,"PgCustomColumn")}static[ai]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return"function"==typeof this.mapFrom?this.mapFrom(e):e}mapToDriverValue(e){return"function"==typeof this.mapTo?this.mapTo(e):e}},__name(customType,"customType")}}),Ja=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/date.common.js"(){Bt(),hi(),ga(),Oi(),Wa=class extends Ti{static{__name(this,"PgDateColumnBaseBuilder")}static[ai]="PgDateColumnBaseBuilder";defaultNow(){return this.default(sql`now()`)}}}});function date(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"date"===r?.mode?new Ga(n):new Ka(n)}var Xa,Za,el=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/date.js"(){Bt(),hi(),_a(),Oi(),Ja(),Ga=class extends Wa{static{__name(this,"PgDateBuilder")}static[ai]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new Va(e,this.config)}},Va=class extends _i{static{__name(this,"PgDate")}static[ai]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?new Date(e):e}mapToDriverValue(e){return e.toISOString()}},Ka=class extends Wa{static{__name(this,"PgDateStringBuilder")}static[ai]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new Qa(e,this.config)}},Qa=class extends _i{static{__name(this,"PgDateString")}static[ai]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?e:e.toISOString().slice(0,-14)}},__name(date,"date")}});function doublePrecision(e){return new Xa(e??"")}var tl,nl,rl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/double-precision.js"(){Bt(),hi(),Oi(),Xa=class extends Ti{static{__name(this,"PgDoublePrecisionBuilder")}static[ai]="PgDoublePrecisionBuilder";constructor(e){super(e,"number","PgDoublePrecision")}build(e){return new Za(e,this.config)}},Za=class extends _i{static{__name(this,"PgDoublePrecision")}static[ai]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(e){return"string"==typeof e?Number.parseFloat(e):e}},__name(doublePrecision,"doublePrecision")}});function inet(e){return new tl(e??"")}var ol,sl,il=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/inet.js"(){Bt(),hi(),Oi(),tl=class extends Ti{static{__name(this,"PgInetBuilder")}static[ai]="PgInetBuilder";constructor(e){super(e,"string","PgInet")}build(e){return new nl(e,this.config)}},nl=class extends _i{static{__name(this,"PgInet")}static[ai]="PgInet";getSQLType(){return"inet"}},__name(inet,"inet")}});function integer(e){return new ol(e??"")}var al,ll,cl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/integer.js"(){Bt(),hi(),Oi(),xa(),ol=class extends Ea{static{__name(this,"PgIntegerBuilder")}static[ai]="PgIntegerBuilder";constructor(e){super(e,"number","PgInteger")}build(e){return new sl(e,this.config)}},sl=class extends _i{static{__name(this,"PgInteger")}static[ai]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(e){return"string"==typeof e?Number.parseInt(e):e}},__name(integer,"integer")}});function interval(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new al(n,r)}var ul,dl,ml=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/interval.js"(){Bt(),hi(),_a(),Oi(),al=class extends Ti{static{__name(this,"PgIntervalBuilder")}static[ai]="PgIntervalBuilder";constructor(e,t){super(e,"string","PgInterval"),this.config.intervalConfig=t}build(e){return new ll(e,this.config)}},ll=class extends _i{static{__name(this,"PgInterval")}static[ai]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){return`interval${this.fields?` ${this.fields}`:""}${this.precision?`(${this.precision})`:""}`}},__name(interval,"interval")}});function json(e){return new ul(e??"")}var pl,gl,hl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/json.js"(){Bt(),hi(),Oi(),ul=class extends Ti{static{__name(this,"PgJsonBuilder")}static[ai]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new dl(e,this.config)}},dl=class extends _i{static{__name(this,"PgJson")}static[ai]="PgJson";constructor(e,t){super(e,t)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}},__name(json,"json")}});function jsonb(e){return new pl(e??"")}var fl,yl,wl,Sl,bl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/jsonb.js"(){Bt(),hi(),Oi(),pl=class extends Ti{static{__name(this,"PgJsonbBuilder")}static[ai]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new gl(e,this.config)}},gl=class extends _i{static{__name(this,"PgJsonb")}static[ai]="PgJsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}},__name(jsonb,"jsonb")}});function line(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return r?.mode&&"tuple"!==r.mode?new wl(n):new fl(n)}var El,vl,Cl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/line.js"(){Bt(),hi(),_a(),Oi(),fl=class extends Ti{static{__name(this,"PgLineBuilder")}static[ai]="PgLineBuilder";constructor(e){super(e,"array","PgLine")}build(e){return new yl(e,this.config)}},yl=class extends _i{static{__name(this,"PgLineTuple")}static[ai]="PgLine";getSQLType(){return"line"}mapFromDriverValue(e){const[t,n,r]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(n),Number.parseFloat(r)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},wl=class extends Ti{static{__name(this,"PgLineABCBuilder")}static[ai]="PgLineABCBuilder";constructor(e){super(e,"json","PgLineABC")}build(e){return new Sl(e,this.config)}},Sl=class extends _i{static{__name(this,"PgLineABC")}static[ai]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(e){const[t,n,r]=e.slice(1,-1).split(",");return{a:Number.parseFloat(t),b:Number.parseFloat(n),c:Number.parseFloat(r)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}},__name(line,"line")}});function macaddr(e){return new El(e??"")}var kl,Tl,_l=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/macaddr.js"(){Bt(),hi(),Oi(),El=class extends Ti{static{__name(this,"PgMacaddrBuilder")}static[ai]="PgMacaddrBuilder";constructor(e){super(e,"string","PgMacaddr")}build(e){return new vl(e,this.config)}},vl=class extends _i{static{__name(this,"PgMacaddr")}static[ai]="PgMacaddr";getSQLType(){return"macaddr"}},__name(macaddr,"macaddr")}});function macaddr8(e){return new kl(e??"")}var xl,Al,Pl,Il,Ml,Rl,Nl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/macaddr8.js"(){Bt(),hi(),Oi(),kl=class extends Ti{static{__name(this,"PgMacaddr8Builder")}static[ai]="PgMacaddr8Builder";constructor(e){super(e,"string","PgMacaddr8")}build(e){return new Tl(e,this.config)}},Tl=class extends _i{static{__name(this,"PgMacaddr8")}static[ai]="PgMacaddr8";getSQLType(){return"macaddr8"}},__name(macaddr8,"macaddr8")}});function numeric(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t),o=r?.mode;return"number"===o?new Pl(n,r?.precision,r?.scale):"bigint"===o?new Ml(n,r?.precision,r?.scale):new xl(n,r?.precision,r?.scale)}var Ll,$l,Dl,Ol,Fl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/numeric.js"(){Bt(),hi(),_a(),Oi(),xl=class extends Ti{static{__name(this,"PgNumericBuilder")}static[ai]="PgNumericBuilder";constructor(e,t,n){super(e,"string","PgNumeric"),this.config.precision=t,this.config.scale=n}build(e){return new Al(e,this.config)}},Al=class extends _i{static{__name(this,"PgNumeric")}static[ai]="PgNumeric";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return"string"==typeof e?e:String(e)}getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}},Pl=class extends Ti{static{__name(this,"PgNumericNumberBuilder")}static[ai]="PgNumericNumberBuilder";constructor(e,t,n){super(e,"number","PgNumericNumber"),this.config.precision=t,this.config.scale=n}build(e){return new Il(e,this.config)}},Il=class extends _i{static{__name(this,"PgNumericNumber")}static[ai]="PgNumericNumber";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}},Ml=class extends Ti{static{__name(this,"PgNumericBigIntBuilder")}static[ai]="PgNumericBigIntBuilder";constructor(e,t,n){super(e,"bigint","PgNumericBigInt"),this.config.precision=t,this.config.scale=n}build(e){return new Rl(e,this.config)}},Rl=class extends _i{static{__name(this,"PgNumericBigInt")}static[ai]="PgNumericBigInt";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}},__name(numeric,"numeric")}});function point(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return r?.mode&&"tuple"!==r.mode?new Dl(n):new Ll(n)}var jl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/point.js"(){Bt(),hi(),_a(),Oi(),Ll=class extends Ti{static{__name(this,"PgPointTupleBuilder")}static[ai]="PgPointTupleBuilder";constructor(e){super(e,"array","PgPointTuple")}build(e){return new $l(e,this.config)}},$l=class extends _i{static{__name(this,"PgPointTuple")}static[ai]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(e){if("string"==typeof e){const[t,n]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(n)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},Dl=class extends Ti{static{__name(this,"PgPointObjectBuilder")}static[ai]="PgPointObjectBuilder";constructor(e){super(e,"json","PgPointObject")}build(e){return new Ol(e,this.config)}},Ol=class extends _i{static{__name(this,"PgPointObject")}static[ai]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(e){if("string"==typeof e){const[t,n]=e.slice(1,-1).split(",");return{x:Number.parseFloat(t),y:Number.parseFloat(n)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}},__name(point,"point")}});function hexToBytes(e){const t=[];for(let n=0;n<e.length;n+=2)t.push(Number.parseInt(e.slice(n,n+2),16));return new Uint8Array(t)}function bytesToFloat64(e,t){const n=new ArrayBuffer(8),r=new DataView(n);for(let n=0;n<8;n++)r.setUint8(n,e[t+n]);return r.getFloat64(0,!0)}function parseEWKB(e){const t=hexToBytes(e);let n=0;const r=t[n];n+=1;const o=new DataView(t.buffer),s=o.getUint32(n,1===r);if(n+=4,536870912&s&&(o.getUint32(n,1===r),n+=4),1==(65535&s)){const e=bytesToFloat64(t,n);n+=8;const r=bytesToFloat64(t,n);return n+=8,[e,r]}throw new Error("Unsupported geometry type")}var Ul,Bl,ql,zl,Hl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js"(){Bt(),__name(hexToBytes,"hexToBytes"),__name(bytesToFloat64,"bytesToFloat64"),__name(parseEWKB,"parseEWKB")}});function geometry(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return r?.mode&&"tuple"!==r.mode?new ql(n):new Ul(n)}var Wl,Gl,Vl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js"(){Bt(),hi(),_a(),Oi(),Hl(),Ul=class extends Ti{static{__name(this,"PgGeometryBuilder")}static[ai]="PgGeometryBuilder";constructor(e){super(e,"array","PgGeometry")}build(e){return new Bl(e,this.config)}},Bl=class extends _i{static{__name(this,"PgGeometry")}static[ai]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){return parseEWKB(e)}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},ql=class extends Ti{static{__name(this,"PgGeometryObjectBuilder")}static[ai]="PgGeometryObjectBuilder";constructor(e){super(e,"json","PgGeometryObject")}build(e){return new zl(e,this.config)}},zl=class extends _i{static{__name(this,"PgGeometryObject")}static[ai]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){const t=parseEWKB(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}},__name(geometry,"geometry")}});function real(e){return new Wl(e??"")}var Kl,Ql,Yl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/real.js"(){Bt(),hi(),Oi(),Wl=class extends Ti{static{__name(this,"PgRealBuilder")}static[ai]="PgRealBuilder";constructor(e,t){super(e,"number","PgReal"),this.config.length=t}build(e){return new Gl(e,this.config)}},Gl=class extends _i{static{__name(this,"PgReal")}static[ai]="PgReal";constructor(e,t){super(e,t)}getSQLType(){return"real"}mapFromDriverValue=__name(e=>"string"==typeof e?Number.parseFloat(e):e,"mapFromDriverValue")},__name(real,"real")}});function serial(e){return new Kl(e??"")}var Jl,Xl,Zl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/serial.js"(){Bt(),hi(),Oi(),Kl=class extends Ti{static{__name(this,"PgSerialBuilder")}static[ai]="PgSerialBuilder";constructor(e){super(e,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Ql(e,this.config)}},Ql=class extends _i{static{__name(this,"PgSerial")}static[ai]="PgSerial";getSQLType(){return"serial"}},__name(serial,"serial")}});function smallint(e){return new Jl(e??"")}var ec,tc,nc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/smallint.js"(){Bt(),hi(),Oi(),xa(),Jl=class extends Ea{static{__name(this,"PgSmallIntBuilder")}static[ai]="PgSmallIntBuilder";constructor(e){super(e,"number","PgSmallInt")}build(e){return new Xl(e,this.config)}},Xl=class extends _i{static{__name(this,"PgSmallInt")}static[ai]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=__name(e=>"string"==typeof e?Number(e):e,"mapFromDriverValue")},__name(smallint,"smallint")}});function smallserial(e){return new ec(e??"")}var rc,oc,sc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/smallserial.js"(){Bt(),hi(),Oi(),ec=class extends Ti{static{__name(this,"PgSmallSerialBuilder")}static[ai]="PgSmallSerialBuilder";constructor(e){super(e,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new tc(e,this.config)}},tc=class extends _i{static{__name(this,"PgSmallSerial")}static[ai]="PgSmallSerial";getSQLType(){return"smallserial"}},__name(smallserial,"smallserial")}});function text(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new rc(n,r)}var ic,ac,lc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/text.js"(){Bt(),hi(),_a(),Oi(),rc=class extends Ti{static{__name(this,"PgTextBuilder")}static[ai]="PgTextBuilder";constructor(e,t){super(e,"string","PgText"),this.config.enumValues=t.enum}build(e){return new oc(e,this.config)}},oc=class extends _i{static{__name(this,"PgText")}static[ai]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}},__name(text,"text")}});function time(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new ic(n,r.withTimezone??!1,r.precision)}var cc,uc,dc,mc,pc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/time.js"(){Bt(),hi(),_a(),Oi(),Ja(),ic=class extends Wa{static{__name(this,"PgTimeBuilder")}constructor(e,t,n){super(e,"string","PgTime"),this.withTimezone=t,this.precision=n,this.config.withTimezone=t,this.config.precision=n}static[ai]="PgTimeBuilder";build(e){return new ac(e,this.config)}},ac=class extends _i{static{__name(this,"PgTime")}static[ai]="PgTime";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${void 0===this.precision?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}},__name(time,"time")}});function timestamp(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"string"===r?.mode?new dc(n,r.withTimezone??!1,r.precision):new cc(n,r?.withTimezone??!1,r?.precision)}var gc,hc,fc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/timestamp.js"(){Bt(),hi(),_a(),Oi(),Ja(),cc=class extends Wa{static{__name(this,"PgTimestampBuilder")}static[ai]="PgTimestampBuilder";constructor(e,t,n){super(e,"date","PgTimestamp"),this.config.withTimezone=t,this.config.precision=n}build(e){return new uc(e,this.config)}},uc=class extends _i{static{__name(this,"PgTimestamp")}static[ai]="PgTimestamp";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${void 0===this.precision?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){return"string"==typeof e?new Date(this.withTimezone?e:e+"+0000"):e}mapToDriverValue=__name(e=>e.toISOString(),"mapToDriverValue")},dc=class extends Wa{static{__name(this,"PgTimestampStringBuilder")}static[ai]="PgTimestampStringBuilder";constructor(e,t,n){super(e,"string","PgTimestampString"),this.config.withTimezone=t,this.config.precision=n}build(e){return new mc(e,this.config)}},mc=class extends _i{static{__name(this,"PgTimestampString")}static[ai]="PgTimestampString";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${void 0===this.precision?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){if("string"==typeof e)return e;const t=e.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){const n=e.getTimezoneOffset();return`${t}${n<=0?"+":"-"}${Math.floor(Math.abs(n)/60).toString().padStart(2,"0")}`}return t}},__name(timestamp,"timestamp")}});function uuid(e){return new gc(e??"")}var yc,wc,Sc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/uuid.js"(){Bt(),hi(),ga(),Oi(),gc=class extends Ti{static{__name(this,"PgUUIDBuilder")}static[ai]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(sql`gen_random_uuid()`)}build(e){return new hc(e,this.config)}},hc=class extends _i{static{__name(this,"PgUUID")}static[ai]="PgUUID";getSQLType(){return"uuid"}},__name(uuid,"uuid")}});function varchar(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new yc(n,r)}var bc,Ec,vc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/varchar.js"(){Bt(),hi(),_a(),Oi(),yc=class extends Ti{static{__name(this,"PgVarcharBuilder")}static[ai]="PgVarcharBuilder";constructor(e,t){super(e,"string","PgVarchar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new wc(e,this.config)}},wc=class extends _i{static{__name(this,"PgVarchar")}static[ai]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"varchar":`varchar(${this.length})`}},__name(varchar,"varchar")}});function bit(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new bc(n,r)}var Cc,kc,Tc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js"(){Bt(),hi(),_a(),Oi(),bc=class extends Ti{static{__name(this,"PgBinaryVectorBuilder")}static[ai]="PgBinaryVectorBuilder";constructor(e,t){super(e,"string","PgBinaryVector"),this.config.dimensions=t.dimensions}build(e){return new Ec(e,this.config)}},Ec=class extends _i{static{__name(this,"PgBinaryVector")}static[ai]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}},__name(bit,"bit")}});function halfvec(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new Cc(n,r)}var _c,xc,Ac=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js"(){Bt(),hi(),_a(),Oi(),Cc=class extends Ti{static{__name(this,"PgHalfVectorBuilder")}static[ai]="PgHalfVectorBuilder";constructor(e,t){super(e,"array","PgHalfVector"),this.config.dimensions=t.dimensions}build(e){return new kc(e,this.config)}},kc=class extends _i{static{__name(this,"PgHalfVector")}static[ai]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(e=>Number.parseFloat(e))}},__name(halfvec,"halfvec")}});function sparsevec(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new _c(n,r)}var Pc,Ic,Mc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js"(){Bt(),hi(),_a(),Oi(),_c=class extends Ti{static{__name(this,"PgSparseVectorBuilder")}static[ai]="PgSparseVectorBuilder";constructor(e,t){super(e,"string","PgSparseVector"),this.config.dimensions=t.dimensions}build(e){return new xc(e,this.config)}},xc=class extends _i{static{__name(this,"PgSparseVector")}static[ai]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}},__name(sparsevec,"sparsevec")}});function vector(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new Pc(n,r)}var Rc,Nc,Lc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js"(){Bt(),hi(),_a(),Oi(),Pc=class extends Ti{static{__name(this,"PgVectorBuilder")}static[ai]="PgVectorBuilder";constructor(e,t){super(e,"array","PgVector"),this.config.dimensions=t.dimensions}build(e){return new Ic(e,this.config)}},Ic=class extends _i{static{__name(this,"PgVector")}static[ai]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(e=>Number.parseFloat(e))}},__name(vector,"vector")}}),$c=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/index.js"(){Bt(),Ra(),$a(),Fa(),Ba(),Ha(),Oi(),Ya(),el(),rl(),Ji(),il(),xa(),cl(),ml(),hl(),bl(),Cl(),_l(),Nl(),Fl(),jl(),Vl(),Yl(),Zl(),nc(),sc(),lc(),pc(),fc(),Sc(),vc(),Tc(),Ac(),Mc(),Lc()}}),Dc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/query-promise.js"(){Bt(),hi(),Rc=class{static{__name(this,"QueryPromise")}static[ai]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}}}),Oc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/selection-proxy.js"(){Bt(),ya(),fi(),hi(),ga(),Xi(),ta(),Nc=class _SelectionProxyHandler{static{__name(this,"SelectionProxyHandler")}static[ai]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if("_"===t)return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===Bi)return{...e[Bi],selectedFields:new Proxy(e[Bi].selectedFields,this)};if("symbol"==typeof t)return e[t];const n=(is(e,Fi)?e._.selectedFields:is(e,ua)?e[Bi].selectedFields:e)[t];if(is(n,ra.Aliased)){if("sql"===this.config.sqlAliasedBehavior&&!n.isSelectionField)return n.sql;const e=n.clone();return e.isSelectionField=!0,e}if(is(n,ra)){if("sql"===this.config.sqlBehavior)return n;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(n,ui)?this.config.alias?new Proxy(n,new ma(new Proxy(n.table,new pa(this.config.alias,this.config.replaceOriginalName??!1)))):n:"object"!=typeof n||null===n?n:new Proxy(n,new _SelectionProxyHandler(this.config))}}}});function getPgColumnBuilders(){return{bigint:bigint,bigserial:bigserial,boolean:boolean,char:char,cidr:cidr,customType:customType,date:date,doublePrecision:doublePrecision,inet:inet,integer:integer,interval:interval,json:json,jsonb:jsonb,line:line,macaddr:macaddr,macaddr8:macaddr8,numeric:numeric,point:point,geometry:geometry,real:real,serial:serial,smallint:smallint,smallserial:smallserial,text:text,time:time,timestamp:timestamp,uuid:uuid,varchar:varchar,bit:bit,halfvec:halfvec,sparsevec:sparsevec,vector:vector}}var Fc,jc,Uc,Bc,qc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/all.js"(){Bt(),Ra(),$a(),Fa(),Ba(),Ha(),Ya(),el(),rl(),il(),cl(),ml(),hl(),bl(),Cl(),_l(),Nl(),Fl(),jl(),Vl(),Yl(),Zl(),nc(),sc(),lc(),pc(),fc(),Sc(),vc(),Tc(),Ac(),Mc(),Lc(),__name(getPgColumnBuilders,"getPgColumnBuilders")}});function pgTableWithSchema(e,t,n,r,o=e){const s=new Uc(e,r,o),i="function"==typeof t?t(getPgColumnBuilders()):t,a=Object.fromEntries(Object.entries(i).map(([e,t])=>{const n=t;n.setName(e);const r=n.build(s);return s[Fc].push(...n.buildForeignKeys(r,s)),[e,r]})),l=Object.fromEntries(Object.entries(i).map(([e,t])=>{const n=t;return n.setName(e),[e,n.buildExtraConfigColumn(s)]})),u=Object.assign(s,a);return u[Yi.Symbol.Columns]=a,u[Yi.Symbol.ExtraConfigColumns]=l,n&&(u[Uc.Symbol.ExtraConfigBuilder]=n),Object.assign(u,{enableRLS:__name(()=>(u[Uc.Symbol.EnableRLS]=!0,u),"enableRLS")})}var zc,Hc,Wc,Gc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/table.js"(){Bt(),hi(),da(),qc(),Fc=Symbol.for("drizzle:PgInlineForeignKeys"),jc=Symbol.for("drizzle:EnableRLS"),Uc=class extends Yi{static{__name(this,"PgTable")}static[ai]="PgTable";static Symbol=Object.assign({},Yi.Symbol,{InlineForeignKeys:Fc,EnableRLS:jc});[Fc]=[];[jc]=!1;[Yi.Symbol.ExtraConfigBuilder]=void 0;[Yi.Symbol.ExtraConfigColumns]={}},__name(pgTableWithSchema,"pgTableWithSchema"),Bc=__name((e,t,n)=>pgTableWithSchema(e,t,n,void 0),"pgTable")}});function index(e){return new zc(!1,e)}function uniqueIndex(e){return new zc(!0,e)}var Vc,Kc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/indexes.js"(){Bt(),ga(),hi(),$c(),zc=class{static{__name(this,"IndexBuilderOn")}constructor(e,t){this.unique=e,this.name=t}static[ai]="PgIndexBuilderOn";on(...e){return new Hc(e.map(e=>{if(is(e,ra))return e;const t=new Ai(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...e){return new Hc(e.map(e=>{if(is(e,ra))return e;const t=new Ai(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=e.defaultConfig,t}),this.unique,!0,this.name)}using(e,...t){return new Hc(t.map(e=>{if(is(e,ra))return e;const t=new Ai(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!0,this.name,e)}},Hc=class{static{__name(this,"IndexBuilder")}static[ai]="PgIndexBuilder";config;constructor(e,t,n,r,o="btree"){this.config={name:r,columns:e,unique:t,only:n,method:o}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new Wc(this.config,e)}},Wc=class{static{__name(this,"Index")}static[ai]="PgIndex";config;constructor(e,t){this.config={...e,table:t}}},__name(index,"index"),__name(uniqueIndex,"uniqueIndex")}});function pgPolicy(e,t){return new Vc(e,t)}var Qc,Yc,Jc,Xc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/policies.js"(){Bt(),hi(),Vc=class{static{__name(this,"PgPolicy")}constructor(e,t){this.name=e,t&&(this.as=t.as,this.for=t.for,this.to=t.to,this.using=t.using,this.withCheck=t.withCheck)}static[ai]="PgPolicy";as;for;to;using;withCheck;_linkedTable;link(e){return this._linkedTable=e,this}},__name(pgPolicy,"pgPolicy")}}),Zc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/primary-keys.js"(){Bt(),hi(),Gc(),class{static{__name(this,"PrimaryKeyBuilder")}static[ai]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Qc(e,this.columns,this.name)}},Qc=class{static{__name(this,"PrimaryKey")}constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static[ai]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Uc.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}}}),eu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/view-common.js"(){Bt(),Yc=Symbol.for("drizzle:PgViewConfig")}});function toSnakeCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function toCamelCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,t,n)=>e+(0===n?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),"")}function noopCase(e){return e}var tu,nu,ru,ou,su,iu,au,lu,cu,uu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/casing.js"(){Bt(),hi(),da(),__name(toSnakeCase,"toSnakeCase"),__name(toCamelCase,"toCamelCase"),__name(noopCase,"noopCase"),Jc=class{static{__name(this,"CasingCache")}static[ai]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert="snake_case"===e?toSnakeCase:"camelCase"===e?toCamelCase:noopCase}getColumnCasing(e){if(!e.keyAsName)return e.name;const t=`${e.table[Yi.Symbol.Schema]??"public"}.${e.table[Yi.Symbol.OriginalName]}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){const t=`${e[Yi.Symbol.Schema]??"public"}.${e[Yi.Symbol.OriginalName]}`;if(!this.cachedTables[t]){for(const n of Object.values(e[Yi.Symbol.Columns])){const e=`${t}.${n.name}`;this.cache[e]=this.convert(n.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}}}),du=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/errors.js"(){Bt(),hi(),tu=class extends Error{static{__name(this,"DrizzleError")}static[ai]="DrizzleError";constructor({message:e,cause:t}){super(e),this.name="DrizzleError",this.cause=t}},nu=class _DrizzleQueryError extends Error{static{__name(this,"DrizzleQueryError")}constructor(e,t,n){super(`Failed query: ${e}\nparams: ${t}`),this.query=e,this.params=t,this.cause=n,Error.captureStackTrace(this,_DrizzleQueryError),n&&(this.cause=n)}},ru=class extends tu{static{__name(this,"TransactionRollbackError")}static[ai]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}}});function bindIfParam(e,t){return!isDriverValueEncoder(t)||isSQLWrapper(e)||is(e,aa)||is(e,la)||is(e,ui)||is(e,Yi)||is(e,ua)?e:new aa(e,t)}function and(...e){const t=e.filter(e=>void 0!==e);if(0!==t.length)return 1===t.length?new ra(t):new ra([new na("("),sql.join(t,new na(" and ")),new na(")")])}function or(...e){const t=e.filter(e=>void 0!==e);if(0!==t.length)return 1===t.length?new ra(t):new ra([new na("("),sql.join(t,new na(" or ")),new na(")")])}function not(e){return sql`not ${e}`}function inArray(e,t){return Array.isArray(t)?0===t.length?sql`false`:sql`${e} in ${t.map(t=>bindIfParam(t,e))}`:sql`${e} in ${bindIfParam(t,e)}`}function notInArray(e,t){return Array.isArray(t)?0===t.length?sql`true`:sql`${e} not in ${t.map(t=>bindIfParam(t,e))}`:sql`${e} not in ${bindIfParam(t,e)}`}function isNull(e){return sql`${e} is null`}function isNotNull(e){return sql`${e} is not null`}function exists(e){return sql`exists ${e}`}function notExists(e){return sql`not exists ${e}`}function between(e,t,n){return sql`${e} between ${bindIfParam(t,e)} and ${bindIfParam(n,e)}`}function notBetween(e,t,n){return sql`${e} not between ${bindIfParam(t,e)} and ${bindIfParam(n,e)}`}function like(e,t){return sql`${e} like ${t}`}function notLike(e,t){return sql`${e} not like ${t}`}function ilike(e,t){return sql`${e} ilike ${t}`}function notIlike(e,t){return sql`${e} not ilike ${t}`}var mu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/expressions/conditions.js"(){Bt(),fi(),hi(),da(),ga(),__name(bindIfParam,"bindIfParam"),ou=__name((e,t)=>sql`${e} = ${bindIfParam(t,e)}`,"eq"),su=__name((e,t)=>sql`${e} <> ${bindIfParam(t,e)}`,"ne"),__name(and,"and"),__name(or,"or"),__name(not,"not"),iu=__name((e,t)=>sql`${e} > ${bindIfParam(t,e)}`,"gt"),au=__name((e,t)=>sql`${e} >= ${bindIfParam(t,e)}`,"gte"),lu=__name((e,t)=>sql`${e} < ${bindIfParam(t,e)}`,"lt"),cu=__name((e,t)=>sql`${e} <= ${bindIfParam(t,e)}`,"lte"),__name(inArray,"inArray"),__name(notInArray,"notInArray"),__name(isNull,"isNull"),__name(isNotNull,"isNotNull"),__name(exists,"exists"),__name(notExists,"notExists"),__name(between,"between"),__name(notBetween,"notBetween"),__name(like,"like"),__name(notLike,"notLike"),__name(ilike,"ilike"),__name(notIlike,"notIlike")}});function asc(e){return sql`${e} asc`}function desc(e){return sql`${e} desc`}var pu,gu,hu,fu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/expressions/select.js"(){Bt(),ga(),__name(asc,"asc"),__name(desc,"desc")}}),yu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/expressions/index.js"(){Bt(),mu(),fu()}});function getOperators(){return{and:and,between:between,eq:ou,exists:exists,gt:iu,gte:au,ilike:ilike,inArray:inArray,isNull:isNull,isNotNull:isNotNull,like:like,lt:lu,lte:cu,ne:su,not:not,notBetween:notBetween,notExists:notExists,notLike:notLike,notIlike:notIlike,notInArray:notInArray,or:or,sql:sql}}function getOrderByOperators(){return{sql:sql,asc:asc,desc:desc}}function normalizeRelation(e,t,n){if(is(n,gu)&&n.config)return{fields:n.config.fields,references:n.config.references};const r=t[getTableUniqueName(n.referencedTable)];if(!r)throw new Error(`Table "${n.referencedTable[Yi.Symbol.Name]}" not found in schema`);const o=e[r];if(!o)throw new Error(`Table "${r}" not found in schema`);const s=n.sourceTable,i=t[getTableUniqueName(s)];if(!i)throw new Error(`Table "${s[Yi.Symbol.Name]}" not found in schema`);const a=[];for(const e of Object.values(o.relations))(n.relationName&&n!==e&&e.relationName===n.relationName||!n.relationName&&e.referencedTable===n.sourceTable)&&a.push(e);if(a.length>1)throw n.relationName?new Error(`There are multiple relations with name "${n.relationName}" in table "${r}"`):new Error(`There are multiple relations between "${r}" and "${n.sourceTable[Yi.Symbol.Name]}". Please specify relation name`);if(a[0]&&is(a[0],gu)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw new Error(`There is not enough information to infer relation "${i}.${n.fieldName}"`)}function mapRelationalRow(e,t,n,r,o=e=>e){const s={};for(const[i,a]of r.entries())if(a.isJson){const r=t.relations[a.tsKey],l=n[i],u="string"==typeof l?JSON.parse(l):l;s[a.tsKey]=is(r,gu)?u&&mapRelationalRow(e,e[a.relationTableTsKey],u,a.selection,o):u.map(t=>mapRelationalRow(e,e[a.relationTableTsKey],t,a.selection,o))}else{const e=o(n[i]),t=a.field;let r;r=is(t,ui)?t:is(t,ra)?t.decoder:t.sql.decoder,s[a.tsKey]=null===e?null:r.mapFromDriverValue(e)}return s}var wu,Su,bu,Eu,vu,Cu,ku,Tu,_u,xu,Au,Pu,Iu,Mu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/relations.js"(){Bt(),da(),fi(),hi(),yu(),ga(),pu=class{static{__name(this,"Relation")}constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[Yi.Symbol.Name]}static[ai]="Relation";referencedTableName;fieldName},class{static{__name(this,"Relations")}constructor(e,t){this.table=e,this.config=t}static[ai]="Relations"},gu=class _One extends pu{static{__name(this,"One")}constructor(e,t,n,r){super(e,t,n?.relationName),this.config=n,this.isNullable=r}static[ai]="One";withFieldName(e){const t=new _One(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}},hu=class _Many extends pu{static{__name(this,"Many")}constructor(e,t,n){super(e,t,n?.relationName),this.config=n}static[ai]="Many";withFieldName(e){const t=new _Many(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}},__name(getOperators,"getOperators"),__name(getOrderByOperators,"getOrderByOperators"),__name(normalizeRelation,"normalizeRelation"),__name(mapRelationalRow,"mapRelationalRow")}}),Ru=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/functions/aggregate.js"(){Bt()}}),Nu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/functions/vector.js"(){Bt()}}),Lu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/functions/index.js"(){Bt(),Ru(),Nu()}}),$u=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/index.js"(){Bt(),yu(),Lu(),ga()}}),Du=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/view-base.js"(){Bt(),hi(),ga(),wu=class extends ua{static{__name(this,"PgViewBase")}static[ai]="PgViewBase"}}}),Ou=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/dialect.js"(){Bt(),ya(),uu(),fi(),hi(),du(),$c(),Gc(),Mu(),$u(),ga(),Xi(),da(),_a(),ta(),Du(),Su=class{static{__name(this,"PgDialect")}static[ai]="PgDialect";casing;constructor(e){this.casing=new Jc(e?.casing)}async migrate(e,t,n){const r="string"==typeof n?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",o="string"==typeof n?"drizzle":n.migrationsSchema??"drizzle",s=sql`
2
+ import*as e from"path";import t,{join as n,dirname as r,parse as o,relative as s,isAbsolute as i,resolve as a,extname as l,basename as u}from"path";import{fileURLToPath as d,pathToFileURL as m,URL as g}from"url";import h,{z as f,ZodError as y}from"zod";import*as w from"os";import S,{tmpdir as E,homedir as v}from"os";import*as C from"fs/promises";import k,{mkdir as T,writeFile as _,rm as x,readFile as A,unlink as P,readdir as I}from"fs/promises";import*as M from"crypto";import R,{randomUUID as N,createHash as L}from"crypto";import*as $ from"fs";import D,{existsSync as O,promises as F,readFileSync as j,constants as U,mkdirSync as B,writeFileSync as q,statSync as z,readdirSync as H,createReadStream as W,appendFileSync as G}from"fs";import*as V from"http";import{createServer as K}from"http";import{Box as Q,Text as Y,Static as J,useStdout as X,useInput as Z,render as ee,useApp as te,Newline as ne}from"ink";import re,{memo as oe,useState as se,useRef as ie,useEffect as ae,useMemo as le,useCallback as ce}from"react";import ue from"chalk";import de from"picocolors";import me from"strip-ansi";import{Jimp as pe,JimpMime as ge}from"jimp";import he from"open";import fe from"@opentelemetry/sdk-node";import ye from"@opentelemetry/exporter-trace-otlp-http";import we from"@opentelemetry/resources";import Se from"@opentelemetry/semantic-conventions";import be from"@opentelemetry/sdk-trace-node";import{exec as Ee,spawn as ve,execSync as Ce,execFileSync as ke,execFile as Te,spawnSync as _e}from"child_process";import{trace as xe,context as Ae,SpanKind as Pe,SpanStatusCode as Ie}from"@opentelemetry/api";import{v4 as Me}from"uuid";import Re from"figures";import{Command as Ne,Option as Le,InvalidArgumentError as $e}from"commander";import De from"ora";import*as Oe from"net";import Fe from"net";import je from"tls";import Ue from"stream";import{performance as Be}from"perf_hooks";import qe from"gray-matter";import ze from"@sindresorhus/slugify";import{EventEmitter as He}from"events";import We from"ink-spinner";import*as Ge from"@clack/prompts";import{multiselect as Ve,confirm as Ke,note as Qe,cancel as Ye,select as Je,isCancel as Xe,password as Ze}from"@clack/prompts";import"dotenv/config";import et from"dedent";import tt from"log-symbols";import{minimatch as nt}from"minimatch";import{glob as rt}from"glob";import{parse as ot,quote as st}from"shell-quote";import it from"ignore";import{createRequire as at}from"module";import lt from"ansi-escapes";import ct from"string-width";import*as ut from"readline";import dt from"readline";import mt from"semver";import{promisify as pt}from"util";import{inflateRawSync as gt}from"zlib";import ht from"strip-json-comments";import ft from"ink-select-input";import{Marked as yt}from"marked";import wt from"marked-terminal";import*as St from"diff";import bt from"is-unicode-supported";import Et from"open-editor";import{wrapAnsi as vt}from"fast-wrap-ansi";import Ct from"terminal-link";import*as kt from"process";var Tt,_t,xt,At,Pt,It,Mt,Rt,Nt,Lt,$t,Dt,Ot,Ft,jt=Object.defineProperty,Ut=Object.getOwnPropertyNames,__name=(e,t)=>jt(e,"name",{value:t,configurable:!0}),__esm=(e,t)=>function __init(){return e&&(t=(0,e[Ut(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)jt(e,n,{get:t[n],enumerable:!0})},Bt=__esm({"../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.12_tsx@4.21.0_typescript@5.9.3_yaml@2.8.3/node_modules/tsup/assets/esm_shims.js"(){}}),qt=__esm({"../shared/src/constants/tracing.ts"(){Bt(),Tt="command_code_cli_tracing"}});function isContentCaptureEnabled(){const e=process.env[Ft];return"1"===e||"true"===e}var zt,Ht,Wt,Gt,Vt,Kt,Qt,Yt,Jt,Xt,Zt,en,tn,nn,rn,on,sn,an,ln,cn,un,dn,mn,pn,gn,hn,fn,yn,wn,Sn,bn,En,vn,Cn,kn=__esm({"src/utils/telemetry/constants.ts"(){Bt(),qt(),_t="https://api.axiom.co/v1/traces",xt="xaat-818bfed7-bc54-45bc-8bfa-d1198174064a",At="xaat-fde9e569-4a3c-4994-aa0d-7a632332d220",Pt="xaat-add69148-8f73-4833-921d-bc843285c95f",It="command-code-cli",Mt=2e3,Rt=512,Nt=128,Lt=500,$t=5e3,Dt={PROVIDER_NAME:"gen_ai.provider.name",OPERATION_NAME:"gen_ai.operation.name",CONVERSATION_ID:"gen_ai.conversation.id",CAPABILITY_NAME:"gen_ai.capability.name",STEP_NAME:"gen_ai.step.name",TOOL_NAME:"gen_ai.tool.name",REQUEST_MODEL:"gen_ai.request.model",REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",REQUEST_TEMPERATURE:"gen_ai.request.temperature",REQUEST_TOP_P:"gen_ai.request.top_p",RESPONSE_MODEL:"gen_ai.response.model",RESPONSE_ID:"gen_ai.response.id",RESPONSE_FINISH_REASONS:"gen_ai.response.finish_reasons",USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",USAGE_CACHED_INPUT_TOKENS:"gen_ai.usage.cached_input_tokens"},Ot={ORG_LOGIN:"cmd.org.login",ORG_ID:"cmd.org.id",COMMAND_NAME:"cmd.command.name",COMMAND_ARGS:"cmd.command.args",SESSION_PROJECT_HASH:"cmd.session.project_hash",SESSION_BRANCH_HASH:"cmd.session.branch_hash",ITERATION_NUMBER:"cmd.iteration.number",ITERATION_OUTCOME:"cmd.iteration.outcome",ITERATION_TERMINAL_ERROR_TYPE:"cmd.iteration.terminal_error_type",ITERATION_TERMINAL_ERROR_MESSAGE:"cmd.iteration.terminal_error_message",ITERATION_INITIAL_MESSAGE_COUNT:"cmd.iteration.initial_message_count",PAYLOAD_MESSAGE_COUNT:"cmd.payload.message_count",PAYLOAD_USER_MESSAGE_COUNT:"cmd.payload.user_message_count",PAYLOAD_ASSISTANT_MESSAGE_COUNT:"cmd.payload.assistant_message_count",PAYLOAD_TOOL_MESSAGE_COUNT:"cmd.payload.tool_message_count",PAYLOAD_ASSISTANT_WITH_TOOL_USE_COUNT:"cmd.payload.assistant_with_tool_use_count",PAYLOAD_TOOL_USE_COUNT:"cmd.payload.tool_use_count",PAYLOAD_TOOL_RESULT_COUNT:"cmd.payload.tool_result_count",PAYLOAD_ORPHAN_TOOL_USE_COUNT:"cmd.payload.orphan_tool_use_count",PAYLOAD_ORPHAN_TOOL_RESULT_COUNT:"cmd.payload.orphan_tool_result_count",PAYLOAD_LAST_MESSAGE_ROLE:"cmd.payload.last_message_role",API_ATTEMPT_NUMBER:"cmd.api.attempt.number",API_ATTEMPT_DELAY_MS_BEFORE:"cmd.api.attempt.delay_ms_before",API_ATTEMPT_STATUS:"cmd.api.attempt.status",API_ATTEMPT_HTTP_STATUS:"cmd.api.attempt.http_status",API_ATTEMPT_IS_RETRYABLE:"cmd.api.attempt.is_retryable",API_ATTEMPT_ERROR_TYPE:"cmd.api.attempt.error_type",API_ATTEMPT_ERROR_MESSAGE:"cmd.api.attempt.error_message",SANITIZE_UNMATCHED_COUNT:"cmd.sanitize.unmatched_count",SANITIZE_TOOL_NAMES:"cmd.sanitize.tool_names",SANITIZE_NEXT_MESSAGE_ROLE:"cmd.sanitize.next_message_role",ERROR_FINGERPRINT:"cmd.error.fingerprint",ERROR_COMPONENT:"cmd.error.component",ERROR_HEADING:"cmd.error.heading",ERROR_CODE:"cmd.error.code"},Ft="COMMAND_CODE_TELEMETRY_CAPTURE_CONTENT",__name(isContentCaptureEnabled,"isContentCaptureEnabled")}});function getModelCategory({provider:e,model:t}){if(e===Qt.VERCEL_AI_GATEWAY)return Zt.has(t)?"premium":"opensource";if(e===Qt.CLOUDFLARE_AI_GATEWAY||e===Qt.OPENROUTER)return"opensource";const n=en[e];if(!n)return null;const r=`${e}:${t}`,o=n.find(e=>e.id===r);return o?.category??null}function getPlanDisplayName(e){return e.replace("individual-","").replace("teams-","Teams ").split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function getMinimumPlanForModel({fullModelId:e,category:t}){for(const n of on){const r=rn[n];if(!r)continue;const o=r.allowedCategories.includes(t),s=r.blockedModels?.includes(e)??!1;if(o&&!s)return n}return null}function buildModelGroups(e){const t=Object.values(pn).filter(e=>!e.hidden),n=[];for(const r of Object.values(Sn)){if(!("co"===e?r.visibleInCoMode:r.visibleInNormalMode))continue;const o=t.filter(e=>r.supportedModelProviders.includes(e.provider));o.length>0&&n.push({providerId:r.id,label:r.label,models:o})}return n}var Tn,_n=__esm({"../shared/src/constants.ts"(){Bt(),Ht="--xco",Wt={INTERNAL_TEAM_FLAG_HEADER:`x-${(zt="--co").replace("--","")}-flag`,OAUTH_TOKEN:"x-oauth-token",OAUTH_PROVIDER:"x-oauth-provider",PROJECT_SLUG:"x-project-slug",TASTE_LEARNING:"x-taste-learning",TASTE_USAGE:"x-taste-usage",CLI_ENVIRONMENT:"x-cli-environment",CLI_VERSION:"x-command-code-version",OSS_PRIMARY_PROVIDER:"x-oss-primary-provider",SESSION_ID:"x-session-id",SYSTEM_PROMPT_BREAKDOWN:"x-system-prompt-breakdown",CMD_ZDR:"x-cmd-zdr"},Gt={V1:{CHAT_COMPLETIONS:"/provider/v1/chat/completions",MODELS:"/provider/v1/models",MESSAGES:"/provider/v1/messages"},ALPHA:{GENERATE:"/alpha/generate",WHOAMI:"/alpha/whoami",NAMESPACES:"/alpha/namespaces",AGENT:{GENERATE:"/alpha/agent/generate"},WEB_SEARCH:"/alpha/web-search",WEB_FETCH:"/alpha/web-fetch",SANDBOX:{START:"/alpha/sandbox/start",STREAM:"/alpha/sandbox/stream",STATUS:"/alpha/sandbox/status",STOP:"/alpha/sandbox/stop",SESSIONS:"/alpha/sandbox/sessions"},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"},BILLING:{CREDITS:"/alpha/billing/credits",SUBSCRIPTIONS:"/alpha/billing/subscriptions"},USAGE:{SUMMARY:"/alpha/usage/summary"},LIFECYCLE_EVENTS:{TRACK:"/alpha/lifecycle-events"},COURSES_LEAD:"/alpha/courses-lead",CONVERSIONS:{TRACK:"/alpha/conversions/track"},CONSENT:{SET:"/alpha/consent/set"}},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",BAN_USER:"/internal/admin/ban-user",BAN_ORG:"/internal/admin/ban-org",UNBAN_USER:"/internal/admin/unban-user",UNBAN_ORG:"/internal/admin/unban-org",DELETE_USER:"/internal/admin/delete-user",DELETE_ORG:"/internal/admin/delete-org",MIGRATE:{PLAN_IDS:"/internal/admin/migrations/plan-ids"}},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"},FINGERPRINT:{RECORD:"/internal/fingerprint/record"},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"},CHECKOUT_ELIGIBILITY:"/internal/billing/checkout/eligibility",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",CHARTS:"/internal/usage/charts"},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"}}}},Vt={ALPHA:{TASTE:{GET:new RegExp("/alpha/taste/[a-z0-9-]+"),UPDATE:new RegExp("/alpha/taste/[a-z0-9-]+/update"),DELETE:new RegExp("/alpha/taste/[a-z0-9-]+/rules/[a-z0-9-]+"),LIST:new RegExp("/alpha/taste/[a-z0-9-]+/rules")},PACKAGES:{FILES:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/alpha/v1/taste/packages/[a-zA-Z0-9_-]+/download")}},BETA:{TASTE_PACKAGES:{UPLOAD:new RegExp("^/beta/taste/packages/[a-zA-Z0-9_-]+$"),FILES:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),GET:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),DOWNLOAD:new RegExp("/beta/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download")}},INTERNAL:{ORGS:{GET:new RegExp("/internal/orgs/[a-zA-Z0-9_-]+"),FOLLOW:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/orgs/[a-zA-Z0-9-]+/followers")},USER:{FOLLOW:new RegExp("/internal/users/[a-zA-Z0-9-]+/follow"),FOLLOWERS:new RegExp("/internal/users/[a-zA-Z0-9-]+/followers"),FOLLOWING:new RegExp("/internal/users/[a-zA-Z0-9-]+/following")},TASTE:{PACKAGES:{GET:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+"),FILES:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/files"),DOWNLOAD:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/download"),UPDATE:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/update"),STAR:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/star"),PIN:new RegExp("/internal/taste/packages/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pin")}}}},Object.values(Vt.ALPHA.TASTE),Object.values(Vt.BETA.TASTE_PACKAGES),new RegExp("^/alpha/sandbox/status/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"),new RegExp("^/alpha/sandbox/stop/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"),new RegExp("^/alpha/sandbox/stream/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"),Gt.V1.CHAT_COMPLETIONS,Gt.V1.MESSAGES,Gt.ALPHA.GENERATE,Gt.ALPHA.AGENT.GENERATE,Gt.ALPHA.WHOAMI,Gt.ALPHA.WEB_SEARCH,Gt.ALPHA.WEB_FETCH,Gt.ALPHA.NAMESPACES,Gt.ALPHA.SANDBOX.START,Gt.ALPHA.SHARE.CREATE,Gt.ALPHA.SHARE.DELETE,Gt.ALPHA.SHARE.APPEND,Gt.ALPHA.DEVREL_THREAD.CREATE,Gt.ALPHA.DEVREL_THREAD.DELETE,Gt.ALPHA.DEVREL_THREAD.UPDATE,Gt.ALPHA.TASTE.LEARN,Gt.ALPHA.TASTE.DELETE,Gt.ALPHA.TASTE.GET,Gt.ALPHA.TASTE.UPDATE,Object.values(Gt.BETA.TASTE.PACKAGES),Gt.ALPHA.BILLING.CREDITS,Gt.ALPHA.BILLING.SUBSCRIPTIONS,Gt.ALPHA.USAGE.SUMMARY,Gt.ALPHA.LIFECYCLE_EVENTS.TRACK,Gt.INTERNAL.ADMIN.USERS,Gt.INTERNAL.ADMIN.ORGS,Gt.INTERNAL.ADMIN.ENTITY_TYPE,Gt.INTERNAL.USER.AVATAR,Gt.INTERNAL.USER.SETTINGS,Gt.INTERNAL.API_KEYS.LIST,Gt.INTERNAL.API_KEYS.CREATE,Gt.INTERNAL.API_KEYS.DELETE,Gt.INTERNAL.FINGERPRINT.RECORD,Gt.INTERNAL.USAGE.LIST,Gt.INTERNAL.USAGE.SUMMARY,Gt.INTERNAL.USAGE.CHARTS,Gt.INTERNAL.ADMIN.GRANT_CREDITS,Gt.INTERNAL.ADMIN.GRANT_ORG_CREDITS,Gt.INTERNAL.ADMIN.BAN_USER,Gt.INTERNAL.ADMIN.BAN_ORG,Gt.INTERNAL.ADMIN.UNBAN_USER,Gt.INTERNAL.ADMIN.UNBAN_ORG,Gt.INTERNAL.ADMIN.DELETE_USER,Gt.INTERNAL.ADMIN.DELETE_ORG,Gt.INTERNAL.BILLING.CREDITS.GET,Gt.INTERNAL.BILLING.CUSTOMERS.GET,Gt.INTERNAL.BILLING.CUSTOMERS.UPSERT,Gt.INTERNAL.BILLING.CUSTOMERS.SETUP_INTENT,Gt.INTERNAL.BILLING.CUSTOMERS.PAYMENT_METHOD,Gt.INTERNAL.BILLING.CUSTOMERS.SET_DEFAULT_PAYMENT_METHOD,Gt.INTERNAL.BILLING.CUSTOMERS.INVOICES,Gt.INTERNAL.BILLING.SUBSCRIPTIONS.GET,Gt.INTERNAL.BILLING.CHECKOUT_ELIGIBILITY,Gt.INTERNAL.ORGS.LIST,Gt.INTERNAL.ORGS.GET,Gt.INTERNAL.ORGS.CREATE,Gt.INTERNAL.ORGS.UPDATE,Gt.INTERNAL.ORGS.DELETE,Gt.INTERNAL.ORGS.MEMBERS.LIST,Gt.INTERNAL.ORGS.MEMBERS.ADD,Gt.INTERNAL.ORGS.MEMBERS.UPDATE,Gt.INTERNAL.ORGS.MEMBERS.REMOVE,Gt.INTERNAL.ORGS.INVITATIONS.LIST,Gt.INTERNAL.ORGS.INVITATIONS.SEND,Gt.INTERNAL.ORGS.INVITATIONS.ACCEPT,Gt.INTERNAL.ORGS.INVITATIONS.CANCEL,Gt.INTERNAL.TASTE.PACKAGES.LIST,Gt.INTERNAL.ADMIN.MIGRATE.PLAN_IDS,Object.values(Vt.INTERNAL.ORGS),Object.values(Vt.INTERNAL.USER),Object.values(Vt.INTERNAL.TASTE.PACKAGES),Kt={INTERNAL:{PROFILE:{GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+"),PACKAGES:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages"),FOLLOWING:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/following"),FOLLOWERS:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/followers"),PACKAGE_GET:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+"),PACKAGE_DOWNLOAD:new RegExp("/internal/profile/[a-zA-Z0-9_-]+/packages/[a-zA-Z0-9_-]+/download")}}},Object.values(Kt.INTERNAL.PROFILE),Yt={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},Jt=[(Qt={ANTHROPIC:"anthropic",OPENAI:"openai",BASETEN:"baseten",VERCEL_AI_GATEWAY:"vercel-ai-gateway",CLOUDFLARE_AI_GATEWAY:"cloudflare-ai-gateway",OPENROUTER:"openrouter",SPIDER_WEB:"spider_web"}).VERCEL_AI_GATEWAY,Qt.BASETEN,Qt.CLOUDFLARE_AI_GATEWAY,Qt.OPENROUTER],Xt=Jt[0],Qt.ANTHROPIC,Qt.OPENAI,Zt=new Set(["google/gemini-3.5-flash","google/gemini-3.1-flash-lite"]),en={[Qt.ANTHROPIC]:[{id:"anthropic:claude-sonnet-4-20250514",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-sonnet-4-5-20250929",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-opus-4-5-20251101",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-sonnet-4-6",provider:"Anthropic",category:"premium",promptCost:3,completionCost:15,cacheWrite5mCost:3.75,cacheWrite1hCost:6,cacheHitCost:.3},{id:"anthropic:claude-fable-5",provider:"Anthropic",category:"premium",promptCost:10,completionCost:50,cacheWrite5mCost:12.5,cacheWrite1hCost:20,cacheHitCost:1},{id:"anthropic:claude-opus-4-8",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-7",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-opus-4-6",provider:"Anthropic",category:"premium",promptCost:5,completionCost:25,cacheWrite5mCost:6.25,cacheWrite1hCost:10,cacheHitCost:.5},{id:"anthropic:claude-haiku-4-5-20251001",provider:"Anthropic",category:"premium",promptCost:1,completionCost:5,cacheWrite5mCost:1.25,cacheWrite1hCost:2,cacheHitCost:.1}],[Qt.OPENAI]:[{id:"openai:gpt-5.5",provider:"OpenAI",category:"premium",promptCost:5,completionCost:30,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4",provider:"OpenAI",category:"premium",promptCost:2.5,completionCost:15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.25},{id:"openai:gpt-5.3-codex",provider:"OpenAI",category:"premium",promptCost:2,completionCost:8,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.5},{id:"openai:gpt-5.4-mini",provider:"OpenAI",category:"premium",promptCost:.75,completionCost:4.5,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.075}],[Qt.BASETEN]:[{id:"baseten:zai-org/GLM-5",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:3.15,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.5",provider:"Baseten",category:"opensource",promptCost:.6,completionCost:3,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0},{id:"baseten:moonshotai/Kimi-K2.6",provider:"Baseten",category:"opensource",promptCost:.95,completionCost:4,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:.16},{id:"baseten:MiniMaxAI/MiniMax-M2.5",provider:"Baseten",category:"opensource",promptCost:.5,completionCost:2,cacheWrite5mCost:0,cacheWrite1hCost:0,cacheHitCost:0}],[Qt.VERCEL_AI_GATEWAY]:[],[Qt.OPENROUTER]:[]},__name(getModelCategory,"getModelCategory"),tn={"individual-go":{premium:0,opensource:10,total:10},"individual-pro":{premium:15,opensource:15,total:30},"individual-provider":{premium:15,opensource:0,total:15},"individual-max":{premium:100,opensource:50,total:150},"individual-ultra":{premium:200,opensource:100,total:300},"teams-pro":{premium:40,opensource:0,total:40}},nn={"individual-go":"Go","individual-pro":"Pro","individual-provider":"Provider","individual-max":"Max","individual-ultra":"Ultra","teams-pro":"Teams Pro"},rn={"individual-go":{allowedCategories:["opensource"]},"individual-pro":{allowedCategories:["premium","opensource"],blockedModels:["anthropic:claude-fable-5","anthropic:claude-opus-4-8","anthropic:claude-opus-4-7","anthropic:claude-opus-4-6","anthropic:claude-opus-4-5-20251101"]},"individual-provider":{allowedCategories:["premium","opensource"]},"individual-max":{allowedCategories:["premium","opensource"]},"individual-ultra":{allowedCategories:["premium","opensource"]},"teams-pro":{allowedCategories:["premium","opensource"]}},on=["individual-go","individual-pro","individual-provider","individual-max","individual-ultra","teams-pro"],__name(getPlanDisplayName,"getPlanDisplayName"),__name(getMinimumPlanForModel,"getMinimumPlanForModel"),sn=[50,75,90],h.enum(["owner","admin","member"]),an={LEARN_TASTE:"learn-taste",TASTE:"taste",TERMINAL_SETUP:"terminal-setup"},ln={MAX_PROMPT_TOKENS:25e3,MAX_PROMPT_CHARS:1e5,DB_PROMPT_MAX_WORDS:10},cn=["active","trialing","past_due"],un="chatComplete",dn="responses",mn="MiniMaxAI/MiniMax-M3-Free",(pn={SONNET_4_6:{id:"claude-sonnet-4-6",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Sonnet 4.6",name:"Claude Sonnet 4.6",description:"best combo of speed & intelligence (recommended)",reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},FABLE_5:{id:"claude-fable-5",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Fable 5",name:"Claude Fable 5",description:"most capable for demanding reasoning & long-horizon agents",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_8:{id:"claude-opus-4-8",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Opus 4.8",name:"Claude Opus 4.8",description:"most intelligent Opus for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},OPUS_4_7:{id:"claude-opus-4-7",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Opus 4.7",name:"Claude Opus 4.7",description:"prev flagship, still strong for agents and coding",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh","max"],contextWindow:1e6},HAIKU_4_5:{id:"claude-haiku-4-5-20251001",inputModalities:["text","image"],provider:Qt.ANTHROPIC,spec:un,label:"Claude Haiku 4.5",name:"Claude Haiku 4.5",description:"fastest & most compact, great for quick tasks",contextWindow:2e5},GPT_5_5:{id:"gpt-5.5",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.5",name:"GPT-5.5",description:"latest frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"]},GPT_5_4:{id:"gpt-5.4",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.4",name:"GPT-5.4",description:"frontier model for general complex work",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_3_CODEX:{id:"gpt-5.3-codex",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.3 Codex",name:"GPT-5.3 Codex",description:"frontier coding model",reasoning:!0,reasoningEfforts:["low","medium","high","xhigh"],contextWindow:4e5},GPT_5_4_MINI:{id:"gpt-5.4-mini",inputModalities:["text","image"],provider:Qt.OPENAI,spec:dn,label:"GPT-5.4 Mini",name:"GPT-5.4 Mini",description:"fast, cost-effective model for everyday tasks",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:4e5},MINIMAX_M3_FREE:{id:mn,inputModalities:["text","image"],provider:Xt,spec:un,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",badge:"free",hidden:!0,reasoning:!0,contextWindow:1e6},DEEPSEEK_V4_PRO:{id:"deepseek/deepseek-v4-pro",inputModalities:["text"],provider:Xt,spec:un,label:"DeepSeek V4 Pro",name:"DeepSeek V4 Pro",description:"hybrid-attention long-context reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},DEEPSEEK_V4_FLASH:{id:"deepseek/deepseek-v4-flash",inputModalities:["text"],provider:Xt,spec:un,label:"DeepSeek V4 Flash",name:"DeepSeek V4 Flash",description:"fast hybrid-attention reasoning",reasoning:!0,reasoningEfforts:["high","max"],contextWindow:1e6},KIMI_K2_7_CODE:{id:"moonshotai/Kimi-K2.7-Code",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.7 Code",name:"Kimi K2.7 Code",description:"improved long-horizon coding with vision",reasoning:!0,contextWindow:256e3},KIMI_K2_7_CODE_HIGHSPEED:{id:"moonshotai/Kimi-K2.7-Code-Highspeed",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.7 Code HighSpeed",name:"Kimi K2.7 Code HighSpeed",description:"high-speed long-horizon coding with vision",reasoning:!0,contextWindow:262e3},KIMI_K2_6:{id:"moonshotai/Kimi-K2.6",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.6",name:"Kimi K2.6",description:"long-horizon coding with vision",contextWindow:256e3},KIMI_K2_5:{id:"moonshotai/Kimi-K2.5",inputModalities:["text","image"],provider:Xt,spec:un,label:"Kimi K2.5",name:"Kimi K2.5",description:"multimodal frontend coding",contextWindow:256e3},GLM_5_2:{id:"zai-org/GLM-5.2",inputModalities:["text"],provider:Xt,spec:un,label:"GLM-5.2",name:"GLM-5.2",description:"powerful coding with 1M context and long-horizon tasks",contextWindow:1e6},GLM_5_1:{id:"zai-org/GLM-5.1",inputModalities:["text"],provider:Xt,spec:un,label:"GLM-5.1",name:"GLM-5.1",description:"long-horizon autonomous coding agent"},GLM_5:{id:"zai-org/GLM-5",inputModalities:["text"],provider:Xt,spec:un,label:"GLM-5",name:"GLM-5",description:"multi-mode thinking & long-range planning",contextWindow:2e5},MINIMAX_M3:{id:"MiniMaxAI/MiniMax-M3",inputModalities:["text","image"],provider:Xt,spec:un,label:"MiniMax M3",name:"MiniMax M3",description:"frontier coding, agents & native multimodality",reasoning:!0,contextWindow:1e6},MINIMAX_M2_7:{id:"MiniMaxAI/MiniMax-M2.7",inputModalities:["text"],provider:Xt,spec:un,label:"MiniMax M2.7",name:"MiniMax M2.7",description:"end-to-end software engineering agent"},MINIMAX_M2_5:{id:"MiniMaxAI/MiniMax-M2.5",inputModalities:["text"],provider:Xt,spec:un,label:"MiniMax M2.5",name:"MiniMax M2.5",description:"cross-platform full-stack agentic dev",contextWindow:2e5},XIAOMI_MIMO_V2_5_PRO:{id:"xiaomi/mimo-v2.5-pro",inputModalities:["text"],provider:Xt,spec:un,label:"MiMo V2.5 Pro",name:"MiMo V2.5 Pro",description:"high-capability long-context agentic coding",contextWindow:1e6},XIAOMI_MIMO_V2_5:{id:"xiaomi/mimo-v2.5",inputModalities:["text","image"],provider:Xt,spec:un,label:"MiMo V2.5",name:"MiMo V2.5",description:"efficient long-context agentic coding",contextWindow:1e6},QWEN_3_6_MAX_PREVIEW:{id:"Qwen/Qwen3.6-Max-Preview",inputModalities:["text"],provider:Xt,spec:un,label:"Qwen 3.6 Max Preview",name:"Qwen 3.6 Max Preview",description:"vibe coding & efficient agent execution",reasoning:!0},QWEN_3_6_PLUS:{id:"Qwen/Qwen3.6-Plus",inputModalities:["text","image"],provider:Xt,spec:un,label:"Qwen 3.6 Plus",name:"Qwen 3.6 Plus",description:"agentic coding & reasoning",reasoning:!0},QWEN_3_7_MAX:{id:"Qwen/Qwen3.7-Max",inputModalities:["text"],provider:Xt,spec:un,label:"Qwen 3.7 Max",name:"Qwen 3.7 Max",description:"frontier coding & long-horizon agent execution",reasoning:!0,contextWindow:1e6},QWEN_3_7_PLUS:{id:"Qwen/Qwen3.7-Plus",inputModalities:["text","image"],provider:Xt,spec:un,label:"Qwen 3.7 Plus",name:"Qwen 3.7 Plus",description:"agentic coding & reasoning at lower cost",reasoning:!0,contextWindow:1e6},STEP_3_7_FLASH:{id:"stepfun/Step-3.7-Flash",inputModalities:["text","image"],provider:Xt,spec:un,label:"Step 3.7 Flash",name:"Step 3.7 Flash",description:"multimodal sparse-MoE reasoning",reasoning:!0,contextWindow:256e3},STEP_3_5_FLASH:{id:"stepfun/Step-3.5-Flash",inputModalities:["text"],provider:Xt,spec:un,label:"Step 3.5 Flash",name:"Step 3.5 Flash",description:"fast sparse-MoE agentic reasoning",reasoning:!0,contextWindow:1e6},GEMINI_3_5_FLASH:{id:"google/gemini-3.5-flash",inputModalities:["text","image"],provider:Xt,spec:un,label:"Gemini 3.5 Flash",name:"Gemini 3.5 Flash",description:"Pro-level coding proficiency, parallel agentic execution",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},GEMINI_3_1_FLASH_LITE:{id:"google/gemini-3.1-flash-lite",inputModalities:["text","image"],provider:Xt,spec:un,label:"Gemini 3.1 Flash Lite",name:"Gemini 3.1 Flash Lite",description:"high-volume workhorse model with implicit caching",vendorLabel:"Google",reasoning:!0,reasoningEfforts:["low","medium","high"],contextWindow:1e6},NEMOTRON_3_ULTRA:{id:"nvidia/nemotron-3-ultra-550b-a55b",inputModalities:["text"],provider:Xt,spec:un,label:"Nemotron 3 Ultra",name:"Nemotron 3 Ultra",description:"open reasoning model for long-horizon autonomous agents",reasoning:!0,contextWindow:1e6}}).SONNET_4_6.id,pn.FABLE_5.id,pn.OPUS_4_8.id,pn.OPUS_4_7.id,pn.HAIKU_4_5.id,gn=[{canonicalId:"zai-org/GLM-5",providers:{[Qt.VERCEL_AI_GATEWAY]:"zai/glm-5",[Qt.BASETEN]:"zai-org/GLM-5"}},{canonicalId:"zai-org/GLM-5.2",providers:{[Qt.VERCEL_AI_GATEWAY]:"zai/glm-5.2"}},{canonicalId:"zai-org/GLM-5.1",providers:{[Qt.VERCEL_AI_GATEWAY]:"zai/glm-5.1"}},{canonicalId:"moonshotai/Kimi-K2.5",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.5",[Qt.BASETEN]:"moonshotai/Kimi-K2.5",[Qt.CLOUDFLARE_AI_GATEWAY]:"workers-ai/@cf/moonshotai/kimi-k2.5"}},{canonicalId:"moonshotai/Kimi-K2.6",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.6",[Qt.BASETEN]:"moonshotai/Kimi-K2.6",[Qt.CLOUDFLARE_AI_GATEWAY]:"workers-ai/@cf/moonshotai/kimi-k2.6"}},{canonicalId:"moonshotai/Kimi-K2.7-Code",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.7-code"}},{canonicalId:"moonshotai/Kimi-K2.7-Code-Highspeed",providers:{[Qt.VERCEL_AI_GATEWAY]:"moonshotai/kimi-k2.7-code-highspeed"}},{canonicalId:"MiniMaxAI/MiniMax-M2.5",providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m2.5",[Qt.BASETEN]:"MiniMaxAI/MiniMax-M2.5"}},{canonicalId:"deepseek/deepseek-v4-pro",providers:{[Qt.VERCEL_AI_GATEWAY]:"deepseek/deepseek-v4-pro"}},{canonicalId:"deepseek/deepseek-v4-flash",providers:{[Qt.VERCEL_AI_GATEWAY]:"deepseek/deepseek-v4-flash"}},{canonicalId:"Qwen/Qwen3.6-Max-Preview",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen-3.6-max-preview"}},{canonicalId:"Qwen/Qwen3.6-Plus",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen3.6-plus"}},{canonicalId:"Qwen/Qwen3.7-Max",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen3.7-max"}},{canonicalId:"Qwen/Qwen3.7-Plus",providers:{[Qt.VERCEL_AI_GATEWAY]:"alibaba/qwen3.7-plus"}},{canonicalId:"MiniMaxAI/MiniMax-M3",providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m3"}},{canonicalId:mn,providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m3"}},{canonicalId:"MiniMaxAI/MiniMax-M2.7",providers:{[Qt.VERCEL_AI_GATEWAY]:"minimax/minimax-m2.7"}},{canonicalId:"stepfun/Step-3.7-Flash",providers:{[Qt.VERCEL_AI_GATEWAY]:"stepfun/step-3.7-flash"}},{canonicalId:"stepfun/Step-3.5-Flash",providers:{[Qt.OPENROUTER]:"stepfun/step-3.5-flash"}},{canonicalId:"xiaomi/mimo-v2.5-pro",providers:{[Qt.VERCEL_AI_GATEWAY]:"xiaomi/mimo-v2.5-pro"}},{canonicalId:"xiaomi/mimo-v2.5",providers:{[Qt.VERCEL_AI_GATEWAY]:"xiaomi/mimo-v2.5"}},{canonicalId:"google/gemini-3.5-flash",providers:{[Qt.VERCEL_AI_GATEWAY]:"google/gemini-3.5-flash"}},{canonicalId:"google/gemini-3.1-flash-lite",providers:{[Qt.VERCEL_AI_GATEWAY]:"google/gemini-3.1-flash-lite"}},{canonicalId:"nvidia/nemotron-3-ultra-550b-a55b",providers:{[Qt.VERCEL_AI_GATEWAY]:"nvidia/nemotron-3-ultra-550b-a55b"}}],hn={"claude-sonnet-4-20250514":pn.SONNET_4_6.id,"claude-sonnet-4-5-20250929":pn.SONNET_4_6.id,"claude-opus-4-5-20251101":pn.OPUS_4_7.id,"claude-opus-4-6":pn.OPUS_4_7.id,"claude-haiku-4-5":pn.HAIKU_4_5.id},fn=pn.DEEPSEEK_V4_FLASH.id,yn={[Qt.ANTHROPIC]:"Anthropic",[Qt.OPENAI]:"OpenAI",[Qt.BASETEN]:"Open Source",[Qt.VERCEL_AI_GATEWAY]:"Open Source"},wn=["Open Source","Anthropic","OpenAI","Google"],Sn={"command-code":{id:"command-code",label:"Command Code",shortLabel:"cmd",description:"recommended",supportedModelProviders:[Qt.ANTHROPIC,Qt.OPENAI,Qt.BASETEN,Qt.VERCEL_AI_GATEWAY],requiresAuth:!1,visibleInCoMode:!0,visibleInNormalMode:!0,showProviderLabelInSelector:!0},anthropic:{id:"anthropic",label:"Anthropic",shortLabel:"anth",description:"Claude Pro/Max",supportedModelProviders:[Qt.ANTHROPIC],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!1,showProviderLabelInSelector:!1},"github-copilot":{id:"github-copilot",label:"GitHub Copilot",shortLabel:"copilot",description:"Copilot subscription",supportedModelProviders:[Qt.ANTHROPIC,Qt.OPENAI],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!1,showProviderLabelInSelector:!0},codex:{id:"codex",label:"ChatGPT (Codex)",shortLabel:"codex",description:"ChatGPT Pro/Plus subscription",supportedModelProviders:[Qt.OPENAI],requiresAuth:!0,visibleInCoMode:!0,visibleInNormalMode:!1,showProviderLabelInSelector:!1}},__name(buildModelGroups,"buildModelGroups"),bn=buildModelGroups("co"),En=buildModelGroups("normal"),new Set(["cc2@www3.in","cc3@www3.in","cc4@www3.in","cc5@www3.in","cc6@www3.in","cc7@www3.in","cc8@www3.in","cc9@www3.in","cc10@www3.in"].map(e=>e.toLowerCase())),vn=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],Cn={TIER_1_THRESHOLD:.5,TIER_2_THRESHOLD:.8,TIER_3_THRESHOLD:.9,TIER_1_KEEP_COUNT:20,TIER_2_KEEP_COUNT:10,KEEP_RECENT_TOKENS:3e4}}}),xn=__esm({"src/utils/env.ts"(){Bt(),Tn=__name(()=>{const e=process.argv.includes("--local"),t=process.argv.includes("--staging");return e?"local":t?"staging":"prod"},"getApiEnv")}});function getAuthDir(){return t.join(S.homedir(),".commandcode")}function getAuthFile(e){const n=e??Tn(),r="local"===n?"auth.local.json":"staging"===n?"auth.staging.json":"auth.json";return t.join(getAuthDir(),r)}function getConfigFile(e){const n=e??Tn(),r="local"===n?"config.local.json":"staging"===n?"config.staging.json":"config.json";return t.join(getAuthDir(),r)}var An,Pn,In,Mn,Rn,Nn,Ln,$n,Dn,On,Fn,jn,Un=__esm({"src/utils/auth/auth-paths.ts"(){Bt(),_n(),xn(),__name(getAuthDir,"getAuthDir"),__name(getAuthFile,"getAuthFile"),__name(getConfigFile,"getConfigFile")}});function isWordLeftSequence(e){return!!An.has(e)||!!On.test(e)}function isWordRightSequence(e){return!!Pn.has(e)||!!Fn.test(e)}function isHomeSequence(e){return In.has(e)}function isEndSequence(e){return Mn.has(e)}function isForwardDeleteSequence(e){return Rn.has(e)}function isDeleteWordSequence(e){return Nn.has(e)}function isCtrlA(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_A}function isCtrlE(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_E}function isCtrlK(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_K}function isCtrlU(e){return 1===e.length&&e.charCodeAt(0)===Ln.CTRL_U}function isAltP(e){return Dn.has(e)}function isCtrlKey({inputChar:e,key:t,letter:n,ctrlCode:r}){return!(!t.ctrl||e.toLowerCase()!==n.toLowerCase())||void 0!==r&&e.charCodeAt(0)===r}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)||jn.includes(t))}var Bn,qn,zn,Hn,Wn,Gn,Vn,Kn,Qn,Yn=__esm({"src/utils/keyboard-sequences.ts"(){Bt(),An=new Set(["","b","","",""]),Pn=new Set(["","f","","",""]),In=new Set(["","[1~","[7~","OH"]),Mn=new Set(["","[4~","[8~","OF"]),Rn=new Set(["[3~"]),Nn=new Set(["",""]),Ln={CTRL_A:1,CTRL_B:2,CTRL_E:5,CTRL_F:6,CTRL_G:7,CTRL_K:11,CTRL_U:21,CTRL_W:23},$n={ALT_P:112,ALT_P_NO_META:960},Dn=new Set([String.fromCharCode(27,$n.ALT_P),String.fromCharCode($n.ALT_P_NO_META),""]),On=/^\x1b\[1;[359]D$/,Fn=/^\x1b\[1;[359]C$/,__name(isWordLeftSequence,"isWordLeftSequence"),__name(isWordRightSequence,"isWordRightSequence"),__name(isHomeSequence,"isHomeSequence"),__name(isEndSequence,"isEndSequence"),__name(isForwardDeleteSequence,"isForwardDeleteSequence"),__name(isDeleteWordSequence,"isDeleteWordSequence"),__name(isCtrlA,"isCtrlA"),__name(isCtrlE,"isCtrlE"),__name(isCtrlK,"isCtrlK"),__name(isCtrlU,"isCtrlU"),__name(isAltP,"isAltP"),__name(isCtrlKey,"isCtrlKey"),jn=["\n","\r","","[27;2;13~","[27;2;13~","[13;2u"],__name(isNewlineShortcutKey,"isNewlineShortcutKey")}}),Jn=__esm({"src/auth/index.ts"(){Bt(),_n(),xn(),(e=>{e.OAuth=f.object({type:f.literal("oauth"),refresh:f.string(),access:f.string(),expires:f.number(),accountId:f.string().optional()}),e.ApiKey=f.object({type:f.literal("api"),key:f.string()}),e.Info=f.discriminatedUnion("type",[e.OAuth,e.ApiKey]);const n=__name(()=>t.join(S.homedir(),".commandcode"),"getAuthDir"),r=__name(()=>{const e=Tn(),r="local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json";return t.join(n(),r)},"getAuthFile");async function get(e){try{const t=await k.readFile(r(),"utf-8");return JSON.parse(t)[e]}catch{return}}async function set(e,t){const o=n(),s=r();await k.mkdir(o,{recursive:!0});let i={};try{const e=await k.readFile(s,"utf-8");i=JSON.parse(e)}catch{}i[e]=t,await k.writeFile(s,JSON.stringify(i,null,2)),await k.chmod(s,384)}async function remove(e){const t=r();try{const n=await k.readFile(t,"utf-8"),r=JSON.parse(n);delete r[e],0===Object.keys(r).length?await k.unlink(t):(await k.writeFile(t,JSON.stringify(r,null,2)),await k.chmod(t,384))}catch{}}async function list2(){try{const e=await k.readFile(r(),"utf-8");return JSON.parse(e)}catch{return{}}}e.get=get,__name(get,"get"),e.set=set,__name(set,"set"),e.remove=remove,__name(remove,"remove"),e.list=list2,__name(list2,"list")})(Bn||(Bn={}))}}),Xn=__esm({"src/utils/constants.ts"(){Bt(),_n(),qn="You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: https://commandcode.ai/billing",zn="OAuth authentication required. Please use /provider command\nSelect your provider and complete the OAuth setup.",Hn=">"}}),Zn=__esm({"src/auth/anthropic.ts"(){Bt(),Jn(),Xn(),Bs(),(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 exchangeCodeForTokens2(e,o,s){const i=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(!i.ok){const e=await i.text(),t=new Error(`Token exchange failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"token_exchange_failed"}),context:{component:Ls.ANTHROPIC_OAUTH,heading:"OAuth token exchange failed"}}),t}const a=await i.json();await Bn.set("anthropic",{type:"oauth",refresh:a.refresh_token,access:a.access_token,expires:Date.now()+1e3*a.expires_in})}async function refreshAccessToken2(){const e=await Bn.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 trackError({error:sanitizeErrorForTelemetry({error:new Error("OAuth token refresh failed"),label:"token_refresh_failed"}),context:{component:Ls.ANTHROPIC_OAUTH,heading:"OAuth token refresh failed"}});const o=await r.json();return await Bn.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 trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"token_refresh_exception"}),context:{component:Ls.ANTHROPIC_OAUTH,heading:"OAuth token refresh exception"}})}}}async function getValidAccessToken2(){const e=await Bn.get("anthropic");if(e)return"api"===e.type?e.key:"oauth"===e.type?await refreshAccessToken2():void 0}__name(generateCodeVerifier,"generateCodeVerifier"),__name(generateCodeChallenge,"generateCodeChallenge"),__name(generateState,"generateState"),e.createAuthorizationUrl=createAuthorizationUrl,__name(createAuthorizationUrl,"createAuthorizationUrl"),e.exchangeCodeForTokens=exchangeCodeForTokens2,__name(exchangeCodeForTokens2,"exchangeCodeForTokens"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken")})(Wn||(Wn={}))}});function getIcon(e){if(Kn[e])return Kn[e];const t=e.split(":")[0];return Kn[t]?Kn[t]:Kn.default}function formatTime(e){return`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`}function parseMessage(e){const t=e.match(/^\[([^\]]+)\]\s*(.*)/);return t?{category:t[1],text:t[2]}:{category:"",text:e}}function showStartup(){if(!Qn){Qn=!0;try{$.mkdirSync(Gn,{recursive:!0});const e=new Date,t=`\n════════════════════════════════════════════════════════════════\n CommandCode Debug Log\n Started: ${e.toLocaleDateString()} ${formatTime(e)}\n Log: ${Vn}\n════════════════════════════════════════════════════════════════\n\n`;$.appendFileSync(Vn,t,"utf-8")}catch{}}}function dlog(e,t){if("true"===process.env.DEBUG){showStartup();try{const n=formatTime(new Date),{category:r,text:o}=parseMessage(e);let s;if(r){s=`${n} ${getIcon(r)} ${`[${r}]`.padEnd(16)} ${o}`}else s=`${n} ${Kn.default} ${e}`;if(t){s+=`\n${("string"==typeof t?t:JSON.stringify(t,null,2)).split("\n").map(e=>` ${e}`).join("\n")}`}s+="\n",$.appendFileSync(Vn,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`;$.appendFileSync(Vn,t,"utf-8")}catch{}}}var er,tr,nr,rr,sr,ir=__esm({"src/utils/dlog.ts"(){Bt(),Gn=e.join(w.homedir(),".commandcode","logs"),Vn=e.join(Gn,"command.log"),Kn={Startup:">",CLI:"$",Config:"#",Auth:"@",Onboarding:"*",LearningAgent:"&",Import:"<",API:"~",Sessions:"+",Observer:"!",Flow:"^",Handler:">",Helper:"-",Codex:"+",UI:"|",Hook:"%",ObserverAPI:"~",ContextEngine:"~",Updater:"^",MCP:"&",default:"-"},__name(getIcon,"getIcon"),__name(formatTime,"formatTime"),__name(parseMessage,"parseMessage"),Qn=!1,__name(showStartup,"showStartup"),"true"===process.env.DEBUG&&showStartup(),__name(dlog,"dlog"),__name(dlogSection,"dlogSection")}}),ar=__esm({"src/auth/codex.ts"(){Bt(),Jn(),Xn(),Bs(),ir(),(e=>{const t="app_EMoamEEZ73f0CkXaXp7hrann",n="https://auth.openai.com",r="openid profile email offline_access",o="http://localhost:1455/auth/callback";function base64UrlEncode(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function generateRandomString2(e){const t=R.randomBytes(e);let n="";for(let r=0;r<e;r++)n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[t[r]%66];return n}function generatePKCE2(){const e=generateRandomString2(64);return{verifier:e,challenge:base64UrlEncode(R.createHash("sha256").update(e).digest())}}function buildAuthorizeUrl(e,s){const i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:r,code_challenge:e.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:s,originator:"codex_cli_rs"});return`${n}/oauth/authorize?${i.toString()}`}function parseJwtClaims(e){const t=e.split(".");if(3===t.length)try{return JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"))}catch{return}}function extractAccountId(e){const t=[e.id_token,e.access_token].filter(Boolean);for(const e of t){const t=parseJwtClaims(e);if(!t)continue;const n=t.chatgpt_account_id||t["https://api.openai.com/auth"]?.chatgpt_account_id||t.organizations?.[0]?.id;if(n)return n}}async function exchangeCodeForTokens2(e,r,s){const i=await fetch(`${n}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:o,client_id:t,code_verifier:r.verifier}).toString(),signal:s});if(!i.ok){const e=await i.text();throw new Error(`Codex token exchange failed: ${i.status} ${e}`)}return i.json()}async function refreshTokens(e){const o=await fetch(`${n}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t,scope:r}).toString()});if(!o.ok){const e=await o.text();throw new Error(`Codex token refresh failed: ${o.status} ${e}`)}return o.json()}function waitForCallback(e){const{state:t,signal:n}=e;return new Promise((e,r)=>{let o,s,i=!1;const a=__name(()=>{if(s&&clearTimeout(s),o){if(o.listening)try{o.close(()=>{})}catch{}o=void 0}n?.removeEventListener("abort",u)},"cleanup"),l=__name((t,n)=>{i||(i=!0,a(),t?r(t):e(n))},"finish"),u=__name(()=>{l(new Error("Authentication cancelled"))},"onAbort");n?.aborted?r(new Error("Authentication cancelled")):(n?.addEventListener("abort",u,{once:!0}),o=K(__name((e,n)=>{try{const r=new URL(e.url||"/","http://localhost:1455");if("/auth/callback"!==r.pathname)return n.writeHead(404),void n.end("Not found");const o=r.searchParams.get("code"),s=r.searchParams.get("state"),i=r.searchParams.get("error"),a=r.searchParams.get("error_description");if(i){const e=a||i;return n.writeHead(400,{"Content-Type":"text/html"}),n.end(renderErrorPage(e)),void l(new Error(`Codex OAuth error: ${e}`))}if(!o||!s)return n.writeHead(400,{"Content-Type":"text/html"}),n.end(renderErrorPage("Missing code or state")),void l(new Error("Codex OAuth: missing code or state"));if(s!==t)return n.writeHead(400,{"Content-Type":"text/html"}),n.end(renderErrorPage("State mismatch — possible CSRF attempt")),void l(new Error("Codex OAuth: state mismatch"));n.writeHead(200,{"Content-Type":"text/html"}),n.end("<!doctype html>\n<html>\n <head><title>Command Code — Codex Authorization Successful</title>\n <style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0f0f0f;color:#eee}h1{color:#7ee787}</style>\n </head>\n <body><div><h1>Authorization successful</h1><p>You can close this window and return to Command Code.</p></div>\n <script>setTimeout(()=>window.close(),2000)<\/script></body>\n</html>"),l(null,o)}catch(e){n.writeHead(500),n.end("Internal error"),l(e instanceof Error?e:new Error(String(e)))}},"handler")),o.on("error",e=>l(e)),o.listen(1455,"127.0.0.1",()=>{s=setTimeout(()=>{l(new Error("Codex OAuth timed out waiting for browser callback"))},3e5)}))})}function renderSuccessPage(){return"<!doctype html>\n<html>\n <head><title>Command Code — Codex Authorization Successful</title>\n <style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0f0f0f;color:#eee}h1{color:#7ee787}</style>\n </head>\n <body><div><h1>Authorization successful</h1><p>You can close this window and return to Command Code.</p></div>\n <script>setTimeout(()=>window.close(),2000)<\/script></body>\n</html>"}function renderErrorPage(e){return`<!doctype html>\n<html>\n <head><title>Command Code — Codex Authorization Failed</title>\n <style>body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0f0f0f;color:#eee}h1{color:#ff7b72}</style>\n </head>\n <body><div><h1>Authorization failed</h1><p>${e.replace(/[&<>]/g,e=>"&"===e?"&amp;":"<"===e?"&lt;":"&gt;")}</p></div></body>\n</html>`}async function refreshAccessToken2(){const e=await Bn.get("codex");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return e.access;dlog("[Auth] codex: refreshing access token");try{const t=await refreshTokens(e.refresh),n=extractAccountId(t)??e.accountId;return await Bn.set("codex",{type:"oauth",refresh:t.refresh_token||e.refresh,access:t.access_token,expires:Date.now()+1e3*(t.expires_in??3600),...n?{accountId:n}:{}}),t.access_token}catch(e){return void trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"codex_token_refresh_exception"}),context:{component:Ls.CODEX_OAUTH,heading:"Codex token refresh exception"}})}}}async function getValidAccessToken2(){const e=await Bn.get("codex");if(e)return"api"===e.type?e.key:"oauth"===e.type?refreshAccessToken2():void 0}async function getAccountId(){const e=await Bn.get("codex");if(e&&"oauth"===e.type)return e.accountId}async function login(e){const{onAuth:t,onProgress:n,signal:r}=e;dlog("[Auth] codex: starting browser oauth flow");const o=generatePKCE2(),s=base64UrlEncode(R.randomBytes(32)),i=buildAuthorizeUrl(o,s),a=waitForCallback({state:s,signal:r});let l;t({authorizeUrl:i}),n?.("Waiting for authorization in browser...");try{l=await a}catch(e){const t=e instanceof Error?e:new Error(String(e));throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"codex_oauth_callback_failed"}),context:{component:Ls.CODEX_OAUTH,heading:"Codex oauth callback failed"}}),t}if(r?.aborted)throw new Error("Authentication cancelled");n?.("Exchanging authorization code...");const u=await exchangeCodeForTokens2(l,o,r);if(r?.aborted)throw new Error("Authentication cancelled");if(!u.refresh_token)throw new Error("Codex OAuth: issuer did not return a refresh_token");const d=extractAccountId(u);dlog("[Auth] codex: login success",{hasAccountId:!!d}),await Bn.set("codex",{type:"oauth",refresh:u.refresh_token,access:u.access_token,expires:Date.now()+1e3*(u.expires_in??3600),...d?{accountId:d}:{}})}__name(base64UrlEncode,"base64UrlEncode"),__name(generateRandomString2,"generateRandomString"),__name(generatePKCE2,"generatePKCE"),__name(buildAuthorizeUrl,"buildAuthorizeUrl"),e.parseJwtClaims=parseJwtClaims,__name(parseJwtClaims,"parseJwtClaims"),e.extractAccountId=extractAccountId,__name(extractAccountId,"extractAccountId"),__name(exchangeCodeForTokens2,"exchangeCodeForTokens"),__name(refreshTokens,"refreshTokens"),__name(waitForCallback,"waitForCallback"),__name(renderSuccessPage,"renderSuccessPage"),__name(renderErrorPage,"renderErrorPage"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken"),e.getAccountId=getAccountId,__name(getAccountId,"getAccountId"),e.login=login,__name(login,"login")})(er||(er={}))}}),lr=__esm({"src/auth/copilot.ts"(){Bt(),Jn(),Xn(),_n(),Bs(),ir(),(e=>{const t=atob("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),n=["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"];async function startDeviceFlow(e){const n=e?.domain||"github.com",r=`https://${n}/login/device/code`;dlog("[Auth] startDeviceFlow",{domain:n,url:r});const o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,scope:"read:user"})});if(!o.ok){const e=await o.text(),t=new Error(`Device code request failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"device_flow_start_failed"}),context:{component:Ls.COPILOT_OAUTH,heading:"Device code flow start failed"}}),t}const s=await o.json();return dlog("[Auth] startDeviceFlow success",{userCode:s.user_code,interval:s.interval,expiresIn:s.expires_in}),s}async function pollForGitHubAccessToken(e){const{deviceCode:n,interval:r,expiresIn:o,signal:s}=e,i=e.domain||"github.com",a=`https://${i}/login/oauth/access_token`,l=Date.now()+1e3*o;let u=1e3*r;for(dlog("[Auth] pollForGitHubAccessToken started",{domain:i,pollInterval:u,deadline:new Date(l).toISOString()});Date.now()<l;){if(s?.aborted)throw new Error("Authentication cancelled");if(await new Promise((e,t)=>{if(!s)return void setTimeout(e,u);const n=__name(()=>{clearTimeout(r),t(new Error("Authentication cancelled"))},"onAbort"),r=setTimeout(()=>{s.removeEventListener("abort",n),e()},u);s.addEventListener("abort",n,{once:!0})}),s?.aborted)throw new Error("Authentication cancelled");const e=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,device_code:n,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})}),r=await e.json();if("error"in r){if(dlog("[Auth] poll response error",r.error),"authorization_pending"===r.error)continue;if("slow_down"===r.error){u+=5e3,dlog("[Auth] poll slow_down, new interval",u);continue}if("expired_token"===r.error)throw new Error("Device code expired. Please try again.");if("access_denied"===r.error)throw new Error("Authorization was denied. Please try again.");throw new Error(`GitHub OAuth error: ${r.error}`)}if("access_token"in r)return dlog("[Auth] pollForGitHubAccessToken success, got access_token"),r}throw new Error("Device code expired. Please try again.")}async function refreshCopilotToken(e){const{refreshToken:t,enterpriseDomain:n}=e;dlog("[Auth] refreshCopilotToken called",{hasRefreshToken:!!t,enterpriseDomain:n});let r="https://api.github.com/copilot_internal/v2/token";n&&(r=`https://${n}/api/v3/copilot_internal/v2/token`);const o=await fetch(r,{method:"GET",headers:{Authorization:`token ${t}`,Accept:"application/json",...Yt}});if(!o.ok){const e=await o.text(),t=new Error(`Copilot token refresh failed: ${e}`);throw trackError({error:sanitizeErrorForTelemetry({error:t,label:"copilot_token_refresh_failed"}),context:{component:Ls.COPILOT_OAUTH,heading:"Copilot token refresh failed"}}),t}const s=await o.json(),i=1e3*s.expires_at-3e5;return dlog("[Auth] refreshCopilotToken success",{expiresAt:new Date(i).toISOString(),refreshIn:s.refresh_in}),{token:s.token,expires:i}}async function refreshAccessToken2(){const e=await Bn.get("github-copilot");if(e&&"oauth"===e.type){if(e.expires>Date.now()+3e5)return dlog("[Auth] refreshAccessToken: token still valid",{expires:new Date(e.expires).toISOString()}),e.access;dlog("[Auth] refreshAccessToken: token expired, refreshing...");try{const t=await refreshCopilotToken({refreshToken:e.refresh});return await Bn.set("github-copilot",{type:"oauth",refresh:e.refresh,access:t.token,expires:t.expires}),t.token}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"copilot_token_refresh_exception"}),context:{component:Ls.COPILOT_OAUTH,heading:"Copilot token refresh exception"}}),void dlog("[Auth] refreshAccessToken: refresh failed, keeping auth for retry")}}else dlog("[Auth] refreshAccessToken: no copilot oauth auth found")}async function getValidAccessToken2(){dlog("[Auth] getValidAccessToken called for copilot");const e=await Bn.get("github-copilot");if(e){if(dlog("[Auth] getValidAccessToken: found stored auth",{type:e.type}),"api"===e.type)return e.key;if("oauth"===e.type)return await refreshAccessToken2()}dlog("[Auth] getValidAccessToken: no stored auth, checking env vars");for(const e of n){const t=process.env[e];if(t)try{const e=await refreshCopilotToken({refreshToken:t});return await Bn.set("github-copilot",{type:"oauth",refresh:t,access:e.token,expires:e.expires}),e.token}catch{continue}}}async function login(e){const{onAuth:t,onProgress:n,signal:r}=e;dlog("[Auth] login: starting copilot device code flow"),n?.("Starting device code flow...");const o=await startDeviceFlow();t({userCode:o.user_code,verificationUri:o.verification_uri}),n?.("Waiting for authorization...");const s=await pollForGitHubAccessToken({deviceCode:o.device_code,interval:o.interval,expiresIn:o.expires_in,signal:r});n?.("Getting Copilot access...");const i=await refreshCopilotToken({refreshToken:s.access_token});dlog("[Auth] login: storing copilot tokens"),await Bn.set("github-copilot",{type:"oauth",refresh:s.access_token,access:i.token,expires:i.expires}),dlog("[Auth] login: copilot login complete")}e.startDeviceFlow=startDeviceFlow,__name(startDeviceFlow,"startDeviceFlow"),e.pollForGitHubAccessToken=pollForGitHubAccessToken,__name(pollForGitHubAccessToken,"pollForGitHubAccessToken"),e.refreshCopilotToken=refreshCopilotToken,__name(refreshCopilotToken,"refreshCopilotToken"),e.refreshAccessToken=refreshAccessToken2,__name(refreshAccessToken2,"refreshAccessToken"),e.getValidAccessToken=getValidAccessToken2,__name(getValidAccessToken2,"getValidAccessToken"),e.login=login,__name(login,"login")})(tr||(tr={}))}});function startEarlyInputCapture(){nr||(nr=!0,rr=[],sr=__name(e=>{const t=e.toString();t&&!isControlSequenceToSkip(t)&&rr.push(t)},"earlyInputHandler"),process.stdin.on("data",sr))}function stopEarlyInputCapture(){nr&&sr&&(process.stdin.off("data",sr),sr=null,nr=!1)}function consumeBufferedInput(){const e=rr.join("");return rr=[],e}function hasBufferedInput(){return rr.length>0}function isControlSequenceToSkip(e){return!!(e.startsWith("[200~")||e.startsWith("[201~")||e.startsWith("")||e.startsWith(""))}var cr,ur=__esm({"src/utils/early-input-buffer.ts"(){Bt(),nr=!1,rr=[],sr=null,__name(startEarlyInputCapture,"startEarlyInputCapture"),__name(stopEarlyInputCapture,"stopEarlyInputCapture"),__name(consumeBufferedInput,"consumeBufferedInput"),__name(hasBufferedInput,"hasBufferedInput"),__name(isControlSequenceToSkip,"isControlSequenceToSkip")}});function isWordBoundary(e){return!e||0===e.length||cr.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),i=o-s;return s+Math.min(r,i)}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,i=findLineEnd(e,s)-s;return s+Math.min(o,i)}function insertTextAt(e,t,n){const r=e||"",o=clampCursor(t,r.length);return{text:r.slice(0,o)+n+r.slice(o),cursor:o+n.length}}function deleteCharBefore(e,t){return!e||t<=0?{text:e||"",cursor:0}:{text:e.slice(0,t-1)+e.slice(t),cursor:t-1}}function deleteCharAt(e,t){return!e||t>=e.length?{text:e||"",cursor:t}:{text:e.slice(0,t)+e.slice(t+1),cursor:t}}var dr,mr,pr,gr=__esm({"src/utils/text-navigation.ts"(){Bt(),cr=/\s|[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/,__name(isWordBoundary,"isWordBoundary"),__name(findPreviousWordBoundary,"findPreviousWordBoundary"),__name(findNextWordBoundary,"findNextWordBoundary"),__name(deleteWordBackwards,"deleteWordBackwards"),__name(clampCursor,"clampCursor"),__name(findLineStart,"findLineStart"),__name(findLineEnd,"findLineEnd"),__name(moveCursorUp,"moveCursorUp"),__name(moveCursorDown,"moveCursorDown"),__name(insertTextAt,"insertTextAt"),__name(deleteCharBefore,"deleteCharBefore"),__name(deleteCharAt,"deleteCharAt")}});function stripBracketedPaste(e){return e.includes(dr)||e.includes(mr)?e.replaceAll(dr,"").replaceAll(mr,""):null}function processBracketedPasteInput({input:e,value:t,cursor:n}){const r=stripBracketedPaste(e);if(null===r)return{value:t,cursor:n,handled:!1};if(0===r.length)return{value:t,cursor:n,handled:!0};const o=insertTextAt(t,n,r);return{value:o.text,cursor:o.cursor,handled:!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 processBackspaceRun(e,t,n){let r=t,o=n;for(let t=0;t<e.length;t++){const e=deleteCharBefore(r,o);r=e.text,o=e.cursor}return{value:r,cursor:o,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-\x09\x0B\x0C\x0E-\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):pr.test(e)?processBackspaceRun(e,t,n):{value:t,cursor:n,handled:!1}}function isIgnoredKey(e,t){return!(!t.ctrl||"c"!==e)||!!t.tab||!(!t.shift||!t.tab)}function processInkInput(e,t,n,r,o){const s=t;return s.meta&&t.leftArrow?processLineStart(n,r):s.meta&&t.rightArrow?processLineEnd(n,r):s.meta&&"b"===e?processWordLeft(n,r):s.meta&&"f"===e?processWordRight(n,r):t.ctrl&&"a"===e?processLineStart(n,r):t.ctrl&&"e"===e?processLineEnd(n,r):t.ctrl&&"w"===e?processDeleteWord(n,r):t.ctrl&&"k"===e?processDeleteToEnd(n,r):t.ctrl&&"u"===e?processDeleteToStart(n,r):t.leftArrow?processCursorLeft(n,r,o):t.rightArrow?processCursorRight(n,r,o):t.upArrow?processCursorUp(n,r,o):t.downArrow?processCursorDown(n,r,o):t.backspace||t.delete?processBackspace(n,r):!t.ctrl&&!s.meta&&e.length>0?processCharacterInput(n,r,e):{value:n,cursor:r,handled:!1}}var hr=__esm({"src/tui/text/input-handlers.ts"(){Bt(),Yn(),gr(),dr="[200~",mr="[201~",__name(stripBracketedPaste,"stripBracketedPaste"),__name(processBracketedPasteInput,"processBracketedPasteInput"),__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"),pr=/^[\u007f\b]{2,}$/,__name(processBackspaceRun,"processBackspaceRun"),__name(processCursorLeft,"processCursorLeft"),__name(processCursorRight,"processCursorRight"),__name(processCursorUp,"processCursorUp"),__name(processCursorDown,"processCursorDown"),__name(processCharacterInput,"processCharacterInput"),__name(processRawInput,"processRawInput"),__name(isIgnoredKey,"isIgnoredKey"),__name(processInkInput,"processInkInput")}});function useCursorState({value:e,focus:t,showCursor:n,initialCursor:r}){const[o,s]=se(r??(e||"").length),i=ie(o),a=ie(e);ae(()=>{const r=a.current;if(a.current=e,e===r)return;if(!t)return;if(!n)return;const l=(e||"").length;o>l&&(s(l),i.current=l)},[e,t,n,o]);const l=ce(e=>{s(e),i.current=e},[]);return{cursor:o,setCursor:l,cursorRef:i}}function useRawStdinHandler({focus:e,valueRef:t,cursorRef:n,onUpdate:r,setHandled:o,stripBracketedPaste:s=!1}){const i=ie(!1);ae(()=>{if(!e)return;const a=process.stdin,l=__name(e=>{o(!0);const t=clampCursor(e.cursor,e.value.length);r(e.value,t),setTimeout(()=>o(!1),0)},"emitStdinResult"),u=__name(e=>{const r=e.toString();if(s){const e=processBracketedPasteInput({input:r,value:t.current,cursor:n.current});if(e.handled)return void l(e)}const o=processRawInput(r,t.current,n.current);o.handled&&l(o)},"handleRawInput");if(a.on("data",u),!i.current&&hasBufferedInput()){i.current=!0;const e=consumeBufferedInput();e&&u(Buffer.from(e))}return stopEarlyInputCapture(),()=>{a.off("data",u)}},[e,t,n,r,o,s])}function useInkInputHandler({focus:e,showCursor:t,valueRef:n,cursorRef:r,isHandledByStdin:o,onUpdate:s,onSubmit:i}){Z((e,a)=>{if(o())return;if(isIgnoredKey(e,a))return;if(a.return)return void i?.(n.current);const l=processInkInput(e,a,n.current,r.current,t);if(!l.handled)return;const u=clampCursor(l.cursor,l.value.length);s(l.value,u)},{isActive:e})}function useSyncedRef(e){const t=ie(e);return t.current=e,t}function useEchoAwareValueRef(e){const t=ie(e),n=ie([]),r=n.current.indexOf(e);return-1!==r?n.current.splice(0,r+1):t.current!==e&&(t.current=e,n.current=[]),{valueRef:t,noteEmittedValue:ce(e=>{n.current.push(e),n.current.length>64&&n.current.shift()},[])}}var fr,yr,wr,Sr,br,Er,vr,Cr,kr,Tr,_r,xr,Ar,Pr,Ir,Mr,Rr,Nr,Lr,$r,Dr,Or,Fr,jr,Ur,Br,qr,zr,Hr=__esm({"src/tui/text/hooks.ts"(){Bt(),ur(),gr(),hr(),__name(useCursorState,"useCursorState"),__name(useRawStdinHandler,"useRawStdinHandler"),__name(useInkInputHandler,"useInkInputHandler"),__name(useSyncedRef,"useSyncedRef"),__name(useEchoAwareValueRef,"useEchoAwareValueRef")}});function isLightTheme(){return"light"===Sr}function applyTuiTheme(e){const t=wr[e];Sr=e,Object.assign(br,t.PALETTE),Er=t.ACCENT,Object.assign(vr,t.TASTE_COLORS),Cr=t.THINKING_COLOR,kr=t.QUEUED_COLOR,Object.assign(Tr,t.DIFF_COLORS),Object.assign(_r,t.TOOL_BADGE_COLORS),Object.assign(xr,t.STATUS_PILL_COLORS),Object.assign(Ar,t.AGENT_BADGE_COLORS),Object.assign(Pr,t.STATUS_COLORS),Ir=t.IDE_COLOR,Mr=t.MUTED,Object.assign(Rr,t.USER_MSG_COLORS),Nr=t.AI_ICON_COLOR,Lr=t.PLAN_MODE_COLOR,$r=t.ACCEPT_EDITS_COLOR,Object.assign(Dr,t.PR_COLORS),Or=t.RETRY_COLOR,Object.assign(Fr,t.MARKDOWN_COLORS),jr.splice(0,jr.length,...t.SHIMMER_COLORS),Ur=t.SHIMMER_DEFAULT,Object.assign(Br,t.LOGO_BANNER_COLORS),qr=br.DIM,zr=t.HIGHLIGHT_BAR_BG}var Wr,Gr,Vr=__esm({"src/tui/colors.ts"(){Bt(),fr={PALETTE:{CYAN:"#7AD4D6",GREEN:"#2EBD8E",GRAY:"#8A94A8",WHITE:"#E5E5E5",YELLOW:"#F5B731",RED:"#E84057",BLUE:"#5945B1",MAGENTA:"#F2608A",DIM:"#8A94A8",DIMMER:"#4C556A",DIMMEST:"#353D50"},ACCENT:"#E4CCFF",TASTE_COLORS:{BADGE_BG:"#08575B",BADGE_FG:"#f4f4f4",TEXT:"#02888E"},THINKING_COLOR:"#E4CCFF",QUEUED_COLOR:"#F5B731",DIFF_COLORS:{REMOVED_BG:"#5C0112",ADDED_BG:"#04473A",REMOVED_TEXT:"#E16B7A",ADDED_TEXT:"#4CC88E",REMOVED_HIGHLIGHT_BG:"#7D2233",ADDED_HIGHLIGHT_BG:"#2E6B4A",LINE_NUM:"#8A94A8"},TOOL_BADGE_COLORS:{BG:"#5945B1",FG:"#f4f4f4"},STATUS_PILL_COLORS:{BG:"#2D2B55",FG:"#E4CCFF"},AGENT_BADGE_COLORS:{BG:"#6943FF",FG:"#f4f4f4"},STATUS_COLORS:{SUCCESS:"#35AD68",ERROR:"#E84057",WARNING:"#F5B731",IN_PROGRESS:"#E4CCFF"},IDE_COLOR:"#B1BAF9",MUTED:"#8A94A8",USER_MSG_COLORS:{BG:"#2D2B55",POINTER:"#A599E9",FG:"#E5E5E5"},HIGHLIGHT_BAR_BG:"#2D2B55",AI_ICON_COLOR:"#A599E9",PLAN_MODE_COLOR:"#F5B731",ACCEPT_EDITS_COLOR:"#8367F4",PR_COLORS:{OPEN:"#F5B731",MERGED:"#A78BFA"},RETRY_COLOR:"#F49D2A",MARKDOWN_COLORS:{CODE:"#B1BAF9",HEADING:"#A599E9"},SHIMMER_COLORS:["#A599E9","#E4CCFF","#ABA5CE","#CCC7E1","#FFFFFF","#EADAFF","#ABA5CE","#E4CCFF","#A599E9"],SHIMMER_DEFAULT:"#6E61A3",LOGO_BANNER_COLORS:{TEXT:"#B1BAF9",BG:"#2B2758"}},yr={...fr,PALETTE:{...fr.PALETTE,CYAN:"#0F6B6D",GREEN:"#047857",GRAY:"#4B5563",WHITE:"#111827",YELLOW:"#92600A",RED:"#BE123C",MAGENTA:"#BE185D",DIM:"#4B5563"},ACCENT:"#5B21B6",TASTE_COLORS:{...fr.TASTE_COLORS,TEXT:"#0F6B6D"},THINKING_COLOR:"#5B21B6",QUEUED_COLOR:"#92600A",DIFF_COLORS:{...fr.DIFF_COLORS,REMOVED_BG:"#FEE2E2",ADDED_BG:"#CCFBF1",REMOVED_TEXT:"#BE123C",ADDED_TEXT:"#0F766E",REMOVED_HIGHLIGHT_BG:"#FECDD3",ADDED_HIGHLIGHT_BG:"#99F6E4"},STATUS_PILL_COLORS:{BG:"#4A4570",FG:"#E4CCFF"},STATUS_COLORS:{...fr.STATUS_COLORS,SUCCESS:"#047857",ERROR:"#BE123C",WARNING:"#92600A",IN_PROGRESS:"#5B21B6"},IDE_COLOR:"#4338CA",MUTED:"#4B5563",USER_MSG_COLORS:{...fr.USER_MSG_COLORS,BG:"#4A4570",POINTER:"#E4CCFF",FG:"#FFFFFF"},HIGHLIGHT_BAR_BG:"#DDD6FE",AI_ICON_COLOR:"#5B21B6",PLAN_MODE_COLOR:"#92600A",PR_COLORS:{OPEN:"#92600A",MERGED:"#6D28D9"},RETRY_COLOR:"#92600A",MARKDOWN_COLORS:{CODE:"#4338CA",HEADING:"#5B21B6"},SHIMMER_COLORS:["#D8B4FE","#E4CCFF","#F5F3FF","#FFFFFF","#F5F3FF","#E4CCFF","#D8B4FE","#F5F3FF","#FFFFFF"],SHIMMER_DEFAULT:"#E4CCFF",LOGO_BANNER_COLORS:{TEXT:"#B1BAF9",BG:"#2B2758"}},wr={dark:fr,light:yr},Sr="dark",br={...fr.PALETTE},Er=fr.ACCENT,vr={...fr.TASTE_COLORS},Cr=fr.THINKING_COLOR,kr=fr.QUEUED_COLOR,Tr={...fr.DIFF_COLORS},_r={...fr.TOOL_BADGE_COLORS},xr={...fr.STATUS_PILL_COLORS},Ar={...fr.AGENT_BADGE_COLORS},Pr={...fr.STATUS_COLORS},Ir=fr.IDE_COLOR,Mr=fr.MUTED,Rr={...fr.USER_MSG_COLORS},Nr=fr.AI_ICON_COLOR,Lr=fr.PLAN_MODE_COLOR,$r=fr.ACCEPT_EDITS_COLOR,Dr={...fr.PR_COLORS},Or=fr.RETRY_COLOR,Fr={...fr.MARKDOWN_COLORS},jr=[...fr.SHIMMER_COLORS],Ur=fr.SHIMMER_DEFAULT,Br={...fr.LOGO_BANNER_COLORS},qr=br.DIM,zr=fr.HIGHLIGHT_BAR_BG,__name(isLightTheme,"isLightTheme"),__name(applyTuiTheme,"applyTuiTheme")}});function stripBracketedPasteMarkers(e){return e.replace(/\x1B\[200~/g,"").replace(/\[200~/g,"").replace(/\x1B\[201~/g,"").replace(/\[201~/g,"")}function processBracketedPaste(e){const t=e.includes("[200~")||e.includes("[200~"),n=e.includes("[201~")||e.includes("[201~");if(!t&&!n)return{isPasteStart:!1,isPasteEnd:!1,cleanedContent:e};const r=stripBracketedPasteMarkers(e);let o,s,i;if(t){const t=e.match(/(\x1B)?\[200~/);if(t&&void 0!==t.index){o=e.slice(0,t.index);const r=e.slice(t.index+t[0].length);if(n){const e=r.match(/(\x1B)?\[201~/);e&&void 0!==e.index&&(s=r.slice(0,e.index))}else s=r}}if(n){const t=e.match(/(\x1B)?\[201~/);t&&void 0!==t.index&&(i=e.slice(t.index+t[0].length))}return{isPasteStart:t,isPasteEnd:n,cleanedContent:r,textBeforePaste:o,pastedContent:s,textAfterPaste:i}}function enableBracketedPasteMode(){process.stdout.write("[?2004h")}function disableBracketedPasteMode(){process.stdout.write("[?2004l")}function pastedLineCount(e){return(e.endsWith("\n")?e.slice(0,-1):e).split("\n").length}function pastedTextPreview(e){const t=e.trim().split(/\s+/).filter(Boolean);if(0===t.length)return"";const n=t.slice(0,3).join(" "),r=n.slice(0,Wr).trimEnd();return t.length>3||r.length<n.length?`${r}…`:r}function pastedTextToken(e){const t=pastedLineCount(e),n=pastedTextPreview(e);return n?`[${n} +${t}L]`:`[+${t}L]`}var Kr,Qr=__esm({"src/utils/bracketed-paste.ts"(){Bt(),__name(stripBracketedPasteMarkers,"stripBracketedPasteMarkers"),__name(processBracketedPaste,"processBracketedPaste"),__name(enableBracketedPasteMode,"enableBracketedPasteMode"),__name(disableBracketedPasteMode,"disableBracketedPasteMode"),__name(pastedLineCount,"pastedLineCount"),Wr=10,__name(pastedTextPreview,"pastedTextPreview"),__name(pastedTextToken,"pastedTextToken"),Gr=/\[[^\[\]]*\+\d+L\]/g}});function pastedTokenRanges(e){const t=[],n=new RegExp(Gr.source,"g");let r;for(;null!==(r=n.exec(e));)t.push([r.index,r.index+r[0].length]);return t}function renderPlainSpan(e,t,n,r,o){let s="";for(let i=t;i<n;i++){const t=e[i];s+=o&&i===r?"\n"===t?de.inverse(" ")+"\n":de.inverse(t):t}return s}function renderTokenSpan(e,t,n,r,o){return o&&r>=t&&r<n?Kr(e.slice(t,r))+de.inverse(e[r])+Kr(e.slice(r+1,n)):Kr(e.slice(t,n))}function renderPlaceholder(e,t){return t?0===e.length?de.inverse(" "):de.inverse(e[0])+Kr(e.slice(1)):Kr(e)}function renderValue(e,t,n){const r=pastedTokenRanges(e);if(!n&&0===r.length)return e;if(n&&0===e.length)return de.inverse(" ");let o="",s=0;for(const[i,a]of r)o+=renderPlainSpan(e,s,i,t,n),o+=renderTokenSpan(e,i,a,t,n),s=a;return o+=renderPlainSpan(e,s,e.length,t,n),n&&t===e.length&&(o+=de.inverse(" ")),o}function wrapWithIndent(e,t,n){if(t<=n)return e;const r=" ".repeat(n),o=t-n,s=t;if(me(e).length<=s)return e;const i=e.split(/(\s+)/);let a="",l=0,u=!0;for(const e of i){const t=me(e).length;if(l+t>(u?s:o)&&l>0&&(a+="\n"+r,l=n,u=!1),a+=e,l+=t,e.includes("\n")){const t=e.substring(e.lastIndexOf("\n")+1);l=me(t).length,u=!0}}return a}function getDisplayValue(e,t,n,r,o){const s=r&&o;return t&&0===e.length?renderPlaceholder(t,s):renderValue(e,n,s)}function getMaskedValue(e,t){return t?t.repeat(e.length):e}var Yr,Jr=__esm({"src/tui/text/render-utils.ts"(){Bt(),Vr(),Qr(),Kr=ue.hex(br.DIM),__name(pastedTokenRanges,"pastedTokenRanges"),__name(renderPlainSpan,"renderPlainSpan"),__name(renderTokenSpan,"renderTokenSpan"),__name(renderPlaceholder,"renderPlaceholder"),__name(renderValue,"renderValue"),__name(wrapWithIndent,"wrapWithIndent"),__name(getDisplayValue,"getDisplayValue"),__name(getMaskedValue,"getMaskedValue")}});function createStdinUpdateHandler(e,t,n,r){return(o,s)=>{e(s),o!==t.current&&(r(o),t.current=o,n.current(o))}}function createInkUpdateHandler(e,t,n,r){return(o,s)=>{e(s),o!==t.current&&(r(o),t.current=o,n.current(o))}}function TextInput({value:e,placeholder:t="",focus:n=!0,mask:r,showCursor:o=!0,onChange:s,onSubmit:i,onCursorChange:a,prefix:l="",prefixColor:u,singleLine:d=!1,maxWidth:m,stripBracketedPaste:g=!1,initialCursor:h}){const f=ie(!1),{valueRef:y,noteEmittedValue:w}=useEchoAwareValueRef(e),S=useSyncedRef(s),{cursor:E,setCursor:v,cursorRef:C}=useCursorState({value:e,focus:n,showCursor:o,initialCursor:h});re.useEffect(()=>{a?.(E)},[E,a]);const k=ce(createStdinUpdateHandler(v,y,S,w),[v,y,S,w]),T=ce(createInkUpdateHandler(v,y,S,w),[v,y,S,w]),_=ce(e=>{f.current=e},[]),x=ce(()=>f.current,[]);useRawStdinHandler({focus:n,valueRef:y,cursorRef:C,onUpdate:k,setHandled:_,stripBracketedPaste:g}),useInkInputHandler({focus:n,showCursor:o,valueRef:y,cursorRef:C,isHandledByStdin:x,onUpdate:T,onSubmit:i});const{stdout:A}=X(),P=A?.columns??80,I=getMaskedValue(e,r),M=u?Yr[u]:void 0,R=l?M?M(l):l:"",N=getDisplayValue(I,t,E,o,n),L=l?.length??0,$=R+N;if(d){const e=$.replace(/\n/g," ");return null!=m?re.createElement(Q,{width:m},re.createElement(Y,{wrap:"truncate"},e)):re.createElement(Y,{wrap:"truncate"},e)}const D=wrapWithIndent($,P,L);return re.createElement(Y,{wrap:"wrap"},D)}var Xr=__esm({"src/tui/text/text-input.tsx"(){Bt(),Hr(),Jr(),gr(),Yr={white:de.white,green:de.green,red:de.red,blue:de.blue,yellow:de.yellow,cyan:de.cyan,magenta:de.magenta,gray:de.gray,grey:de.gray},__name(createStdinUpdateHandler,"createStdinUpdateHandler"),__name(createInkUpdateHandler,"createInkUpdateHandler"),__name(TextInput,"TextInput")}});function bitmapHasAlpha(e){for(let t=3;t<e.length;t+=4)if((e[t]??255)<255)return!0;return!1}async function compressImageForSharing(e,t="image/png"){try{const n=Buffer.from(e,"base64"),r=n.length,o=await pe.fromBuffer(n),{width:s,height:i}=o.bitmap;if(!s||!i)return console.warn("[ImageCompression] Could not determine image dimensions"),null;const a=bitmapHasAlpha(o.bitmap.data),l=1200;let u,d,m=s,g=i;(s>l||i>l)&&(s>i?(g=Math.round(i*l/s),m=l):(m=Math.round(s*l/i),g=l),o.resize({w:m,h:g})),t.includes("png")&&a?(u=await o.getBuffer(ge.png),d="image/png"):(u=await o.getBuffer(ge.jpeg,{quality:95}),d="image/jpeg");const h=u.length;return{compressedBase64:u.toString("base64"),mediaType:d,originalSizeBytes:r,compressedSizeBytes:h,compressionRatio:r/h}}catch(e){return console.error("[ImageCompression] Failed to compress image:",e),null}}var Zr,eo,to,no=__esm({"src/utils/image-compression.ts"(){Bt(),__name(bitmapHasAlpha,"bitmapHasAlpha"),__name(compressImageForSharing,"compressImageForSharing")}}),ro={};function isClipboardAvailable(){if(void 0!==Zr)return Zr;const e=process.platform;return Zr="darwin"===e||"win32"===e||"linux"===e&&isLinuxClipboardAvailable()}function isLinuxClipboardAvailable(){const e=process.env.DISPLAY;if(e){const t=e.match(/^:(\d+)/);return!t||D.existsSync(`/tmp/.X11-unix/X${t[1]}`)}return!1}function _resetClipboardAvailableCacheForTests(){Zr=void 0}async function detectDroppedImageFile(e){try{if(!e||0===e.trim().length)return null;let t=e.trim();if((t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),t=t.replace(/\\(.)/g,"$1"),t.includes("\n")||t.includes("\r"))return null;const n=l(t).toLowerCase(),r=eo[n];if(!r)return null;const o=a(t);if(!D.existsSync(o))return null;const s=D.readFileSync(o).toString("base64");if(!s||0===s.length)return null;if(s.length>32e6)return null;const i=await compressImageForSharing(s,r);return i?{data:i.compressedBase64,mediaType:i.mediaType}:to.has(n)?{data:s,mediaType:r}:null}catch(e){return null}}async function detectClipboardImage(){try{if(!isClipboardAvailable())return null;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{if(!isClipboardAvailable())return null;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}}__export(ro,{_resetClipboardAvailableCacheForTests:()=>_resetClipboardAvailableCacheForTests,detectClipboardImage:()=>detectClipboardImage,detectClipboardText:()=>detectClipboardText,detectDroppedImageFile:()=>detectDroppedImageFile,isClipboardAvailable:()=>isClipboardAvailable});var oo,so=__esm({"src/utils/clipboard-image.ts"(){Bt(),no(),__name(isClipboardAvailable,"isClipboardAvailable"),__name(isLinuxClipboardAvailable,"isLinuxClipboardAvailable"),__name(_resetClipboardAvailableCacheForTests,"_resetClipboardAvailableCacheForTests"),eo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/png",".tiff":"image/png"},to=new Set([".png",".jpg",".jpeg",".gif",".webp"]),__name(detectDroppedImageFile,"detectDroppedImageFile"),__name(detectClipboardImage,"detectClipboardImage"),__name(detectClipboardText,"detectClipboardText")}});function isCliTheme(e){return"string"==typeof e&&oo.has(e)}var io,ao,lo,co=__esm({"src/utils/cli-theme.ts"(){Bt(),oo=new Set(["dark","light"]),__name(isCliTheme,"isCliTheme")}});function getSupportedEfforts(e){return findModelById(e)?.reasoningEfforts??null}function modelSupportsReasoningEffort(e){return null!==getSupportedEfforts(e)}function getContextLimit(e){const t=getCanonicalModelId(e);return findModelById(t)?.contextWindow??io}function findModelById(e){return Object.values(pn).find(t=>t.id===e)}function getProviderFromModel(e){return findModelById(e)?.provider??Qt.ANTHROPIC}function getAllModelOptions(){return Object.values(pn)}function getModelGroupLabel(e){return e.vendorLabel??yn[e.provider]??e.provider}function groupModelsByDisplayOrder(e){const t=new Map;for(const n of e){const e=getModelGroupLabel(n),r=t.get(e)??[];r.push(n),t.set(e,r)}return[...wn.filter(e=>t.has(e)),...[...t.keys()].filter(e=>!wn.includes(e))].map(e=>({label:e,models:t.get(e)}))}function getModelGroupsInOrder(){return groupModelsByDisplayOrder(getAllModelOptions().filter(e=>!e.hidden))}function resolveKnownModelId(e){const t=getCanonicalModelId(e);return findModelById(t)?t:void 0}function modelSupportsVision(e){const t=findModelById(getCanonicalModelId(e));return!t?.inputModalities||t.inputModalities.includes("image")}function ossEntryMatches(e,t){return e.canonicalId.toLowerCase()===t||Object.values(e.providers).some(e=>"string"==typeof e&&e.toLowerCase()===t)}function tryResolveCanonical(e){const t=(hn[e.toLowerCase()]??e).toLowerCase(),n=Object.values(pn).find(e=>e.id.toLowerCase()===t);if(n)return n.id;const r=gn.find(e=>ossEntryMatches(e,t));return r?.canonicalId}function getCanonicalModelId(e){if(!e)return e;const t=e.startsWith(lo)?e.slice(lo.length):e,n=tryResolveCanonical(t);if(n)return n;const r=t.replace(ao,"");return r===t?t:tryResolveCanonical(r)??t}function getModelDisplayName(e){const t=getCanonicalModelId(e),n=Object.values(pn).find(e=>e.id===t);return n?.name??e}var uo,mo,po,ho,fo,yo,wo,So,bo=__esm({"../shared/src/utils/models.ts"(){Bt(),_n(),__name(getSupportedEfforts,"getSupportedEfforts"),__name(modelSupportsReasoningEffort,"modelSupportsReasoningEffort"),io=2e5,__name(getContextLimit,"getContextLimit"),__name(findModelById,"findModelById"),__name(getProviderFromModel,"getProviderFromModel"),__name(getAllModelOptions,"getAllModelOptions"),__name(getModelGroupLabel,"getModelGroupLabel"),__name(groupModelsByDisplayOrder,"groupModelsByDisplayOrder"),__name(getModelGroupsInOrder,"getModelGroupsInOrder"),__name(resolveKnownModelId,"resolveKnownModelId"),__name(modelSupportsVision,"modelSupportsVision"),ao=/[-@]\d{8}$/,lo="workers-ai/@cf/",__name(ossEntryMatches,"ossEntryMatches"),__name(tryResolveCanonical,"tryResolveCanonical"),__name(getCanonicalModelId,"getCanonicalModelId"),__name(getModelDisplayName,"getModelDisplayName")}});async function loadUserConfig(){try{const e=getConfigFile();return parseJSON(await C.readFile(e,"utf-8"))||{}}catch{return{}}}async function saveUserConfig(e){try{const t=getConfigFile();$.writeFileSync(t,JSON.stringify(e,null,2)),$.chmodSync(t,384)}catch(e){throw new Error(`Failed to save user config: ${e}`)}}async function updateUserConfig(e){const t=await loadUserConfig(),n=t.model,r={...t,...e,model:e.model??n};await saveUserConfig(r)}async function isOAuthEnforced(){if(null!==uo)return uo;if(isInternalTeamDisableFlagPresent())return dlog("[Auth] OAuth disabled via --xco flag"),await updateUserConfig({forceOAuth:!1}),uo=!1,!1;if(isInternalTeamFlagPresent()){dlog("[Auth] OAuth enabled via --co flag");const e=await loadUserConfig(),t=await resolveOAuthProvider({currentProvider:e.provider});return dlog("[Auth] --co resolved provider",t),await updateUserConfig({provider:t,forceOAuth:!0}),uo=!0,!0}const e=await loadUserConfig();return(uo=e.forceOAuth??!1)&&dlog("[Auth] using OAuth (persisted from previous --co)"),uo}async function resolveOAuthProvider(e){const{currentProvider:t}=e;if(t&&ho.includes(t))return t;const n=await Bn.get("github-copilot"),r=await Bn.get("codex"),o=(await Bn.get("anthropic"),n?"github-copilot":r?"codex":"anthropic");return dlog("[Auth] resolveOAuthProvider fallback",{from:t,to:o}),o}function validateOAuthToken(e){const{token:t,provider:n}=e;if(n&&ho.includes(n)&&!t)throw new Error(zn)}async function getOAuthCredentials(e){const{provider:t}=e;return"anthropic"===t?{token:await Wn.getValidAccessToken(),oauthProvider:"anthropic"}:"github-copilot"===t?{token:await tr.getValidAccessToken(),oauthProvider:"github-copilot"}:"codex"===t?{token:await er.getValidAccessToken(),oauthProvider:"codex"}:{token:void 0,oauthProvider:void 0}}function readDiskDefaultModel(){if(null!==fo)return fo;try{const e=getConfigFile(),t=parseJSON($.readFileSync(e,"utf-8"))||{};fo=t.model??fn}catch{fo=fn}return fo}async function getSelectedModel(){return yo||So||readDiskDefaultModel()}function setModelOverride(e){yo=e}function clearModelOverride(){yo=void 0}function setGoalMaxTurnsOverride(e){wo=e}function getGoalMaxTurnsOverride(){return wo}function setSessionModel(e){So=e}function hasRuntimeModelSelection(){return void 0!==yo||void 0!==So}function shouldAdoptResumedModel(e){const{inTuiResume:t}=e;return t||!hasRuntimeModelSelection()}function getConfiguredModel(){return yo||So||readDiskDefaultModel()}function setSelectedModel(e){setSessionModel(e.model)}async function persistDefaultModel(e){await updateUserConfig({model:e.model}),fo=e.model}function getReasoningEffort(e){try{const t=getConfigFile(),n=parseJSON($.readFileSync(t,"utf-8"))||{};return n.reasoningEffort?.[e]}catch{return}}async function setReasoningEffort(e){const{modelId:t,effort:n}=e,r={...(await loadUserConfig()).reasoningEffort??{}};if(void 0===n)return delete r[t],void await updateUserConfig({reasoningEffort:r});r[t]=n,await updateUserConfig({reasoningEffort:r})}function getCliTheme(){if(null!==po)return po;try{const e=getConfigFile(),t=parseJSON($.readFileSync(e,"utf-8"))||{};return po=isCliTheme(t.theme)?t.theme:"dark"}catch{return po="dark","dark"}}async function setCliTheme(e){const{theme:t}=e;await updateUserConfig({theme:t}),po=t}async function setThemeOnboarded(e){await updateUserConfig({themeOnboarded:e.themeOnboarded})}function isExperimentalEnabled(){return process.argv.includes("--experimental")}async function migrateDeprecatedModel(){try{const e=await loadUserConfig();if(!e.model)return;const t=hn[e.model];if(!t)return;dlog(`[Migration] Upgrading model ${e.model} → ${t}`),await saveUserConfig({...e,model:t}),fo=t}catch(e){dlog(`[Migration] Failed to migrate model: ${e}`)}}function getCompactMode(){if(null!==mo)return mo;try{const e=getConfigFile(),t=(parseJSON($.readFileSync(e,"utf-8"))||{}).compactMode;return mo="default"===t||"fast"===t?t:"default"}catch{return mo="default","default"}}async function setCompactMode(e){const{mode:t}=e;mo=t,await updateUserConfig({compactMode:t})}var Eo,vo,Co=__esm({"src/utils/user-config.ts"(){Bt(),_n(),Un(),Jn(),Zn(),ar(),lr(),Xn(),co(),ir(),Ro(),No(),bo(),__name(loadUserConfig,"loadUserConfig"),__name(saveUserConfig,"saveUserConfig"),__name(updateUserConfig,"updateUserConfig"),uo=null,mo=null,po=null,__name(isOAuthEnforced,"isOAuthEnforced"),ho=["anthropic","github-copilot","codex"],__name(resolveOAuthProvider,"resolveOAuthProvider"),__name(validateOAuthToken,"validateOAuthToken"),__name(getOAuthCredentials,"getOAuthCredentials"),fo=null,__name(readDiskDefaultModel,"readDiskDefaultModel"),__name(getSelectedModel,"getSelectedModel"),__name(setModelOverride,"setModelOverride"),__name(clearModelOverride,"clearModelOverride"),__name(setGoalMaxTurnsOverride,"setGoalMaxTurnsOverride"),__name(getGoalMaxTurnsOverride,"getGoalMaxTurnsOverride"),__name(setSessionModel,"setSessionModel"),__name(hasRuntimeModelSelection,"hasRuntimeModelSelection"),__name(shouldAdoptResumedModel,"shouldAdoptResumedModel"),__name(getConfiguredModel,"getConfiguredModel"),__name(setSelectedModel,"setSelectedModel"),__name(persistDefaultModel,"persistDefaultModel"),__name(getReasoningEffort,"getReasoningEffort"),__name(setReasoningEffort,"setReasoningEffort"),__name(getCliTheme,"getCliTheme"),__name(setCliTheme,"setCliTheme"),__name(setThemeOnboarded,"setThemeOnboarded"),__name(isExperimentalEnabled,"isExperimentalEnabled"),__name(migrateDeprecatedModel,"migrateDeprecatedModel"),__name(getCompactMode,"getCompactMode"),__name(setCompactMode,"setCompactMode")}}),ko=__esm({"src/tui/terminal-link.tsx"(){Bt(),Vr(),Eo=__name(({url:e,text:t,dimColor:n=!1,color:r})=>{const o=`]8;;${e}${t}]8;;`,s=r??(n?br.DIM:void 0);return re.createElement(Y,{dimColor:n&&!!r,color:s},o)},"TerminalLink")}}),To=__esm({"src/tui/anthropic-auth.tsx"(){Bt(),Xr(),Zn(),Xn(),so(),Qr(),Co(),Vr(),ko(),vo=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=se(""),[s,i]=se(null),[a,l]=se(!1),[u,d]=se(null),[m,g]=se(!0),[h,f]=se(!1),[y,w]=se(!1);ae(()=>{const{url:e,verifier:t,state:n}=Wn.createAuthorizationUrl();i({url:e,verifier:t,state:n})},[]);const S=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||y){if(!y||t.isPasteEnd){if(y&&t.isPasteEnd){w(!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(w(!0),t.isPasteEnd){w(!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}},[y]);Z((e,n)=>{if(n.escape&&t(),m&&!h)if(n.return||"y"===e||"Y"===e){if(!s)return;he(s.url).then(()=>{f(!0),g(!1)}).catch(()=>{d(`Failed to open browser. Please manually open: ${s.url}`),f(!0),g(!1)})}else"n"!==e&&"N"!==e||t()});const E=__name(async()=>{if(r.trim()&&s&&!a){l(!0),d(null);try{const t=r.split("#")[0].trim();await Wn.exchangeCodeForTokens(t,s.verifier,s.state),await updateUserConfig({provider:"anthropic"}),e()}catch(e){const t=e instanceof Error?e.message:"Authentication failed";d(t),l(!1),n&&n(t)}}},"handleSubmit");return m&&!h?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"Anthropic Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Open the Anthropic auth page?",re.createElement(Y,{color:br.DIM}," (Y/n)")))):re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"Anthropic Authentication")),s&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Login: "),re.createElement(Eo,{url:s.url,text:"Open auth page ↗",color:br.CYAN})),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"After authorizing, copy the code and paste it below:")),u&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},"Error: ",u)),re.createElement(Q,null,re.createElement(Y,null,"Authorization code: "),re.createElement(TextInput,{mask:"*",focus:!0,value:r,onChange:S,onSubmit:E,placeholder:"Paste code here..."})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Enter to submit or ESC to cancel")))},"AnthropicAuth")}});function createOSC8Link(e,t,n=!0){return`${n?"":""}]8;;${e}${t||e}]8;;${n?"":""}`}var _o,xo,Ao,Po=__esm({"src/utils/osc8-link.ts"(){Bt(),__name(createOSC8Link,"createOSC8Link")}}),Io=__esm({"src/tui/codex-auth.tsx"(){Bt(),ar(),Xn(),Co(),Po(),Vr(),_o=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=se("confirm"),[s,i]=se(""),[a,l]=se(null),[u,d]=se(""),m=ie(null),g=ce(async()=>{const t=new AbortController;m.current=t;try{await er.login({onAuth:__name(({authorizeUrl:e})=>{i(e),o("waiting"),he(e).catch(()=>{})},"onAuth"),onProgress:__name(e=>{d(e),e.startsWith("Exchanging")&&o("exchanging")},"onProgress"),signal:t.signal}),await updateUserConfig({provider:"codex"}),o("success"),e()}catch(e){if(t.signal.aborted)return;const r=e instanceof Error?e.message:"Authentication failed";l(r),o("error"),n?.(r)}},[e,n]);return ae(()=>()=>{m.current?.abort()},[]),Z((e,n)=>{if(n.escape)return m.current?.abort(),void t();if("confirm"===r){if(n.return||"y"===e||"Y"===e)return void g();"n"!==e&&"N"!==e||t()}}),"confirm"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"ChatGPT (Codex) Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"This will open your browser to sign in with ChatGPT.")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Continue?",re.createElement(Y,{color:br.DIM}," (Y/n)")))):"waiting"===r||"exchanging"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"ChatGPT (Codex) Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,createOSC8Link(s,"Open auth page ↗"))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},u||"Waiting for authorization...")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to cancel"))):"error"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"ChatGPT (Codex) Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},"Error: ",a)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to go back"))):null},"CodexAuth")}}),Mo=__esm({"src/tui/copilot-auth.tsx"(){Bt(),lr(),Xn(),Co(),Vr(),xo=__name(({onSuccess:e,onCancel:t,onFailure:n})=>{const[r,o]=se("confirm"),[s,i]=se(""),[a,l]=se(""),[u,d]=se(null),[m,g]=se(""),h=ie(null),f=ce(async()=>{const t=new AbortController;h.current=t;try{await tr.login({onAuth:__name(({userCode:e,verificationUri:t})=>{i(e),l(t),o("device-code"),he(t).catch(()=>{})},"onAuth"),onProgress:__name(e=>{g(e),"Waiting for authorization..."===e&&o("polling")},"onProgress"),signal:t.signal}),await updateUserConfig({provider:"github-copilot"}),o("success"),e()}catch(e){if(t.signal.aborted)return;const r=e instanceof Error?e.message:"Authentication failed";d(r),o("error"),n&&n(r)}},[e,n]);return ae(()=>()=>{h.current?.abort()},[]),Z((e,n)=>{if(n.escape)return h.current?.abort(),void t();if("confirm"===r){if(n.return||"y"===e||"Y"===e)return void f();"n"!==e&&"N"!==e||t()}}),"confirm"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"GitHub Copilot Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"This will open GitHub to authorize Copilot access.")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Continue?",re.createElement(Y,{color:br.DIM}," (Y/n)")))):"device-code"===r||"polling"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"GitHub Copilot Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Enter this code on GitHub:"," ",re.createElement(Y,{bold:!0,color:br.GREEN},s))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Open: ",a)),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"polling"===r?"Waiting for authorization...":m||"Starting...")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to cancel"))):"error"===r?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{bold:!0,color:br.CYAN},"GitHub Copilot Authentication")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},"Error: ",u)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Press ESC to go back"))):null},"CopilotAuth")}});function getProviderDisplayName(e){return e?Sn[e]?.label??e:"None"}function getProviderConfig(e){return Ao[e]}function isInternalTeamFlagPresent(){return process.argv.includes(zt)}function isInternalTeamDisableFlagPresent(){return process.argv.includes(Ht)}function isInternalTeamFlagEnforced(){if(isInternalTeamDisableFlagPresent())return!1;if(isInternalTeamFlagPresent())return!0;try{const e=getConfigFile();return(parseJSON($.readFileSync(e,"utf-8"))||{}).forceOAuth??!1}catch{return!1}}function getProviderOptions(){const e=isInternalTeamFlagEnforced();return Object.values(Ao).filter(t=>!t.hidden||e).map(e=>({label:`${e.displayName} (${e.description})`,value:e.id}))}var Ro=__esm({"src/utils/provider-config.ts"(){Bt(),_n(),Zn(),ar(),lr(),To(),Io(),Mo(),Un(),No(),(Ao=Object.fromEntries(Object.values(Sn).map(e=>[e.id,{id:e.id,displayName:e.label,description:e.description,requiresAuth:e.requiresAuth,hidden:!e.visibleInNormalMode}]))).anthropic&&(Ao.anthropic.authComponent=vo,Ao.anthropic.checkAuth=async()=>!!await Wn.getValidAccessToken()),Ao["github-copilot"]&&(Ao["github-copilot"].authComponent=xo,Ao["github-copilot"].checkAuth=async()=>!!await tr.getValidAccessToken()),Ao.codex&&(Ao.codex.authComponent=_o,Ao.codex.checkAuth=async()=>!!await er.getValidAccessToken()),__name(getProviderDisplayName,"getProviderDisplayName"),__name(getProviderConfig,"getProviderConfig"),__name(isInternalTeamFlagPresent,"isInternalTeamFlagPresent"),__name(isInternalTeamDisableFlagPresent,"isInternalTeamDisableFlagPresent"),__name(isInternalTeamFlagEnforced,"isInternalTeamFlagEnforced"),__name(getProviderOptions,"getProviderOptions")}});function isInternalTeamDisableOAuthFlagPresent(){return process.argv.includes(Ht)}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 k.readFile(e,"utf-8"),n=JSON.parse(t),r=n.provider||null,o=n.forceOAuth||!1,s=isInternalTeamFlagPresent();if(isInternalTeamDisableOAuthFlagPresent())return await updateUserConfig({provider:Sn["command-code"].id,forceOAuth:!1}),Sn["command-code"].id;if(s||o){if(r)return await updateUserConfig({forceOAuth:!0}),r;const e=await resolveOAuthProvider({currentProvider:r});return await updateUserConfig({provider:e,forceOAuth:!0}),e}return r}catch{return null}}function getIsExpandToolShortcut(e,t){return isCtrlKey({inputChar:t,key:e,letter:"o",ctrlCode:15})}function formatTime2(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function formatTokens(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}var No=__esm({"src/utils/utils.ts"(){Bt(),_n(),Un(),Yn(),Ro(),Co(),__name(isInternalTeamDisableOAuthFlagPresent,"isInternalTeamDisableOAuthFlagPresent"),__name(formatDate,"formatDate"),__name(parseJSON,"parseJSON"),__name(getConfiguredProvider,"getConfiguredProvider"),__name(getIsExpandToolShortcut,"getIsExpandToolShortcut"),__name(formatTime2,"formatTime"),__name(formatTokens,"formatTokens")}});function isLocalDevelopmentBuild(){try{const e=process.argv[1];if(!e)return!1;if(e.includes("/usr/local/bin/dmd"))return!0;const t=D.realpathSync(e);return!(!t.includes("/dist/index.mjs")||t.includes("node_modules"))}catch{return!1}}var Lo=__esm({"src/utils/is-local-dev.ts"(){Bt(),__name(isLocalDevelopmentBuild,"isLocalDevelopmentBuild")}});function getTelemetryEnv(){return isLocalDevelopmentBuild()?"local":Tn()}function getAxiomToken(){switch(getTelemetryEnv()){case"staging":return At;case"local":return Pt;default:return xt}}function isTelemetryEnabled(){if("1"===process.env.DO_NOT_TRACK||"true"===process.env.DO_NOT_TRACK)return!1;try{const e=getConfigFile();return!1!==(parseJSON($.readFileSync(e,"utf-8"))||{}).telemetry}catch{return!0}}function hasAxiomToken(){return Boolean(getAxiomToken())}var $o=__esm({"src/utils/telemetry/config.ts"(){Bt(),Un(),No(),xn(),Lo(),kn(),kn(),__name(getTelemetryEnv,"getTelemetryEnv"),__name(getAxiomToken,"getAxiomToken"),__name(isTelemetryEnabled,"isTelemetryEnabled"),__name(hasAxiomToken,"hasAxiomToken")}}),Do={};function getPackageJson(){const e=import.meta.url,t=d(e);let s=r(t);const{root:i}=o(s);for(;;){const e=n(s,"package.json");if(O(e))return JSON.parse(j(e,"utf8"));if(s===i)throw new Error("Could not find package.json");s=r(s)}}__export(Do,{getPackageJson:()=>getPackageJson});var Oo,Fo,jo,Uo,Bo,qo,zo,Ho,Wo,Go=__esm({"src/utils/package.ts"(){Bt(),__name(getPackageJson,"getPackageJson")}});function parseRetryAfter(e){if(!e)return null;const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.min(1e3*t,Wo);const n=Date.parse(e);if(Number.isFinite(n)){const e=n-Date.now();if(e>0)return Math.min(e,Wo)}return null}function installOtlpRetryFetch(){const e=globalThis.fetch;if(!e||e.__commandcodeOtlpWrapped)return;const t=__name(async(t,n)=>{const r="string"==typeof t?t:t.url??"";if("string"!=typeof r||!r.includes(_t))return e(t,n);let o,s=0;for(;s<=Ho;){const r=await e(t,n);if(o=r,429!==r.status&&430!==r.status)return r;if(s===Ho)break;const i=parseRetryAfter(r.headers.get("retry-after")),a=Math.min(200*Math.pow(2,s),Wo),l=i??a;await new Promise(e=>setTimeout(e,l)),s++}return o},"wrapped");t.__commandcodeOtlpWrapped=!0,globalThis.fetch=t}function createAxiomExporter(){return installOtlpRetryFetch(),new Fo({url:_t,headers:{Authorization:`Bearer ${getAxiomToken()}`,"X-Axiom-Dataset":Tt}})}function createServiceResource(){const e=getPackageJson(),n=process.execPath,r=t.basename(n)||"unknown";return jo({[Uo]:It,[Bo]:e.version,"process.executable.name":r,"process.runtime.name":"node","process.runtime.version":process.version,"process.pid":process.pid})}function createTelemetrySDK(){const e=createAxiomExporter(),t=createServiceResource(),n="1"===process.env.COMMAND_CODE_TELEMETRY_SYNC?new zo(e):new qo(e,{maxQueueSize:Rt,maxExportBatchSize:Nt,scheduledDelayMillis:Lt,exportTimeoutMillis:$t});return new Oo({resource:t,spanProcessors:[n],autoDetectResources:!1})}var Vo=__esm({"src/utils/telemetry/sdk-factory.ts"(){Bt(),kn(),$o(),Go(),({NodeSDK:Oo}=fe),({OTLPTraceExporter:Fo}=ye),({resourceFromAttributes:jo}=we),({ATTR_SERVICE_NAME:Uo,ATTR_SERVICE_VERSION:Bo}=Se),({BatchSpanProcessor:qo,SimpleSpanProcessor:zo}=be),Ho=2,Wo=1500,__name(parseRetryAfter,"parseRetryAfter"),__name(installOtlpRetryFetch,"installOtlpRetryFetch"),__name(createAxiomExporter,"createAxiomExporter"),__name(createServiceResource,"createServiceResource"),__name(createTelemetrySDK,"createTelemetrySDK")}});function resolveNearestAncestor(e){let n=t.dirname(e),r=t.basename(e);for(;n!==t.dirname(n);)try{return t.join(D.realpathSync(n),r)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code){r=t.join(t.basename(n),r),n=t.dirname(n);continue}return null}return null}function resolveSymlinks(e){try{return D.realpathSync(e)}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))return null}try{if(D.lstatSync(e).isSymbolicLink())return null}catch{}return resolveNearestAncestor(e)}function resolvePlansDir(e){try{return D.realpathSync(e)}catch{return e}}function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=S.homedir(),o=n.startsWith("~/")?t.join(r,n.slice(2)):n,s=resolveSymlinks(t.resolve(o));if(!s)return!1;const i=resolvePlansDir(t.join(r,".commandcode","plans"));return s.startsWith(i+t.sep)||s===i}var Ko,Qo,Yo,Jo=__esm({"src/utils/plan-path-validator.ts"(){Bt(),_n(),__name(resolveNearestAncestor,"resolveNearestAncestor"),__name(resolveSymlinks,"resolveSymlinks"),__name(resolvePlansDir,"resolvePlansDir"),__name(isPlanPath,"isPlanPath")}});function setCurrentPermissionMode(e){Yo=e}function normalizePathForComparison(e){const n=t.normalize(e);return"win32"===process.platform?n.toLowerCase():n}function areSamePath(e,t){return normalizePathForComparison(e)===normalizePathForComparison(t)}function getCanonicalPath(e){try{return D.realpathSync(e)}catch(n){const r=n.code;return"ENOENT"!==r&&console.error(`Warning: Could not resolve canonical path for "${e}" (${r}). Path comparison may be less reliable.`),t.normalize(e)}}function canonicalizeForLookup(e){try{let n=t.resolve(e);const r=[];for(;!D.existsSync(n);){const o=t.dirname(n);if(o===n)return t.normalize(e);r.unshift(t.basename(n)),n=o}return t.join(getCanonicalPath(n),...r)}catch{return t.normalize(e)}}function formatDirectoryForDisplay(e){const n=canonicalizeForLookup(t.normalize(e)),r=getCanonicalPath(process.cwd()),o=S.homedir();if(isPathInDirectory(n,r)){const e=t.relative(r,n);return e?`./${e}`:"."}if(o&&isPathInDirectory(n,o)){const e=t.relative(o,n);return e?`~/${e}`:"~"}return n}function isPathInDirectory(e,n){const r=normalizePathForComparison(e),o=normalizePathForComparison(n),s=o.endsWith(t.sep)?o:o+t.sep;return r===o||r.startsWith(s)}function findSensitiveDirectoryConflict(e){const n=[t.normalize(e),getCanonicalPath(e)];for(const e of Ko){const r=[t.normalize(e),getCanonicalPath(e)];for(const e of n)for(const t of r)if(isPathInDirectory(e,t)||isPathInDirectory(t,e))return t}return null}function resolveDirectoryPath(e){let n=e.trim();return n.startsWith("~")&&(n=t.join(S.homedir(),n.slice(1))),t.isAbsolute(n)||(n=t.resolve(process.cwd(),n)),t.normalize(n)}function createSkippedResult(e){const{inputPath:t,absolutePath:n,code:r}=e,o=formatDirectoryForDisplay(n);return{status:"skipped",inputPath:t,absolutePath:n,displayPath:o,code:r,message:"ALREADY_IN_WORKSPACE"===r?`${o} is already accessible from the current workspace`:`${o} is already added`}}function createErrorResult(e){const{inputPath:t,code:n,message:r}=e;return{status:"error",inputPath:t,code:n,message:r}}function addDirectory(e){const t=e.trim();if(!t)return createErrorResult({inputPath:e,code:"EMPTY_PATH",message:"Directory path cannot be empty"});const n=resolveDirectoryPath(e);let r,o;try{r=D.statSync(n)}catch(n){return"ENOENT"===n.code?createErrorResult({inputPath:e,code:"NOT_FOUND",message:`Directory does not exist: ${t}`}):createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}if(!r.isDirectory())return createErrorResult({inputPath:e,code:"NOT_A_DIRECTORY",message:`${formatDirectoryForDisplay(n)} is not a directory`});try{D.accessSync(n,D.constants.R_OK),o=getCanonicalPath(n)}catch{return createErrorResult({inputPath:e,code:"NOT_READABLE",message:`Directory is not readable: ${t}`})}const s=findSensitiveDirectoryConflict(o);if(s)return createErrorResult({inputPath:e,code:"SENSITIVE_DIRECTORY",message:`Cannot add ${formatDirectoryForDisplay(o)} because it overlaps sensitive path ${formatDirectoryForDisplay(s)}`});const i=getCanonicalPath(process.cwd());return isPathInDirectory(o,i)?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_IN_WORKSPACE"}):Qo.some(e=>isPathInDirectory(o,e)||isPathInDirectory(e,o))?createSkippedResult({inputPath:e,absolutePath:o,code:"ALREADY_ADDED"}):(Qo.push(o),{status:"added",inputPath:e,absolutePath:o,displayPath:formatDirectoryForDisplay(o)})}function getAdditionalDirectories(){return[...Qo]}function removeAdditionalDirectory(e){if(!e.trim())return!1;const t=getCanonicalPath(resolveDirectoryPath(e)),n=Qo.findIndex(e=>areSamePath(t,e));return-1!==n&&(Qo.splice(n,1),!0)}function isPathInAdditionalDirs(e){const t=canonicalizeForLookup(e);return Qo.some(e=>isPathInDirectory(t,e))}function isPathInWorkspace(e){const t=canonicalizeForLookup(e);return!("plan"!==Yo||!isPlanPath({filePath:t}))||(isPathInDirectory(t,getCanonicalPath(process.cwd()))||isPathInAdditionalDirs(t))}function getWorkspaceDirectories(){return[t.resolve(process.cwd()),...getAdditionalDirectories()]}var Xo=__esm({"src/utils/additional-dirs.ts"(){Bt(),Jo(),Ko=new Set(["/etc","/root","/proc","/sys","/dev",t.join(S.homedir(),".ssh"),t.join(S.homedir(),".gnupg"),t.join(S.homedir(),".aws")]),Qo=[],Yo="standard",__name(setCurrentPermissionMode,"setCurrentPermissionMode"),__name(normalizePathForComparison,"normalizePathForComparison"),__name(areSamePath,"areSamePath"),__name(getCanonicalPath,"getCanonicalPath"),__name(canonicalizeForLookup,"canonicalizeForLookup"),__name(formatDirectoryForDisplay,"formatDirectoryForDisplay"),__name(isPathInDirectory,"isPathInDirectory"),__name(findSensitiveDirectoryConflict,"findSensitiveDirectoryConflict"),__name(resolveDirectoryPath,"resolveDirectoryPath"),__name(createSkippedResult,"createSkippedResult"),__name(createErrorResult,"createErrorResult"),__name(addDirectory,"addDirectory"),__name(getAdditionalDirectories,"getAdditionalDirectories"),__name(removeAdditionalDirectory,"removeAdditionalDirectory"),__name(isPathInAdditionalDirs,"isPathInAdditionalDirs"),__name(isPathInWorkspace,"isPathInWorkspace"),__name(getWorkspaceDirectories,"getWorkspaceDirectories")}});function getCurrentWorkingDirectory(){return global.COMMAND_CODE_CWD||process.cwd()}function getCurrentDate(){return(new Date).toISOString().split("T")[0]}function getEnvironmentInfo(){return`${S.platform()}-${S.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 D.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!e.name.startsWith(".")).filter(e=>!t.has(e.name)).map(e=>e.name).sort()}catch{return[]}}function getAccessibleDirectoryStructure(){return[...getRootDirectoryStructure(),...getAdditionalDirectories().map(e=>`scope:${formatDirectoryForDisplay(e)}`)]}function isGitRepository(){try{return Ce("git rev-parse --git-dir",{stdio:"ignore",cwd:getCurrentWorkingDirectory()}),!0}catch{return!1}}function getCurrentBranch(){try{return Ce("git branch --show-current",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}}function getMainBranch(){const e=getCurrentWorkingDirectory();try{const t=Ce("git symbolic-ref --short refs/remotes/origin/HEAD",{encoding:"utf8",cwd:e,stdio:["pipe","pipe","ignore"]}).trim().replace(/^origin\//,"");if(t)return t}catch{}try{const t=Ce("git branch -r",{encoding:"utf8",cwd:e,stdio:["pipe","pipe","ignore"]});return t.includes("origin/main")?"main":t.includes("origin/master")?"master":"main"}catch{return""}}function getGitStatus(){try{const e=Ce("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,i=[];return n>0&&i.push(`M ${n}`),r>0&&i.push(`A ${r}`),o>0&&i.push(`D ${o}`),s>0&&i.push(`?? ${s}`),i.join(", ")||e}catch{return""}}function getRecentCommits(){try{const e=Ce("git log --oneline -3",{encoding:"utf8",cwd:getCurrentWorkingDirectory(),stdio:["pipe","pipe","ignore"]}).trim();return e?e.split("\n"):[]}catch{return[]}}function getEnvironmentContext(){const e=isGitRepository(),t=getAdditionalDirectories();return{workingDir:getCurrentWorkingDirectory(),date:getCurrentDate(),environment:getEnvironmentInfo(),structure:getAccessibleDirectoryStructure(),isGitRepo:e,currentBranch:e?getCurrentBranch():"",mainBranch:e?getMainBranch():"",gitStatus:e?getGitStatus():"",recentCommits:e?getRecentCommits():[],...t.length>0?{additionalDirectories:t}:{}}}var Zo,es,ts,ns,rs,os=__esm({"src/utils/environment.ts"(){Bt(),Xo(),__name(getCurrentWorkingDirectory,"getCurrentWorkingDirectory"),__name(getCurrentDate,"getCurrentDate"),__name(getEnvironmentInfo,"getEnvironmentInfo"),__name(getRootDirectoryStructure,"getRootDirectoryStructure"),__name(getAccessibleDirectoryStructure,"getAccessibleDirectoryStructure"),__name(isGitRepository,"isGitRepository"),__name(getCurrentBranch,"getCurrentBranch"),__name(getMainBranch,"getMainBranch"),__name(getGitStatus,"getGitStatus"),__name(getRecentCommits,"getRecentCommits"),__name(getEnvironmentContext,"getEnvironmentContext")}});function generateSessionId(){return`sess_${Me().replace(/-/g,"").substring(0,16)}`}function hashPath(e){return M.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(),[Ot.SESSION_PROJECT_HASH]:hashPath(n),[Ot.SESSION_BRANCH_HASH]:r?hashPath(r):"unknown","session.cli_version":o,"session.platform":`${w.platform()}-${w.arch()}`,"session.node_version":process.version}}function startSession(){rs={},ns=null,ts=null,Zo=generateSessionId(),es=Date.now();try{const e=xe.getTracer(It),t=getCliVersion(),n=getCurrentWorkingDirectory(),r=getCurrentBranch(),o=buildSessionAttributes({sessionId:Zo,projectPath:n,gitBranch:r,cliVersion:t}),s=e.startSpan("session:cli",{attributes:o});ts=s.spanContext(),s.end()}catch{}return Zo}function getSessionId(){return Zo}function setActiveIterationSpanContext(e){ns=e}function getActiveIterationSpanContext(){return ns}function getTraceId(){return ns?ns.traceId:null}function getSessionContext(){return ns?xe.setSpanContext(Ae.active(),ns):Ae.active()}function endSession(e={}){const{status:t="success"}=e;if(es)try{const e=xe.getTracer(It),n=ts?[{context:ts,attributes:{"cmd.session.link_kind":"session_cli"}}]:void 0,r=e.startSpan("session:end",{attributes:{"session.id":Zo||"unknown","session.end_time":(new Date).toISOString(),"session.status":t,...rs},links:n,root:!0},xe.deleteSpan(Ae.active()));r.setStatus({code:"error"===t?Ie.ERROR:Ie.OK}),r.end()}catch{}ns=null,ts=null,Zo=null,es=null,rs={}}function updateSessionContext(e){es&&(rs={...rs,...e})}var ss,as,ls=__esm({"src/utils/telemetry/session.ts"(){Bt(),kn(),Go(),os(),Zo=null,es=null,ts=null,ns=null,rs={},__name(generateSessionId,"generateSessionId"),__name(hashPath,"hashPath"),__name(getCliVersion,"getCliVersion"),__name(buildSessionAttributes,"buildSessionAttributes"),__name(startSession,"startSession"),__name(getSessionId,"getSessionId"),__name(setActiveIterationSpanContext,"setActiveIterationSpanContext"),__name(getActiveIterationSpanContext,"getActiveIterationSpanContext"),__name(getTraceId,"getTraceId"),__name(getSessionContext,"getSessionContext"),__name(endSession,"endSession"),__name(updateSessionContext,"updateSessionContext")}});function getStatus(e){if("number"==typeof e.status)return e.status;if("number"==typeof e.statusCode)return e.statusCode;const t=(e.message||"").match(/\b(\d{3})\b/);if(t){const e=Number(t[1]);if(e>=400&&e<600)return e}}function categorizeError(e){if(!e||"object"!=typeof e)return ss.UNKNOWN;const t=e,n="string"==typeof t.code?t.code.toUpperCase():void 0,r=(t.name||"").toLowerCase(),o=(t.message||"").toLowerCase(),s=getStatus(t);return n&&as.has(n)?ss.NETWORK:"ETIMEDOUT"===n||o.includes("timeout")||o.includes("timed out")?ss.TIMEOUT:"ENOENT"===n||404===s?ss.NOT_FOUND:"EACCES"===n||"EPERM"===n?ss.PERMISSION:"ABORT_ERR"===n||"aborterror"===r||o.includes("abort")?ss.CANCELLED:401===s||403===s||o.includes("unauthorized")||o.includes("forbidden")?ss.AUTH:429===s||o.includes("rate limit")||o.includes("too many requests")?ss.RATE_LIMIT:void 0!==s&&s>=500&&s<600?ss.INTERNAL:void 0!==s&&s>=400&&s<500||r.includes("zod")||r.includes("validation")||o.includes("invalid")?ss.VALIDATION:"fetcherror"===r||o.includes("fetch failed")||o.includes("network")?ss.NETWORK:ss.UNKNOWN}function normalizeStackFrame(e){return e.replace(/0x[0-9a-fA-F]+/g,"0xN").replace(/:\d+:\d+/g,":N:N").replace(/file:\/\/\/[^\s)]+/g,"file:///N").replace(/(\/[^\s:)]+\/)+/g,"/N/").replace(/\b\d{4,}\b/g,"N")}function errorFingerprint(e){const t=e||{},n=t.name||"Error",r=(t.stack||"").split("\n").slice(1).map(e=>e.trim()).find(e=>e.startsWith("at ")&&!e.includes("node:internal")),o=r?`${n}|${normalizeStackFrame(r)}`:`${n}|${(t.message||"").slice(0,120)}`;return M.createHash("sha1").update(o).digest("hex").substring(0,16)}var cs=__esm({"src/utils/telemetry/error-categorization.ts"(){Bt(),ss={NETWORK:"network",AUTH:"auth",RATE_LIMIT:"rate_limit",TIMEOUT:"timeout",VALIDATION:"validation",NOT_FOUND:"not_found",PERMISSION:"permission",INTERNAL:"internal",CANCELLED:"cancelled",UNKNOWN:"unknown"},as=new Set(["ENOTFOUND","ECONNRESET","ECONNREFUSED","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE"]),__name(getStatus,"getStatus"),__name(categorizeError,"categorizeError"),__name(normalizeStackFrame,"normalizeStackFrame"),__name(errorFingerprint,"errorFingerprint")}});function setSpanStatus(e,t){"error"===t?e.setStatus({code:Ie.ERROR}):e.setStatus({code:Ie.OK})}function applyErrorAttributes(e,t){e.setAttribute("error.type",categorizeError(t)),e.setAttribute(Ot.ERROR_FINGERPRINT,errorFingerprint(t))}function createSpan(e){const{name:t,attributes:n}=e,r=xe.getTracer(It),o=Ae.active(),s=void 0!==xe.getSpan(o)?o:getSessionContext();return r.startSpan(t,{attributes:n},s)}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:Ie.ERROR,message:n.message}),applyErrorAttributes(t,n),r)for(const[e,n]of Object.entries(r))void 0!==n&&t.setAttribute(e,n)}var us,ds,ms=__esm({"src/utils/telemetry/spans.ts"(){Bt(),kn(),ls(),cs(),__name(setSpanStatus,"setSpanStatus"),__name(applyErrorAttributes,"applyErrorAttributes"),__name(createSpan,"createSpan"),__name(endSpan,"endSpan"),__name(recordError,"recordError")}});async function initAxiomAITelemetry(){if(!us&&!ds)try{const e=await import("axiom/ai").catch(e=>(ds=e instanceof Error?e.message:String(e),null));if(!e)return void dlog("[telemetry] axiom/ai not available — falling back to plain OTel");const t=xe.getTracer(It),n=isContentCaptureEnabled()?e.RedactionPolicy?.AxiomDefault:e.RedactionPolicy?.AxiomStrict??e.RedactionPolicy?.AxiomDefault;e.initAxiomAI?.({tracer:t,redactionPolicy:n}),us=!0}catch(e){ds=e instanceof Error?e.message:String(e)}}var ps,gs,hs,fs,ys,ws,Ss,bs,Es,vs,Cs,ks,Ts,_s,xs,As,Ps,Is,Ms=__esm({"src/utils/telemetry/axiom-ai.ts"(){Bt(),kn(),ir(),us=!1,ds=null,__name(initAxiomAITelemetry,"initAxiomAITelemetry")}});function dedentText(e){const t=e.split("\n");let n=1/0;for(const e of t){if(0===e.trim().length)continue;const t=e.length-e.trimStart().length;t>0&&t<n&&(n=t)}return n===1/0||0===n?e:t.map(e=>0===e.trim().length?e:e.length-e.trimStart().length>=n?e.slice(n):e).join("\n")}function getEffectiveWidth({padding:e=ws}={}){let t=80;return process.stdout.columns?t=process.stdout.columns:process.stderr.columns?t=process.stderr.columns:process.env.COLUMNS&&(t=Number(process.env.COLUMNS)),Math.max(40,t-e)}function truncateString({text:e,maxChars:t}){return e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`}function truncateCommand({command:e}){const t=e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~").replace(/C:\\Users\\[^\\]+/g,"~");if(t.length<=Ss)return t;if(t.includes(" && ")){const e=t.split(" && ")[0].trim();return e.length<=Ss-5?`${e} && ...`:truncateString({text:e,maxChars:Ss})}return truncateString({text:t,maxChars:Ss})}function truncateToVisualLines({output:e,maxVisualLines:t=ps,padding:n=ws,maxChars:r}){const o=getEffectiveWidth({padding:n}),s=r??t*o,i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").replace(/\u00A0/g," ").trim().split("\n");let a=0,l=i.length;for(let e=0;e<i.length;e++){const n=i[e];if(0===n.trim().length)continue;const r=Math.max(1,Math.ceil(n.length/o));if(!(a+r<=t)){l=Math.max(1,e);break}a+=r}const u=l<i.length,d=i.slice(l).reduce((e,t)=>e+Math.max(1,Math.ceil(t.length/o)),0),m=i.slice(0,l).filter(e=>e.trim().length>0).join("\n");if(m.length>s){const e=m.slice(0,s-3).trimEnd(),t=e.lastIndexOf("\n"),n=t>0?e.slice(0,t):e;return{text:u?n:`${n}...`,isTruncated:!0,remainingLines:d}}return{text:m,isTruncated:u,remainingLines:d}}var Rs=__esm({"src/utils/truncation.ts"(){Bt(),ps=2,gs=10,hs=10,fs=10,ys=20,ws=4,Ss=100,bs=100,Es=50,vs=100,Cs=100,ks=60,Ts=80,_s=2,xs=1e5,As=5e4,Ps=25e3,Is=1e3,__name(dedentText,"dedentText"),__name(getEffectiveWidth,"getEffectiveWidth"),__name(truncateString,"truncateString"),__name(truncateCommand,"truncateCommand"),__name(truncateToVisualLines,"truncateToVisualLines")}});function normalizeError(e){return e instanceof Error?e:new Error(String(e))}function sanitizeErrorForTelemetry(e){const{error:t,label:n="error"}=e,r=scrubPII(t.message),o=r.length>0?`${n}: ${r}`:n,s=new Error(o);s.name=t.name||"Error";const i=t.code;return void 0!==i&&(s.code=i),s}function scrubPII(e){return e.replace(/[A-Z]:[/\\](?:Users|Documents and Settings)[/\\][^\s:'"`,)}\]]+/gi,"[path]").replace(/\/(?:Users|home|root)\/[^\s:'"`,)}\]]+/g,"[path]").replace(/~\/[^\s:'"`,)}\]]+/g,"[path]").replace(/\b[0-9a-f]{32,}\b/gi,"[token]").replace(/\b(?:sk|key|token|pat|ghp|gho|ghs|ghu|ghr)-[A-Za-z0-9_-]{10,}\b/g,"[apikey]")}function sanitizeEndpoint(e){return e.split("?")[0]}var Ns=__esm({"src/utils/telemetry/sanitization.ts"(){Bt(),kn(),Rs(),__name(normalizeError,"normalizeError"),__name(sanitizeErrorForTelemetry,"sanitizeErrorForTelemetry"),__name(scrubPII,"scrubPII"),__name(sanitizeEndpoint,"sanitizeEndpoint")}});function createTrackingHandle(e){const{span:t}=e;return{span:t,end:__name(e=>{if("status"in e)e.error&&recordError({span:t,error:e.error}),endSpan({span:t,status:e.status});else{const{statusCode:n,error:r}=e;t.setAttribute("http.status_code",n),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}=e;return createTrackingHandle({span:createSpan({name:`execute_tool ${t}`,attributes:{[Dt.TOOL_NAME]:t}})})}function buildContextAttributes(e){const{component:t,heading:n,code:r,...o}=e,s={[Ot.ERROR_COMPONENT]:t,[Ot.ERROR_HEADING]:n};void 0!==r&&(s[Ot.ERROR_CODE]=String(r));for(const[e,t]of Object.entries(o))null!=t&&"object"!=typeof t&&(s[e]=String(t));return s}function trackError(e){const{error:t,context:n}=e,r=normalizeError(t),o=buildContextAttributes(n);o["error.type"]=categorizeError(t),o[Ot.ERROR_FINGERPRINT]=errorFingerprint(t);const s=createSpan({name:`error:${r.name}`,attributes:o});recordError({span:s,error:r}),s.end()}function trackEvent(e){const{name:t,context:n}=e;endSpan({span:createSpan({name:t,attributes:buildContextAttributes(n)}),status:"success"})}function trackAPICallStart(e){const{method:t,endpoint:n,cliVersion:r}=e,o=sanitizeEndpoint(n);return createTrackingHandle({span:createSpan({name:`api:${t}:${o}`,attributes:{"http.method":t,"http.url":o,...r?{"cli.version":r}:{}}})})}function getDisplayTraceId(){return getTraceId()||"unknown"}function systemInfo(e){const{userName:t,userId:n,orgLogin:r,orgId:o,platform:s,arch:i}=e,a={"os.type":s,"os.arch":i};t&&(a["user.name"]=t),n&&(a["user.id"]=n),r&&(a[Ot.ORG_LOGIN]=r),o&&(a[Ot.ORG_ID]=o),updateSessionContext(a)}var Ls,$s,Ds,Os,Fs=__esm({"src/utils/telemetry/events.ts"(){Bt(),kn(),cs(),Ns(),ls(),ms(),Ns(),__name(createTrackingHandle,"createTrackingHandle"),__name(trackToolStart,"trackToolStart"),__name(buildContextAttributes,"buildContextAttributes"),__name(trackError,"trackError"),__name(trackEvent,"trackEvent"),__name(trackAPICallStart,"trackAPICallStart"),__name(getDisplayTraceId,"getDisplayTraceId"),__name(systemInfo,"systemInfo")}}),js=__esm({"src/utils/telemetry/components.ts"(){Bt(),Ls={AUTH_FLOW:"auth-flow",ANTHROPIC_OAUTH:"anthropic-oauth",COPILOT_OAUTH:"copilot-oauth",CODEX_OAUTH:"codex-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",UPDATER:"updater",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",AGENT_LOOP:"agent-loop",CLI_ERROR_HANDLER:"cli-error-handler",TOOL_REPAIR:"tool-repair"}}});function initTelemetry(){if(Ds)return!0;if(!isTelemetryEnabled())return!1;if(!hasAxiomToken())return!1;try{return($s=createTelemetrySDK()).start(),Ds=!0,initAxiomAITelemetry(),!0}catch{return $s=null,Ds=!1,!1}}async function shutdownTelemetry(){if($s&&Ds)try{endSession(),await Promise.allSettled(Os),await Promise.race([$s.shutdown(),new Promise(e=>setTimeout(e,Mt))])}catch{}finally{$s=null,Ds=!1}}function shutdownTelemetrySync(){if(Ds)try{endSession()}catch{}}function isTelemetryInitialized(){return Ds}function registerStartupTask(e){Os.push(e)}var Us,Bs=__esm({"src/utils/telemetry/telemetry.ts"(){Bt(),Vo(),$o(),ls(),ms(),kn(),Ms(),Fs(),js(),cs(),$s=null,Ds=!1,Os=[],__name(initTelemetry,"initTelemetry"),__name(shutdownTelemetry,"shutdownTelemetry"),__name(shutdownTelemetrySync,"shutdownTelemetrySync"),__name(isTelemetryInitialized,"isTelemetryInitialized"),__name(registerStartupTask,"registerStartupTask")}});function getApiKeyFromEnv(){const e=process.env[Us]?.trim();return e&&e.length>0?e:null}async function readAuthFile(e){try{const t=getAuthFile(e),n=await k.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async function getAuthKey(e){const t=getApiKeyFromEnv();if(t)return t;const n=await readAuthFile(e);return n&&n.apiKey||null}async function getPersistedAuth(e){const t=await readAuthFile(e);return t?.apiKey?{authenticated:!0,userName:t.userName,apiKey:t.apiKey}:{authenticated:!1}}async function getUserName(e){const t=await readAuthFile(e);return t&&t.userName||""}async function checkAuthStatus(e){const t=getApiKeyFromEnv();if(t)return{authenticated:!0,apiKey:t,fromEnv:!0};const n=await readAuthFile(e);return n&&n.apiKey?{authenticated:!0,apiKey:n.apiKey,userName:n.userName}:{authenticated:!1,apiKey:null}}var qs=__esm({"src/utils/auth/auth-file.ts"(){Bt(),Un(),Us="COMMAND_CODE_API_KEY",__name(getApiKeyFromEnv,"getApiKeyFromEnv"),__name(readAuthFile,"readAuthFile"),__name(getAuthKey,"getAuthKey"),__name(getPersistedAuth,"getPersistedAuth"),__name(getUserName,"getUserName"),__name(checkAuthStatus,"checkAuthStatus")}});function isGenericUserName(e){return!e||"API Key"===e||"Manual API Key"===e}function formatUserSuffix(e){return isGenericUserName(e)?"":` as ${e}`}function formatColoredUserSuffix(e){return isGenericUserName(e)?"":` as ${de.cyan(e)}`}function formatAlreadyLoggedIn(e){return`Already logged in${formatUserSuffix(e)}`}function getStartedLine(){return`${de.dim("Run")} ${de.cyan("cmd")} ${de.dim("to get started.")}`}function getLoginSuccessSuffix(e,t){return isGenericUserName(e)?t?"":" successfully":formatColoredUserSuffix(e)}function formatLoginSuccessStyled(e){const{userName:t,authFileName:n,providerLabel:r,providerWarning:o}=e,s=getLoginSuccessSuffix(t,r),i=r?` with ${de.cyan(r)}`:"",a=[`${de.green(Re.tick)} ${de.bold("Logged in")}${s}${i}`];return o&&a.push(` ${de.yellow(Re.warning)} ${de.yellow(o)}`),a.push("",`${de.dim("API key stored in")} ${de.cyan(`~/.commandcode/${n}`)}`,getStartedLine()),a.join("\n")}function formatAlreadyLoggedInStyled(e){const t=formatColoredUserSuffix(e);return[`${de.green(Re.tick)} ${de.bold("Already logged in")}${t}`,"",getStartedLine()].join("\n")}function formatLogoutSuccess(e){return isGenericUserName(e)?"Logged out successfully":`Logged out as ${e}`}function formatNotAuthenticated(){return"Not currently authenticated"}function formatLogoutFailed(e){return`Logout failed: ${e}`}function formatLogoutWarnings(e){return 0===e.length?"":`Warnings: ${e.join(", ")}`}function formatAuthCancelled(){return"Authentication cancelled"}var zs,Hs=__esm({"src/utils/auth/auth-messages.ts"(){Bt(),_n(),__name(isGenericUserName,"isGenericUserName"),__name(formatUserSuffix,"formatUserSuffix"),__name(formatColoredUserSuffix,"formatColoredUserSuffix"),__name(formatAlreadyLoggedIn,"formatAlreadyLoggedIn"),__name(getStartedLine,"getStartedLine"),__name(getLoginSuccessSuffix,"getLoginSuccessSuffix"),__name(formatLoginSuccessStyled,"formatLoginSuccessStyled"),__name(formatAlreadyLoggedInStyled,"formatAlreadyLoggedInStyled"),__name(formatLogoutSuccess,"formatLogoutSuccess"),__name(formatNotAuthenticated,"formatNotAuthenticated"),__name(formatLogoutFailed,"formatLogoutFailed"),__name(formatLogoutWarnings,"formatLogoutWarnings"),__name(formatAuthCancelled,"formatAuthCancelled")}});function detectConfigParseError(){try{const e=getConfigFile();if(!$.existsSync(e))return null;const t=$.readFileSync(e,"utf-8");return""===t.trim()?null:null===parseJSON(t)?`config.json at ${e} is not valid JSON`:null}catch{return null}}async function buildStatusJson(e){const t=getPackageJson().version;if(e.error)return{authenticated:!1,version:t,error:e.error};if(!e.authenticated)return{authenticated:!1,version:t};const n=detectConfigParseError();if(n)return{authenticated:!0,version:t,error:n};const r={authenticated:!0,version:t};e.userName&&!isGenericUserName(e.userName)&&(r.user=e.userName);try{const e=await getConfiguredProvider();e&&(r.provider=e)}catch{}try{const e=getConfiguredModel();if(e){r.model=e;const t=findModelById(getCanonicalModelId(e))?.contextWindow;t&&(r.context_window=t)}}catch{}return r}async function statusAction(e){if(e.json){const e=Tn();let t;try{t=await checkAuthStatus(e)}catch(e){t={authenticated:!1,apiKey:null,error:e instanceof Error?e.message:"Unknown error"}}const n=await buildStatusJson(t),r=!n.authenticated||n.error?1:0;return void process.stdout.write(`${JSON.stringify(n)}\n`,()=>process.exit(r))}const t=De("Checking authentication status...").start();try{const e=Tn(),n=await checkAuthStatus(e);n.error&&(t.fail(de.red(`Status check failed: ${n.error}`)),process.exit(1)),n.authenticated||(t.fail(de.red("Not authenticated")),console.log(""),console.log(`${de.dim("Run")} ${de.cyan("cmd auth login")} ${de.dim("to authenticate.")}`),console.log(""),process.exit(1));const r=isGenericUserName(n.userName)?"":` as ${de.cyan(n.userName)}`;t.succeed("Authentication verified"),console.log(`${de.green(Re.tick)} ${de.bold("Authenticated")}${r}`),console.log(` ${de.dim("Provider:")} ${de.cyan("Command Code")}`),n.fromEnv&&console.log(` ${de.dim("Source:")} ${de.cyan(`$${Us}`)} ${de.dim("(env var)")}`),console.log(""),process.exit(0)}catch(e){t.fail(de.red(`Status check failed: ${e instanceof Error?e.message:"Unknown error"}`)),process.exit(1)}}var Ws,Gs,Vs,Ks,Qs,Ys,Js,Xs,Zs,ei,ti,ni,ri=__esm({"src/commands/auth/status.ts"(){Bt(),_n(),bo(),xn(),qs(),Un(),Hs(),Co(),No(),Go(),No(),qs(),__name(detectConfigParseError,"detectConfigParseError"),__name(buildStatusJson,"buildStatusJson"),__name(statusAction,"statusAction"),zs=new Ne("status").description("Show authentication status").option("--json","Output status as JSON for automation").allowUnknownOption().allowExcessArguments().action(statusAction)}}),oi=__esm({"src/api/errors.ts"(){Bt(),Ws=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,null!=o?.status&&(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 Gs({cause:t instanceof Error?t:void 0});const o=t?.error;switch(e){case 400:return new Vs(e,o,n,r);case 401:return new Ks(e,o,n,r);case 403:return new Qs(e,o,n,r);case 404:return new Ys(e,o,n,r);case 409:return new Js(e,o,n,r);case 422:return new Xs(e,o,n,r);case 429:return new Zs(e,o,n,r);default:return e>=500?new ei(e,o,n,r):new _APIError(e,o,n,r)}}},Gs=class extends Ws{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)}},Vs=class extends Ws{static{__name(this,"BadRequestError")}status=400},Ks=class extends Ws{static{__name(this,"AuthenticationError")}status=401},Qs=class extends Ws{static{__name(this,"PermissionDeniedError")}status=403},Ys=class extends Ws{static{__name(this,"NotFoundError")}status=404},Js=class extends Ws{static{__name(this,"ConflictError")}status=409},Xs=class extends Ws{static{__name(this,"UnprocessableEntityError")}status=422},Zs=class extends Ws{static{__name(this,"RateLimitError")}status=429},ei=class extends Ws{static{__name(this,"InternalServerError")}}}}),si=__esm({"../shared/src/types/share.ts"(){Bt(),ti=f.object({messageId:f.string().optional(),timestamp:f.string(),model:f.string().optional(),duration:f.number().optional(),usage:f.object({inputTokens:f.number(),outputTokens:f.number(),totalTokens:f.number(),cacheReadTokens:f.number().optional(),cacheWriteTokens:f.number().optional(),estimatedCost:f.number().optional()}).optional(),source:f.string().optional(),entrypoint:f.string().optional(),context:f.object({sessionId:f.string().optional(),threadId:f.string().optional(),userId:f.string().optional()}).optional(),highlight:f.boolean().optional(),isSummary:f.boolean().optional(),isAutomated:f.boolean().optional(),isMeta:f.boolean().optional(),hookContexts:f.record(f.string(),f.object({preToolUse:f.string().optional(),postToolUse:f.string().optional()})).optional()}),f.object({message:f.any(),meta:ti}),f.object({sessionId:f.string().uuid("sessionId must be a UUID"),messages:f.array(f.any()).optional()}),f.object({secret:f.string(),url:f.string()}),f.object({sessionId:f.string().uuid("sessionId must be a UUID"),secret:f.string()}),f.object({sessionId:f.string(),secret:f.string(),key:f.string(),content:f.any()}),f.object({sessionId:f.string().uuid("sessionId must be a UUID"),secret:f.string(),message:f.any()}),ni=/^[a-f0-9]{8}$/,f.object({shortId:f.string().regex(ni,"Invalid shortId")}),f.object({info:f.any().optional(),messages:f.array(f.any())})}}),ii=__esm({"../shared/src/types/whoami.ts"(){Bt()}});function parseModelString(e){if(e.includes(":")){const t=e.indexOf(":");return{provider:e.slice(0,t),modelId:e.slice(t+1)}}return{provider:"anthropic",modelId:e}}var ai,li=__esm({"../shared/src/types/messages.ts"(){Bt(),__name(parseModelString,"parseModelString")}}),ci=__esm({"../shared/src/types/email.ts"(){Bt(),f.object({to:f.union([f.email(),f.array(f.email())]),subject:f.string(),html:f.string().optional(),text:f.string().optional(),template:f.string().optional(),templateData:f.record(f.any(),f.any()).optional(),cc:f.array(f.email()).optional(),bcc:f.array(f.email()).optional(),replyTo:f.array(f.email()).optional(),tags:f.array(f.object({name:f.string(),value:f.string()})).optional()}),f.object({success:f.boolean(),messageId:f.string().optional(),error:f.string().optional()})}});function is(e,t){if(!e||"object"!=typeof e)return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,ai))throw new Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(ai in n&&n[ai]===t[ai])return!0;n=Object.getPrototypeOf(n)}return!1}var ui,di,mi,pi,gi,hi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/entity.js"(){Bt(),ai=Symbol.for("drizzle:entityKind"),__name(is,"is")}}),fi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/column.js"(){Bt(),hi(),ui=class{static{__name(this,"Column")}constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[ai]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}}}),yi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/column-builder.js"(){Bt(),hi(),di=class{static{__name(this,"ColumnBuilder")}static[ai]="ColumnBuilder";config;constructor(e,t,n){this.config={name:e,keyAsName:""===e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){""===this.config.name&&(this.config.name=e)}}}}),wi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/table.utils.js"(){Bt(),mi=Symbol.for("drizzle:Name")}}),Si=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/foreign-keys.js"(){Bt(),hi(),wi(),pi=class{static{__name(this,"ForeignKeyBuilder")}static[ai]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){this.reference=()=>{const{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new gi(e,this)}},gi=class{static{__name(this,"ForeignKey")}constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[ai]="PgForeignKey";reference;onUpdate;onDelete;getName(){const{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),o=n.map(e=>e.name),s=[this.table[mi],...r,n[0].table[mi],...o];return e??`${s.join("_")}_fk`}}}});function iife(e,...t){return e(...t)}var bi,Ei,vi,Ci=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/tracing-utils.js"(){Bt(),__name(iife,"iife")}});function unique(e){return new Ei(e)}function uniqueKeyName(e,t){return`${e[mi]}_${t.join("_")}_unique`}var ki=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/unique-constraint.js"(){Bt(),hi(),wi(),__name(unique,"unique"),__name(uniqueKeyName,"uniqueKeyName"),bi=class{static{__name(this,"UniqueConstraintBuilder")}constructor(e,t){this.name=t,this.columns=e}static[ai]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new vi(e,this.columns,this.nullsNotDistinctConfig,this.name)}},Ei=class{static{__name(this,"UniqueOnConstraintBuilder")}static[ai]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new bi(e,this.name)}},vi=class{static{__name(this,"UniqueConstraint")}constructor(e,t,n,r){this.table=e,this.columns=t,this.name=r??uniqueKeyName(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static[ai]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}}});function parsePgArrayValue(e,t,n){for(let r=t;r<e.length;r++){const o=e[r];if("\\"!==o){if('"'===o)return[e.slice(t,r).replace(/\\/g,""),r+1];if(!n&&(","===o||"}"===o))return[e.slice(t,r).replace(/\\/g,""),r]}else r++}return[e.slice(t).replace(/\\/g,""),e.length]}function parsePgNestedArray(e,t=0){const n=[];let r=t,o=!1;for(;r<e.length;){const s=e[r];if(","===s){(o||r===t)&&n.push(""),o=!0,r++;continue}if(o=!1,"\\"===s){r+=2;continue}if('"'===s){const[t,o]=parsePgArrayValue(e,r+1,!0);n.push(t),r=o;continue}if("}"===s)return[n,r+1];if("{"===s){const[t,o]=parsePgNestedArray(e,r+1);n.push(t),r=o;continue}const[i,a]=parsePgArrayValue(e,r,!1);n.push(i),r=a}return[n,r]}function parsePgArray(e){const[t]=parsePgNestedArray(e,1);return t}function makePgArray(e){return`{${e.map(e=>Array.isArray(e)?makePgArray(e):"string"==typeof e?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}var Ti,_i,xi,Ai,Pi,Ii,Mi,Ri,Ni,Li,$i,Di=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/utils/array.js"(){Bt(),__name(parsePgArrayValue,"parsePgArrayValue"),__name(parsePgNestedArray,"parsePgNestedArray"),__name(parsePgArray,"parsePgArray"),__name(makePgArray,"makePgArray")}}),Oi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/common.js"(){Bt(),yi(),fi(),hi(),Si(),Ci(),ki(),Di(),Ti=class extends di{static{__name(this,"PgColumnBuilder")}foreignKeyConfigs=[];static[ai]="PgColumnBuilder";array(e){return new Pi(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>iife((n,r)=>{const o=new pi(()=>{const t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&o.onUpdate(r.onUpdate),r.onDelete&&o.onDelete(r.onDelete),o.build(t)},n,r))}buildExtraConfigColumn(e){return new xi(e,this.config)}},_i=class extends ui{static{__name(this,"PgColumn")}constructor(e,t){t.uniqueName||(t.uniqueName=uniqueKeyName(e,[t.name])),super(e,t),this.table=e}static[ai]="PgColumn"},xi=class extends _i{static{__name(this,"ExtraConfigColumn")}static[ai]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}},Ai=class{static{__name(this,"IndexedColumn")}static[ai]="IndexedColumn";constructor(e,t,n,r){this.name=e,this.keyAsName=t,this.type=n,this.indexConfig=r}name;keyAsName;type;indexConfig},Pi=class extends Ti{static{__name(this,"PgArrayBuilder")}static[ai]="PgArrayBuilder";constructor(e,t,n){super(e,"array","PgArray"),this.config.baseBuilder=t,this.config.size=n}build(e){const t=this.config.baseBuilder.build(e);return new Ii(e,this.config,t)}},Ii=class _PgArray extends _i{static{__name(this,"PgArray")}constructor(e,t,n,r){super(e,t),this.baseColumn=n,this.range=r,this.size=t.size}size;static[ai]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=parsePgArray(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,t=!1){const n=e.map(e=>null===e?null:is(this.baseColumn,_PgArray)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return t?n:makePgArray(n)}}}});function isPgEnum(e){return!!e&&"function"==typeof e&&Ni in e&&!0===e[Ni]}function pgEnum(e,t){return Array.isArray(t)?pgEnumWithSchema(e,[...t],void 0):pgEnumObjectWithSchema(e,t,void 0)}function pgEnumWithSchema(e,t,n){const r=Object.assign(e=>new Li(e??"",r),{enumName:e,enumValues:t,schema:n,[Ni]:!0});return r}function pgEnumObjectWithSchema(e,t,n){const r=Object.assign(e=>new Mi(e??"",r),{enumName:e,enumValues:Object.values(t),schema:n,[Ni]:!0});return r}var Fi,ji,Ui,Bi,qi,zi,Hi,Wi,Gi,Vi,Ki,Qi,Yi,Ji=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/enum.js"(){Bt(),hi(),Oi(),Mi=class extends Ti{static{__name(this,"PgEnumObjectColumnBuilder")}static[ai]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn"),this.config.enum=t}build(e){return new Ri(e,this.config)}},Ri=class extends _i{static{__name(this,"PgEnumObjectColumn")}static[ai]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},Ni=Symbol.for("drizzle:isPgEnum"),__name(isPgEnum,"isPgEnum"),Li=class extends Ti{static{__name(this,"PgEnumColumnBuilder")}static[ai]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn"),this.config.enum=t}build(e){return new $i(e,this.config)}},$i=class extends _i{static{__name(this,"PgEnumColumn")}static[ai]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},__name(pgEnum,"pgEnum"),__name(pgEnumWithSchema,"pgEnumWithSchema"),__name(pgEnumObjectWithSchema,"pgEnumObjectWithSchema")}}),Xi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/subquery.js"(){Bt(),hi(),Fi=class{static{__name(this,"Subquery")}static[ai]="Subquery";constructor(e,t,n,r=!1,o=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:n,isWith:r,usedTables:o}}},ji=class extends Fi{static{__name(this,"WithSubquery")}static[ai]="WithSubquery"}}}),Zi=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/version.js"(){Bt()}}),ea=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/tracing.js"(){Bt(),Ci(),Zi(),Ui={startActiveSpan:(e,t)=>t()}}}),ta=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/view-common.js"(){Bt(),Bi=Symbol.for("drizzle:ViewBaseConfig")}});function getTableName(e){return e[mi]}function getTableUniqueName(e){return`${e[qi]??"public"}.${e[mi]}`}var na,ra,oa,sa,ia,aa,la,ca,ua,da=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/table.js"(){Bt(),hi(),wi(),qi=Symbol.for("drizzle:Schema"),zi=Symbol.for("drizzle:Columns"),Hi=Symbol.for("drizzle:ExtraConfigColumns"),Wi=Symbol.for("drizzle:OriginalName"),Gi=Symbol.for("drizzle:BaseName"),Vi=Symbol.for("drizzle:IsAlias"),Ki=Symbol.for("drizzle:ExtraConfigBuilder"),Qi=Symbol.for("drizzle:IsDrizzleTable"),Yi=class{static{__name(this,"Table")}static[ai]="Table";static Symbol={Name:mi,Schema:qi,OriginalName:Wi,Columns:zi,ExtraConfigColumns:Hi,BaseName:Gi,IsAlias:Vi,ExtraConfigBuilder:Ki};[mi];[Wi];[qi];[zi];[Hi];[Gi];[Vi]=!1;[Qi]=!0;[Ki]=void 0;constructor(e,t,n){this[mi]=this[Wi]=e,this[qi]=t,this[Gi]=n}},__name(getTableName,"getTableName"),__name(getTableUniqueName,"getTableUniqueName")}});function isSQLWrapper(e){return null!=e&&"function"==typeof e.getSQL}function mergeQueries(e){const t={sql:"",params:[]};for(const n of e)t.sql+=n.sql,t.params.push(...n.params),n.typings?.length&&(t.typings||(t.typings=[]),t.typings.push(...n.typings));return t}function isDriverValueEncoder(e){return"object"==typeof e&&null!==e&&"mapToDriverValue"in e&&"function"==typeof e.mapToDriverValue}function sql(e,...t){const n=[];(t.length>0||e.length>0&&""!==e[0])&&n.push(new na(e[0]));for(const[r,o]of t.entries())n.push(o,new na(e[r+1]));return new ra(n)}var ma,pa,ga=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/sql.js"(){Bt(),hi(),Ji(),Xi(),ea(),ta(),fi(),da(),class{static{__name(this,"FakePrimitiveParam")}static[ai]="FakePrimitiveParam"},__name(isSQLWrapper,"isSQLWrapper"),__name(mergeQueries,"mergeQueries"),na=class{static{__name(this,"StringChunk")}static[ai]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new ra([this])}},ra=class _SQL{static{__name(this,"SQL")}constructor(e){this.queryChunks=e;for(const t of e)if(is(t,Yi)){const e=t[Yi.Symbol.Schema];this.usedTables.push(void 0===e?t[Yi.Symbol.Name]:e+"."+t[Yi.Symbol.Name])}}static[ai]="SQL";decoder=sa;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return Ui.startActiveSpan("drizzle.buildSQL",t=>{const n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){const n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:r,escapeName:o,escapeParam:s,prepareTyping:i,inlineParams:a,paramStartIndex:l}=n;return mergeQueries(e.map(e=>{if(is(e,na))return{sql:e.value.join(""),params:[]};if(is(e,oa))return{sql:o(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){const t=[new na("(")];for(const[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(new na(", "));return t.push(new na(")")),this.buildQueryFromSourceParams(t,n)}if(is(e,_SQL))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:a||e.shouldInlineParams});if(is(e,Yi)){const t=e[Yi.Symbol.Schema],n=e[Yi.Symbol.Name];return{sql:void 0===t||e[Vi]?o(n):o(t)+"."+o(n),params:[]}}if(is(e,ui)){const n=r.getColumnCasing(e);if("indexes"===t.invokeSource)return{sql:o(n),params:[]};const s=e.table[Yi.Symbol.Schema];return{sql:e.table[Vi]||void 0===s?o(e.table[Yi.Symbol.Name])+"."+o(n):o(s)+"."+o(e.table[Yi.Symbol.Name])+"."+o(n),params:[]}}if(is(e,ua)){const t=e[Bi].schema,n=e[Bi].name;return{sql:void 0===t||e[Bi].isAlias?o(n):o(t)+"."+o(n),params:[]}}if(is(e,aa)){if(is(e.value,la))return{sql:s(l.value++,e),params:[e],typings:["none"]};const t=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(is(t,_SQL))return this.buildQueryFromSourceParams([t],n);if(a)return{sql:this.mapInlineParam(t,n),params:[]};let r=["none"];return i&&(r=[i(e.encoder)]),{sql:s(l.value++,t),params:[t],typings:r}}return is(e,la)?{sql:s(l.value++,e),params:[e],typings:["none"]}:is(e,_SQL.Aliased)&&void 0!==e.fieldAlias?{sql:o(e.fieldAlias),params:[]}:is(e,Fi)?e._.isWith?{sql:o(e._.alias),params:[]}:this.buildQueryFromSourceParams([new na("("),e._.sql,new na(") "),new oa(e._.alias)],n):isPgEnum(e)?e.schema?{sql:o(e.schema)+"."+o(e.enumName),params:[]}:{sql:o(e.enumName),params:[]}:isSQLWrapper(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new na("("),e.getSQL(),new na(")")],n):a?{sql:this.mapInlineParam(e,n),params:[]}:{sql:s(l.value++,e),params:[e],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return t(e);if("object"==typeof e){const n=e.toString();return t("[object Object]"===n?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new _SQL.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},oa=class{static{__name(this,"Name")}constructor(e){this.value=e}static[ai]="Name";brand;getSQL(){return new ra([this])}},__name(isDriverValueEncoder,"isDriverValueEncoder"),sa={mapFromDriverValue:__name(e=>e,"mapFromDriverValue")},ia={mapToDriverValue:__name(e=>e,"mapToDriverValue")},aa=class{static{__name(this,"Param")}constructor(e,t=ia){this.value=e,this.encoder=t}static[ai]="Param";brand;getSQL(){return new ra([this])}},__name(sql,"sql"),(e=>{function empty(){return new ra([])}function fromList(e){return new ra(e)}function raw(e){return new ra([new na(e)])}function join30(e,t){const n=[];for(const[r,o]of e.entries())r>0&&void 0!==t&&n.push(t),n.push(o);return new ra(n)}function identifier(e){return new oa(e)}function placeholder2(e){return new la(e)}function param2(e,t){return new aa(e,t)}__name(empty,"empty"),e.empty=empty,__name(fromList,"fromList"),e.fromList=fromList,__name(raw,"raw"),e.raw=raw,__name(join30,"join"),e.join=join30,__name(identifier,"identifier"),e.identifier=identifier,__name(placeholder2,"placeholder2"),e.placeholder=placeholder2,__name(param2,"param2"),e.param=param2})(sql||(sql={})),(e=>{class Aliased{static{__name(this,"Aliased")}constructor(e,t){this.sql=e,this.fieldAlias=t}static[ai]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Aliased(this.sql,this.fieldAlias)}}e.Aliased=Aliased})(ra||(ra={})),la=class{static{__name(this,"Placeholder")}constructor(e){this.name=e}static[ai]="Placeholder";getSQL(){return new ra([this])}},ca=Symbol.for("drizzle:IsDrizzleView"),ua=class{static{__name(this,"View")}static[ai]="View";[Bi];[ca]=!0;constructor({name:e,schema:t,selectedFields:n,query:r}){this[Bi]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new ra([this])}},ui.prototype.getSQL=function(){return new ra([this])},Yi.prototype.getSQL=function(){return new ra([this])},Fi.prototype.getSQL=function(){return new ra([this])}}});function aliasedTable(e,t){return new Proxy(e,new pa(t,!1))}function aliasedTableColumn(e,t){return new Proxy(e,new ma(new Proxy(e.table,new pa(t,!1))))}function mapColumnsInAliasedSQLToAlias(e,t){return new ra.Aliased(mapColumnsInSQLToAlias(e.sql,t),e.fieldAlias)}function mapColumnsInSQLToAlias(e,t){return sql.join(e.queryChunks.map(e=>is(e,ui)?aliasedTableColumn(e,t):is(e,ra)?mapColumnsInSQLToAlias(e,t):is(e,ra.Aliased)?mapColumnsInAliasedSQLToAlias(e,t):e))}var ha,fa,ya=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/alias.js"(){Bt(),fi(),hi(),ga(),da(),ta(),ma=class{static{__name(this,"ColumnAliasProxyHandler")}constructor(e){this.table=e}static[ai]="ColumnAliasProxyHandler";get(e,t){return"table"===t?this.table:e[t]}},pa=class{static{__name(this,"TableAliasProxyHandler")}constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[ai]="TableAliasProxyHandler";get(e,t){if(t===Yi.Symbol.IsAlias)return!0;if(t===Yi.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Yi.Symbol.OriginalName)return this.alias;if(t===Bi)return{...e[Bi],name:this.alias,isAlias:!0};if(t===Yi.Symbol.Columns){const t=e[Yi.Symbol.Columns];if(!t)return t;const n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new ma(new Proxy(e,this)))}),n}const n=e[t];return is(n,ui)?new Proxy(n,new ma(new Proxy(e,this))):n}},class{static{__name(this,"RelationTableAliasProxyHandler")}constructor(e){this.alias=e}static[ai]="RelationTableAliasProxyHandler";get(e,t){return"sourceTable"===t?aliasedTable(e.sourceTable,this.alias):e[t]}},__name(aliasedTable,"aliasedTable"),__name(aliasedTableColumn,"aliasedTableColumn"),__name(mapColumnsInAliasedSQLToAlias,"mapColumnsInAliasedSQLToAlias"),__name(mapColumnsInSQLToAlias,"mapColumnsInSQLToAlias")}}),wa=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/alias.js"(){Bt()}});function check(e,t){return new ha(e,t)}var Sa,ba=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/checks.js"(){Bt(),hi(),ha=class{static{__name(this,"CheckBuilder")}constructor(e,t){this.name=e,this.value=t}static[ai]="PgCheckBuilder";brand;build(e){return new fa(e,this)}},fa=class{static{__name(this,"Check")}constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[ai]="PgCheck";name;value},__name(check,"check")}});function orderSelectedFields(e,t){return Object.entries(e).reduce((e,[n,r])=>{if("string"!=typeof n)return e;const o=t?[...t,n]:[n];return is(r,ui)||is(r,ra)||is(r,ra.Aliased)||is(r,Fi)?e.push({path:o,field:r}):is(r,Yi)?e.push(...orderSelectedFields(r[Yi.Symbol.Columns],o)):e.push(...orderSelectedFields(r,o)),e},[])}function haveSameKeys(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const[e,t]of n.entries())if(t!==r[e])return!1;return!0}function mapUpdateSet(e,t){const n=Object.entries(t).filter(([,e])=>void 0!==e).map(([t,n])=>is(n,ra)||is(n,ui)?[t,n]:[t,new aa(n,e[Yi.Symbol.Columns][t])]);if(0===n.length)throw new Error("No values to set");return Object.fromEntries(n)}function applyMixins(e,t){for(const n of t)for(const t of Object.getOwnPropertyNames(n.prototype))"constructor"!==t&&Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)||Object.create(null))}function getTableColumns(e){return e[Yi.Symbol.Columns]}function getTableLikeName(e){return is(e,Fi)?e._.alias:is(e,ua)?e[Bi].name:is(e,ra)?void 0:e[Yi.Symbol.IsAlias]?e[Yi.Symbol.Name]:e[Yi.Symbol.BaseName]}function getColumnNameAndConfig(e,t){return{name:"string"==typeof e&&e.length>0?e:"",config:"object"==typeof e?e:t}}var Ea,va,Ca,ka,Ta,_a=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/utils.js"(){Bt(),fi(),hi(),ga(),Xi(),da(),ta(),__name(orderSelectedFields,"orderSelectedFields"),__name(haveSameKeys,"haveSameKeys"),__name(mapUpdateSet,"mapUpdateSet"),__name(applyMixins,"applyMixins"),__name(getTableColumns,"getTableColumns"),__name(getTableLikeName,"getTableLikeName"),__name(getColumnNameAndConfig,"getColumnNameAndConfig"),Sa="undefined"==typeof TextDecoder?null:new TextDecoder}}),xa=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/int.common.js"(){Bt(),hi(),Oi(),Ea=class extends Ti{static{__name(this,"PgIntColumnBaseBuilder")}static[ai]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(e){if(e){const{name:t,...n}=e;this.config.generatedIdentity={type:"always",sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){const{name:t,...n}=e;this.config.generatedIdentity={type:"byDefault",sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}}});function bigint(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"number"===r.mode?new va(n):new ka(n)}var Aa,Pa,Ia,Ma,Ra=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/bigint.js"(){Bt(),hi(),_a(),Oi(),xa(),va=class extends Ea{static{__name(this,"PgBigInt53Builder")}static[ai]="PgBigInt53Builder";constructor(e){super(e,"number","PgBigInt53")}build(e){return new Ca(e,this.config)}},Ca=class extends _i{static{__name(this,"PgBigInt53")}static[ai]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}},ka=class extends Ea{static{__name(this,"PgBigInt64Builder")}static[ai]="PgBigInt64Builder";constructor(e){super(e,"bigint","PgBigInt64")}build(e){return new Ta(e,this.config)}},Ta=class extends _i{static{__name(this,"PgBigInt64")}static[ai]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(e){return BigInt(e)}},__name(bigint,"bigint")}});function bigserial(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"number"===r.mode?new Aa(n):new Ia(n)}var Na,La,$a=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/bigserial.js"(){Bt(),hi(),_a(),Oi(),Aa=class extends Ti{static{__name(this,"PgBigSerial53Builder")}static[ai]="PgBigSerial53Builder";constructor(e){super(e,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Pa(e,this.config)}},Pa=class extends _i{static{__name(this,"PgBigSerial53")}static[ai]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}},Ia=class extends Ti{static{__name(this,"PgBigSerial64Builder")}static[ai]="PgBigSerial64Builder";constructor(e){super(e,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(e){return new Ma(e,this.config)}},Ma=class extends _i{static{__name(this,"PgBigSerial64")}static[ai]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(e){return BigInt(e)}},__name(bigserial,"bigserial")}});function boolean(e){return new Na(e??"")}var Da,Oa,Fa=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/boolean.js"(){Bt(),hi(),Oi(),Na=class extends Ti{static{__name(this,"PgBooleanBuilder")}static[ai]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new La(e,this.config)}},La=class extends _i{static{__name(this,"PgBoolean")}static[ai]="PgBoolean";getSQLType(){return"boolean"}},__name(boolean,"boolean")}});function char(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new Da(n,r)}var ja,Ua,Ba=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/char.js"(){Bt(),hi(),_a(),Oi(),Da=class extends Ti{static{__name(this,"PgCharBuilder")}static[ai]="PgCharBuilder";constructor(e,t){super(e,"string","PgChar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new Oa(e,this.config)}},Oa=class extends _i{static{__name(this,"PgChar")}static[ai]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"char":`char(${this.length})`}},__name(char,"char")}});function cidr(e){return new ja(e??"")}var qa,za,Ha=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/cidr.js"(){Bt(),hi(),Oi(),ja=class extends Ti{static{__name(this,"PgCidrBuilder")}static[ai]="PgCidrBuilder";constructor(e){super(e,"string","PgCidr")}build(e){return new Ua(e,this.config)}},Ua=class extends _i{static{__name(this,"PgCidr")}static[ai]="PgCidr";getSQLType(){return"cidr"}},__name(cidr,"cidr")}});function customType(e){return(t,n)=>{const{name:r,config:o}=getColumnNameAndConfig(t,n);return new qa(r,o,e)}}var Wa,Ga,Va,Ka,Qa,Ya=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/custom.js"(){Bt(),hi(),_a(),Oi(),qa=class extends Ti{static{__name(this,"PgCustomColumnBuilder")}static[ai]="PgCustomColumnBuilder";constructor(e,t,n){super(e,"custom","PgCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new za(e,this.config)}},za=class extends _i{static{__name(this,"PgCustomColumn")}static[ai]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return"function"==typeof this.mapFrom?this.mapFrom(e):e}mapToDriverValue(e){return"function"==typeof this.mapTo?this.mapTo(e):e}},__name(customType,"customType")}}),Ja=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/date.common.js"(){Bt(),hi(),ga(),Oi(),Wa=class extends Ti{static{__name(this,"PgDateColumnBaseBuilder")}static[ai]="PgDateColumnBaseBuilder";defaultNow(){return this.default(sql`now()`)}}}});function date(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"date"===r?.mode?new Ga(n):new Ka(n)}var Xa,Za,el=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/date.js"(){Bt(),hi(),_a(),Oi(),Ja(),Ga=class extends Wa{static{__name(this,"PgDateBuilder")}static[ai]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new Va(e,this.config)}},Va=class extends _i{static{__name(this,"PgDate")}static[ai]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?new Date(e):e}mapToDriverValue(e){return e.toISOString()}},Ka=class extends Wa{static{__name(this,"PgDateStringBuilder")}static[ai]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new Qa(e,this.config)}},Qa=class extends _i{static{__name(this,"PgDateString")}static[ai]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?e:e.toISOString().slice(0,-14)}},__name(date,"date")}});function doublePrecision(e){return new Xa(e??"")}var tl,nl,rl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/double-precision.js"(){Bt(),hi(),Oi(),Xa=class extends Ti{static{__name(this,"PgDoublePrecisionBuilder")}static[ai]="PgDoublePrecisionBuilder";constructor(e){super(e,"number","PgDoublePrecision")}build(e){return new Za(e,this.config)}},Za=class extends _i{static{__name(this,"PgDoublePrecision")}static[ai]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(e){return"string"==typeof e?Number.parseFloat(e):e}},__name(doublePrecision,"doublePrecision")}});function inet(e){return new tl(e??"")}var ol,sl,il=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/inet.js"(){Bt(),hi(),Oi(),tl=class extends Ti{static{__name(this,"PgInetBuilder")}static[ai]="PgInetBuilder";constructor(e){super(e,"string","PgInet")}build(e){return new nl(e,this.config)}},nl=class extends _i{static{__name(this,"PgInet")}static[ai]="PgInet";getSQLType(){return"inet"}},__name(inet,"inet")}});function integer(e){return new ol(e??"")}var al,ll,cl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/integer.js"(){Bt(),hi(),Oi(),xa(),ol=class extends Ea{static{__name(this,"PgIntegerBuilder")}static[ai]="PgIntegerBuilder";constructor(e){super(e,"number","PgInteger")}build(e){return new sl(e,this.config)}},sl=class extends _i{static{__name(this,"PgInteger")}static[ai]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(e){return"string"==typeof e?Number.parseInt(e):e}},__name(integer,"integer")}});function interval(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new al(n,r)}var ul,dl,ml=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/interval.js"(){Bt(),hi(),_a(),Oi(),al=class extends Ti{static{__name(this,"PgIntervalBuilder")}static[ai]="PgIntervalBuilder";constructor(e,t){super(e,"string","PgInterval"),this.config.intervalConfig=t}build(e){return new ll(e,this.config)}},ll=class extends _i{static{__name(this,"PgInterval")}static[ai]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){return`interval${this.fields?` ${this.fields}`:""}${this.precision?`(${this.precision})`:""}`}},__name(interval,"interval")}});function json(e){return new ul(e??"")}var pl,gl,hl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/json.js"(){Bt(),hi(),Oi(),ul=class extends Ti{static{__name(this,"PgJsonBuilder")}static[ai]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new dl(e,this.config)}},dl=class extends _i{static{__name(this,"PgJson")}static[ai]="PgJson";constructor(e,t){super(e,t)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}},__name(json,"json")}});function jsonb(e){return new pl(e??"")}var fl,yl,wl,Sl,bl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/jsonb.js"(){Bt(),hi(),Oi(),pl=class extends Ti{static{__name(this,"PgJsonbBuilder")}static[ai]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new gl(e,this.config)}},gl=class extends _i{static{__name(this,"PgJsonb")}static[ai]="PgJsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}},__name(jsonb,"jsonb")}});function line(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return r?.mode&&"tuple"!==r.mode?new wl(n):new fl(n)}var El,vl,Cl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/line.js"(){Bt(),hi(),_a(),Oi(),fl=class extends Ti{static{__name(this,"PgLineBuilder")}static[ai]="PgLineBuilder";constructor(e){super(e,"array","PgLine")}build(e){return new yl(e,this.config)}},yl=class extends _i{static{__name(this,"PgLineTuple")}static[ai]="PgLine";getSQLType(){return"line"}mapFromDriverValue(e){const[t,n,r]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(n),Number.parseFloat(r)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},wl=class extends Ti{static{__name(this,"PgLineABCBuilder")}static[ai]="PgLineABCBuilder";constructor(e){super(e,"json","PgLineABC")}build(e){return new Sl(e,this.config)}},Sl=class extends _i{static{__name(this,"PgLineABC")}static[ai]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(e){const[t,n,r]=e.slice(1,-1).split(",");return{a:Number.parseFloat(t),b:Number.parseFloat(n),c:Number.parseFloat(r)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}},__name(line,"line")}});function macaddr(e){return new El(e??"")}var kl,Tl,_l=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/macaddr.js"(){Bt(),hi(),Oi(),El=class extends Ti{static{__name(this,"PgMacaddrBuilder")}static[ai]="PgMacaddrBuilder";constructor(e){super(e,"string","PgMacaddr")}build(e){return new vl(e,this.config)}},vl=class extends _i{static{__name(this,"PgMacaddr")}static[ai]="PgMacaddr";getSQLType(){return"macaddr"}},__name(macaddr,"macaddr")}});function macaddr8(e){return new kl(e??"")}var xl,Al,Pl,Il,Ml,Rl,Nl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/macaddr8.js"(){Bt(),hi(),Oi(),kl=class extends Ti{static{__name(this,"PgMacaddr8Builder")}static[ai]="PgMacaddr8Builder";constructor(e){super(e,"string","PgMacaddr8")}build(e){return new Tl(e,this.config)}},Tl=class extends _i{static{__name(this,"PgMacaddr8")}static[ai]="PgMacaddr8";getSQLType(){return"macaddr8"}},__name(macaddr8,"macaddr8")}});function numeric(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t),o=r?.mode;return"number"===o?new Pl(n,r?.precision,r?.scale):"bigint"===o?new Ml(n,r?.precision,r?.scale):new xl(n,r?.precision,r?.scale)}var Ll,$l,Dl,Ol,Fl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/numeric.js"(){Bt(),hi(),_a(),Oi(),xl=class extends Ti{static{__name(this,"PgNumericBuilder")}static[ai]="PgNumericBuilder";constructor(e,t,n){super(e,"string","PgNumeric"),this.config.precision=t,this.config.scale=n}build(e){return new Al(e,this.config)}},Al=class extends _i{static{__name(this,"PgNumeric")}static[ai]="PgNumeric";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return"string"==typeof e?e:String(e)}getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}},Pl=class extends Ti{static{__name(this,"PgNumericNumberBuilder")}static[ai]="PgNumericNumberBuilder";constructor(e,t,n){super(e,"number","PgNumericNumber"),this.config.precision=t,this.config.scale=n}build(e){return new Il(e,this.config)}},Il=class extends _i{static{__name(this,"PgNumericNumber")}static[ai]="PgNumericNumber";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}},Ml=class extends Ti{static{__name(this,"PgNumericBigIntBuilder")}static[ai]="PgNumericBigIntBuilder";constructor(e,t,n){super(e,"bigint","PgNumericBigInt"),this.config.precision=t,this.config.scale=n}build(e){return new Rl(e,this.config)}},Rl=class extends _i{static{__name(this,"PgNumericBigInt")}static[ai]="PgNumericBigInt";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}},__name(numeric,"numeric")}});function point(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return r?.mode&&"tuple"!==r.mode?new Dl(n):new Ll(n)}var jl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/point.js"(){Bt(),hi(),_a(),Oi(),Ll=class extends Ti{static{__name(this,"PgPointTupleBuilder")}static[ai]="PgPointTupleBuilder";constructor(e){super(e,"array","PgPointTuple")}build(e){return new $l(e,this.config)}},$l=class extends _i{static{__name(this,"PgPointTuple")}static[ai]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(e){if("string"==typeof e){const[t,n]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(n)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},Dl=class extends Ti{static{__name(this,"PgPointObjectBuilder")}static[ai]="PgPointObjectBuilder";constructor(e){super(e,"json","PgPointObject")}build(e){return new Ol(e,this.config)}},Ol=class extends _i{static{__name(this,"PgPointObject")}static[ai]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(e){if("string"==typeof e){const[t,n]=e.slice(1,-1).split(",");return{x:Number.parseFloat(t),y:Number.parseFloat(n)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}},__name(point,"point")}});function hexToBytes(e){const t=[];for(let n=0;n<e.length;n+=2)t.push(Number.parseInt(e.slice(n,n+2),16));return new Uint8Array(t)}function bytesToFloat64(e,t){const n=new ArrayBuffer(8),r=new DataView(n);for(let n=0;n<8;n++)r.setUint8(n,e[t+n]);return r.getFloat64(0,!0)}function parseEWKB(e){const t=hexToBytes(e);let n=0;const r=t[n];n+=1;const o=new DataView(t.buffer),s=o.getUint32(n,1===r);if(n+=4,536870912&s&&(o.getUint32(n,1===r),n+=4),1==(65535&s)){const e=bytesToFloat64(t,n);n+=8;const r=bytesToFloat64(t,n);return n+=8,[e,r]}throw new Error("Unsupported geometry type")}var Ul,Bl,ql,zl,Hl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js"(){Bt(),__name(hexToBytes,"hexToBytes"),__name(bytesToFloat64,"bytesToFloat64"),__name(parseEWKB,"parseEWKB")}});function geometry(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return r?.mode&&"tuple"!==r.mode?new ql(n):new Ul(n)}var Wl,Gl,Vl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js"(){Bt(),hi(),_a(),Oi(),Hl(),Ul=class extends Ti{static{__name(this,"PgGeometryBuilder")}static[ai]="PgGeometryBuilder";constructor(e){super(e,"array","PgGeometry")}build(e){return new Bl(e,this.config)}},Bl=class extends _i{static{__name(this,"PgGeometry")}static[ai]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){return parseEWKB(e)}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},ql=class extends Ti{static{__name(this,"PgGeometryObjectBuilder")}static[ai]="PgGeometryObjectBuilder";constructor(e){super(e,"json","PgGeometryObject")}build(e){return new zl(e,this.config)}},zl=class extends _i{static{__name(this,"PgGeometryObject")}static[ai]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){const t=parseEWKB(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}},__name(geometry,"geometry")}});function real(e){return new Wl(e??"")}var Kl,Ql,Yl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/real.js"(){Bt(),hi(),Oi(),Wl=class extends Ti{static{__name(this,"PgRealBuilder")}static[ai]="PgRealBuilder";constructor(e,t){super(e,"number","PgReal"),this.config.length=t}build(e){return new Gl(e,this.config)}},Gl=class extends _i{static{__name(this,"PgReal")}static[ai]="PgReal";constructor(e,t){super(e,t)}getSQLType(){return"real"}mapFromDriverValue=__name(e=>"string"==typeof e?Number.parseFloat(e):e,"mapFromDriverValue")},__name(real,"real")}});function serial(e){return new Kl(e??"")}var Jl,Xl,Zl=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/serial.js"(){Bt(),hi(),Oi(),Kl=class extends Ti{static{__name(this,"PgSerialBuilder")}static[ai]="PgSerialBuilder";constructor(e){super(e,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Ql(e,this.config)}},Ql=class extends _i{static{__name(this,"PgSerial")}static[ai]="PgSerial";getSQLType(){return"serial"}},__name(serial,"serial")}});function smallint(e){return new Jl(e??"")}var ec,tc,nc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/smallint.js"(){Bt(),hi(),Oi(),xa(),Jl=class extends Ea{static{__name(this,"PgSmallIntBuilder")}static[ai]="PgSmallIntBuilder";constructor(e){super(e,"number","PgSmallInt")}build(e){return new Xl(e,this.config)}},Xl=class extends _i{static{__name(this,"PgSmallInt")}static[ai]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=__name(e=>"string"==typeof e?Number(e):e,"mapFromDriverValue")},__name(smallint,"smallint")}});function smallserial(e){return new ec(e??"")}var rc,oc,sc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/smallserial.js"(){Bt(),hi(),Oi(),ec=class extends Ti{static{__name(this,"PgSmallSerialBuilder")}static[ai]="PgSmallSerialBuilder";constructor(e){super(e,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new tc(e,this.config)}},tc=class extends _i{static{__name(this,"PgSmallSerial")}static[ai]="PgSmallSerial";getSQLType(){return"smallserial"}},__name(smallserial,"smallserial")}});function text(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new rc(n,r)}var ic,ac,lc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/text.js"(){Bt(),hi(),_a(),Oi(),rc=class extends Ti{static{__name(this,"PgTextBuilder")}static[ai]="PgTextBuilder";constructor(e,t){super(e,"string","PgText"),this.config.enumValues=t.enum}build(e){return new oc(e,this.config)}},oc=class extends _i{static{__name(this,"PgText")}static[ai]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}},__name(text,"text")}});function time(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new ic(n,r.withTimezone??!1,r.precision)}var cc,uc,dc,mc,pc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/time.js"(){Bt(),hi(),_a(),Oi(),Ja(),ic=class extends Wa{static{__name(this,"PgTimeBuilder")}constructor(e,t,n){super(e,"string","PgTime"),this.withTimezone=t,this.precision=n,this.config.withTimezone=t,this.config.precision=n}static[ai]="PgTimeBuilder";build(e){return new ac(e,this.config)}},ac=class extends _i{static{__name(this,"PgTime")}static[ai]="PgTime";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${void 0===this.precision?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}},__name(time,"time")}});function timestamp(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return"string"===r?.mode?new dc(n,r.withTimezone??!1,r.precision):new cc(n,r?.withTimezone??!1,r?.precision)}var gc,hc,fc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/timestamp.js"(){Bt(),hi(),_a(),Oi(),Ja(),cc=class extends Wa{static{__name(this,"PgTimestampBuilder")}static[ai]="PgTimestampBuilder";constructor(e,t,n){super(e,"date","PgTimestamp"),this.config.withTimezone=t,this.config.precision=n}build(e){return new uc(e,this.config)}},uc=class extends _i{static{__name(this,"PgTimestamp")}static[ai]="PgTimestamp";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${void 0===this.precision?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){return"string"==typeof e?new Date(this.withTimezone?e:e+"+0000"):e}mapToDriverValue=__name(e=>e.toISOString(),"mapToDriverValue")},dc=class extends Wa{static{__name(this,"PgTimestampStringBuilder")}static[ai]="PgTimestampStringBuilder";constructor(e,t,n){super(e,"string","PgTimestampString"),this.config.withTimezone=t,this.config.precision=n}build(e){return new mc(e,this.config)}},mc=class extends _i{static{__name(this,"PgTimestampString")}static[ai]="PgTimestampString";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${void 0===this.precision?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){if("string"==typeof e)return e;const t=e.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){const n=e.getTimezoneOffset();return`${t}${n<=0?"+":"-"}${Math.floor(Math.abs(n)/60).toString().padStart(2,"0")}`}return t}},__name(timestamp,"timestamp")}});function uuid(e){return new gc(e??"")}var yc,wc,Sc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/uuid.js"(){Bt(),hi(),ga(),Oi(),gc=class extends Ti{static{__name(this,"PgUUIDBuilder")}static[ai]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(sql`gen_random_uuid()`)}build(e){return new hc(e,this.config)}},hc=class extends _i{static{__name(this,"PgUUID")}static[ai]="PgUUID";getSQLType(){return"uuid"}},__name(uuid,"uuid")}});function varchar(e,t={}){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new yc(n,r)}var bc,Ec,vc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/varchar.js"(){Bt(),hi(),_a(),Oi(),yc=class extends Ti{static{__name(this,"PgVarcharBuilder")}static[ai]="PgVarcharBuilder";constructor(e,t){super(e,"string","PgVarchar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new wc(e,this.config)}},wc=class extends _i{static{__name(this,"PgVarchar")}static[ai]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"varchar":`varchar(${this.length})`}},__name(varchar,"varchar")}});function bit(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new bc(n,r)}var Cc,kc,Tc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js"(){Bt(),hi(),_a(),Oi(),bc=class extends Ti{static{__name(this,"PgBinaryVectorBuilder")}static[ai]="PgBinaryVectorBuilder";constructor(e,t){super(e,"string","PgBinaryVector"),this.config.dimensions=t.dimensions}build(e){return new Ec(e,this.config)}},Ec=class extends _i{static{__name(this,"PgBinaryVector")}static[ai]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}},__name(bit,"bit")}});function halfvec(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new Cc(n,r)}var _c,xc,Ac=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js"(){Bt(),hi(),_a(),Oi(),Cc=class extends Ti{static{__name(this,"PgHalfVectorBuilder")}static[ai]="PgHalfVectorBuilder";constructor(e,t){super(e,"array","PgHalfVector"),this.config.dimensions=t.dimensions}build(e){return new kc(e,this.config)}},kc=class extends _i{static{__name(this,"PgHalfVector")}static[ai]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(e=>Number.parseFloat(e))}},__name(halfvec,"halfvec")}});function sparsevec(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new _c(n,r)}var Pc,Ic,Mc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js"(){Bt(),hi(),_a(),Oi(),_c=class extends Ti{static{__name(this,"PgSparseVectorBuilder")}static[ai]="PgSparseVectorBuilder";constructor(e,t){super(e,"string","PgSparseVector"),this.config.dimensions=t.dimensions}build(e){return new xc(e,this.config)}},xc=class extends _i{static{__name(this,"PgSparseVector")}static[ai]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}},__name(sparsevec,"sparsevec")}});function vector(e,t){const{name:n,config:r}=getColumnNameAndConfig(e,t);return new Pc(n,r)}var Rc,Nc,Lc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js"(){Bt(),hi(),_a(),Oi(),Pc=class extends Ti{static{__name(this,"PgVectorBuilder")}static[ai]="PgVectorBuilder";constructor(e,t){super(e,"array","PgVector"),this.config.dimensions=t.dimensions}build(e){return new Ic(e,this.config)}},Ic=class extends _i{static{__name(this,"PgVector")}static[ai]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(e=>Number.parseFloat(e))}},__name(vector,"vector")}}),$c=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/index.js"(){Bt(),Ra(),$a(),Fa(),Ba(),Ha(),Oi(),Ya(),el(),rl(),Ji(),il(),xa(),cl(),ml(),hl(),bl(),Cl(),_l(),Nl(),Fl(),jl(),Vl(),Yl(),Zl(),nc(),sc(),lc(),pc(),fc(),Sc(),vc(),Tc(),Ac(),Mc(),Lc()}}),Dc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/query-promise.js"(){Bt(),hi(),Rc=class{static{__name(this,"QueryPromise")}static[ai]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}}}),Oc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/selection-proxy.js"(){Bt(),ya(),fi(),hi(),ga(),Xi(),ta(),Nc=class _SelectionProxyHandler{static{__name(this,"SelectionProxyHandler")}static[ai]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if("_"===t)return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===Bi)return{...e[Bi],selectedFields:new Proxy(e[Bi].selectedFields,this)};if("symbol"==typeof t)return e[t];const n=(is(e,Fi)?e._.selectedFields:is(e,ua)?e[Bi].selectedFields:e)[t];if(is(n,ra.Aliased)){if("sql"===this.config.sqlAliasedBehavior&&!n.isSelectionField)return n.sql;const e=n.clone();return e.isSelectionField=!0,e}if(is(n,ra)){if("sql"===this.config.sqlBehavior)return n;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(n,ui)?this.config.alias?new Proxy(n,new ma(new Proxy(n.table,new pa(this.config.alias,this.config.replaceOriginalName??!1)))):n:"object"!=typeof n||null===n?n:new Proxy(n,new _SelectionProxyHandler(this.config))}}}});function getPgColumnBuilders(){return{bigint:bigint,bigserial:bigserial,boolean:boolean,char:char,cidr:cidr,customType:customType,date:date,doublePrecision:doublePrecision,inet:inet,integer:integer,interval:interval,json:json,jsonb:jsonb,line:line,macaddr:macaddr,macaddr8:macaddr8,numeric:numeric,point:point,geometry:geometry,real:real,serial:serial,smallint:smallint,smallserial:smallserial,text:text,time:time,timestamp:timestamp,uuid:uuid,varchar:varchar,bit:bit,halfvec:halfvec,sparsevec:sparsevec,vector:vector}}var Fc,jc,Uc,Bc,qc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/columns/all.js"(){Bt(),Ra(),$a(),Fa(),Ba(),Ha(),Ya(),el(),rl(),il(),cl(),ml(),hl(),bl(),Cl(),_l(),Nl(),Fl(),jl(),Vl(),Yl(),Zl(),nc(),sc(),lc(),pc(),fc(),Sc(),vc(),Tc(),Ac(),Mc(),Lc(),__name(getPgColumnBuilders,"getPgColumnBuilders")}});function pgTableWithSchema(e,t,n,r,o=e){const s=new Uc(e,r,o),i="function"==typeof t?t(getPgColumnBuilders()):t,a=Object.fromEntries(Object.entries(i).map(([e,t])=>{const n=t;n.setName(e);const r=n.build(s);return s[Fc].push(...n.buildForeignKeys(r,s)),[e,r]})),l=Object.fromEntries(Object.entries(i).map(([e,t])=>{const n=t;return n.setName(e),[e,n.buildExtraConfigColumn(s)]})),u=Object.assign(s,a);return u[Yi.Symbol.Columns]=a,u[Yi.Symbol.ExtraConfigColumns]=l,n&&(u[Uc.Symbol.ExtraConfigBuilder]=n),Object.assign(u,{enableRLS:__name(()=>(u[Uc.Symbol.EnableRLS]=!0,u),"enableRLS")})}var zc,Hc,Wc,Gc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/table.js"(){Bt(),hi(),da(),qc(),Fc=Symbol.for("drizzle:PgInlineForeignKeys"),jc=Symbol.for("drizzle:EnableRLS"),Uc=class extends Yi{static{__name(this,"PgTable")}static[ai]="PgTable";static Symbol=Object.assign({},Yi.Symbol,{InlineForeignKeys:Fc,EnableRLS:jc});[Fc]=[];[jc]=!1;[Yi.Symbol.ExtraConfigBuilder]=void 0;[Yi.Symbol.ExtraConfigColumns]={}},__name(pgTableWithSchema,"pgTableWithSchema"),Bc=__name((e,t,n)=>pgTableWithSchema(e,t,n,void 0),"pgTable")}});function index(e){return new zc(!1,e)}function uniqueIndex(e){return new zc(!0,e)}var Vc,Kc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/indexes.js"(){Bt(),ga(),hi(),$c(),zc=class{static{__name(this,"IndexBuilderOn")}constructor(e,t){this.unique=e,this.name=t}static[ai]="PgIndexBuilderOn";on(...e){return new Hc(e.map(e=>{if(is(e,ra))return e;const t=new Ai(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...e){return new Hc(e.map(e=>{if(is(e,ra))return e;const t=new Ai(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=e.defaultConfig,t}),this.unique,!0,this.name)}using(e,...t){return new Hc(t.map(e=>{if(is(e,ra))return e;const t=new Ai(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!0,this.name,e)}},Hc=class{static{__name(this,"IndexBuilder")}static[ai]="PgIndexBuilder";config;constructor(e,t,n,r,o="btree"){this.config={name:r,columns:e,unique:t,only:n,method:o}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new Wc(this.config,e)}},Wc=class{static{__name(this,"Index")}static[ai]="PgIndex";config;constructor(e,t){this.config={...e,table:t}}},__name(index,"index"),__name(uniqueIndex,"uniqueIndex")}});function pgPolicy(e,t){return new Vc(e,t)}var Qc,Yc,Jc,Xc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/policies.js"(){Bt(),hi(),Vc=class{static{__name(this,"PgPolicy")}constructor(e,t){this.name=e,t&&(this.as=t.as,this.for=t.for,this.to=t.to,this.using=t.using,this.withCheck=t.withCheck)}static[ai]="PgPolicy";as;for;to;using;withCheck;_linkedTable;link(e){return this._linkedTable=e,this}},__name(pgPolicy,"pgPolicy")}}),Zc=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/primary-keys.js"(){Bt(),hi(),Gc(),class{static{__name(this,"PrimaryKeyBuilder")}static[ai]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Qc(e,this.columns,this.name)}},Qc=class{static{__name(this,"PrimaryKey")}constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static[ai]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Uc.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}}}),eu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/view-common.js"(){Bt(),Yc=Symbol.for("drizzle:PgViewConfig")}});function toSnakeCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function toCamelCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,t,n)=>e+(0===n?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),"")}function noopCase(e){return e}var tu,nu,ru,ou,su,iu,au,lu,cu,uu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/casing.js"(){Bt(),hi(),da(),__name(toSnakeCase,"toSnakeCase"),__name(toCamelCase,"toCamelCase"),__name(noopCase,"noopCase"),Jc=class{static{__name(this,"CasingCache")}static[ai]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert="snake_case"===e?toSnakeCase:"camelCase"===e?toCamelCase:noopCase}getColumnCasing(e){if(!e.keyAsName)return e.name;const t=`${e.table[Yi.Symbol.Schema]??"public"}.${e.table[Yi.Symbol.OriginalName]}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){const t=`${e[Yi.Symbol.Schema]??"public"}.${e[Yi.Symbol.OriginalName]}`;if(!this.cachedTables[t]){for(const n of Object.values(e[Yi.Symbol.Columns])){const e=`${t}.${n.name}`;this.cache[e]=this.convert(n.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}}}),du=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/errors.js"(){Bt(),hi(),tu=class extends Error{static{__name(this,"DrizzleError")}static[ai]="DrizzleError";constructor({message:e,cause:t}){super(e),this.name="DrizzleError",this.cause=t}},nu=class _DrizzleQueryError extends Error{static{__name(this,"DrizzleQueryError")}constructor(e,t,n){super(`Failed query: ${e}\nparams: ${t}`),this.query=e,this.params=t,this.cause=n,Error.captureStackTrace(this,_DrizzleQueryError),n&&(this.cause=n)}},ru=class extends tu{static{__name(this,"TransactionRollbackError")}static[ai]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}}});function bindIfParam(e,t){return!isDriverValueEncoder(t)||isSQLWrapper(e)||is(e,aa)||is(e,la)||is(e,ui)||is(e,Yi)||is(e,ua)?e:new aa(e,t)}function and(...e){const t=e.filter(e=>void 0!==e);if(0!==t.length)return 1===t.length?new ra(t):new ra([new na("("),sql.join(t,new na(" and ")),new na(")")])}function or(...e){const t=e.filter(e=>void 0!==e);if(0!==t.length)return 1===t.length?new ra(t):new ra([new na("("),sql.join(t,new na(" or ")),new na(")")])}function not(e){return sql`not ${e}`}function inArray(e,t){return Array.isArray(t)?0===t.length?sql`false`:sql`${e} in ${t.map(t=>bindIfParam(t,e))}`:sql`${e} in ${bindIfParam(t,e)}`}function notInArray(e,t){return Array.isArray(t)?0===t.length?sql`true`:sql`${e} not in ${t.map(t=>bindIfParam(t,e))}`:sql`${e} not in ${bindIfParam(t,e)}`}function isNull(e){return sql`${e} is null`}function isNotNull(e){return sql`${e} is not null`}function exists(e){return sql`exists ${e}`}function notExists(e){return sql`not exists ${e}`}function between(e,t,n){return sql`${e} between ${bindIfParam(t,e)} and ${bindIfParam(n,e)}`}function notBetween(e,t,n){return sql`${e} not between ${bindIfParam(t,e)} and ${bindIfParam(n,e)}`}function like(e,t){return sql`${e} like ${t}`}function notLike(e,t){return sql`${e} not like ${t}`}function ilike(e,t){return sql`${e} ilike ${t}`}function notIlike(e,t){return sql`${e} not ilike ${t}`}var mu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/expressions/conditions.js"(){Bt(),fi(),hi(),da(),ga(),__name(bindIfParam,"bindIfParam"),ou=__name((e,t)=>sql`${e} = ${bindIfParam(t,e)}`,"eq"),su=__name((e,t)=>sql`${e} <> ${bindIfParam(t,e)}`,"ne"),__name(and,"and"),__name(or,"or"),__name(not,"not"),iu=__name((e,t)=>sql`${e} > ${bindIfParam(t,e)}`,"gt"),au=__name((e,t)=>sql`${e} >= ${bindIfParam(t,e)}`,"gte"),lu=__name((e,t)=>sql`${e} < ${bindIfParam(t,e)}`,"lt"),cu=__name((e,t)=>sql`${e} <= ${bindIfParam(t,e)}`,"lte"),__name(inArray,"inArray"),__name(notInArray,"notInArray"),__name(isNull,"isNull"),__name(isNotNull,"isNotNull"),__name(exists,"exists"),__name(notExists,"notExists"),__name(between,"between"),__name(notBetween,"notBetween"),__name(like,"like"),__name(notLike,"notLike"),__name(ilike,"ilike"),__name(notIlike,"notIlike")}});function asc(e){return sql`${e} asc`}function desc(e){return sql`${e} desc`}var pu,gu,hu,fu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/expressions/select.js"(){Bt(),ga(),__name(asc,"asc"),__name(desc,"desc")}}),yu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/expressions/index.js"(){Bt(),mu(),fu()}});function getOperators(){return{and:and,between:between,eq:ou,exists:exists,gt:iu,gte:au,ilike:ilike,inArray:inArray,isNull:isNull,isNotNull:isNotNull,like:like,lt:lu,lte:cu,ne:su,not:not,notBetween:notBetween,notExists:notExists,notLike:notLike,notIlike:notIlike,notInArray:notInArray,or:or,sql:sql}}function getOrderByOperators(){return{sql:sql,asc:asc,desc:desc}}function normalizeRelation(e,t,n){if(is(n,gu)&&n.config)return{fields:n.config.fields,references:n.config.references};const r=t[getTableUniqueName(n.referencedTable)];if(!r)throw new Error(`Table "${n.referencedTable[Yi.Symbol.Name]}" not found in schema`);const o=e[r];if(!o)throw new Error(`Table "${r}" not found in schema`);const s=n.sourceTable,i=t[getTableUniqueName(s)];if(!i)throw new Error(`Table "${s[Yi.Symbol.Name]}" not found in schema`);const a=[];for(const e of Object.values(o.relations))(n.relationName&&n!==e&&e.relationName===n.relationName||!n.relationName&&e.referencedTable===n.sourceTable)&&a.push(e);if(a.length>1)throw n.relationName?new Error(`There are multiple relations with name "${n.relationName}" in table "${r}"`):new Error(`There are multiple relations between "${r}" and "${n.sourceTable[Yi.Symbol.Name]}". Please specify relation name`);if(a[0]&&is(a[0],gu)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw new Error(`There is not enough information to infer relation "${i}.${n.fieldName}"`)}function mapRelationalRow(e,t,n,r,o=e=>e){const s={};for(const[i,a]of r.entries())if(a.isJson){const r=t.relations[a.tsKey],l=n[i],u="string"==typeof l?JSON.parse(l):l;s[a.tsKey]=is(r,gu)?u&&mapRelationalRow(e,e[a.relationTableTsKey],u,a.selection,o):u.map(t=>mapRelationalRow(e,e[a.relationTableTsKey],t,a.selection,o))}else{const e=o(n[i]),t=a.field;let r;r=is(t,ui)?t:is(t,ra)?t.decoder:t.sql.decoder,s[a.tsKey]=null===e?null:r.mapFromDriverValue(e)}return s}var wu,Su,bu,Eu,vu,Cu,ku,Tu,_u,xu,Au,Pu,Iu,Mu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/relations.js"(){Bt(),da(),fi(),hi(),yu(),ga(),pu=class{static{__name(this,"Relation")}constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[Yi.Symbol.Name]}static[ai]="Relation";referencedTableName;fieldName},class{static{__name(this,"Relations")}constructor(e,t){this.table=e,this.config=t}static[ai]="Relations"},gu=class _One extends pu{static{__name(this,"One")}constructor(e,t,n,r){super(e,t,n?.relationName),this.config=n,this.isNullable=r}static[ai]="One";withFieldName(e){const t=new _One(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}},hu=class _Many extends pu{static{__name(this,"Many")}constructor(e,t,n){super(e,t,n?.relationName),this.config=n}static[ai]="Many";withFieldName(e){const t=new _Many(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}},__name(getOperators,"getOperators"),__name(getOrderByOperators,"getOrderByOperators"),__name(normalizeRelation,"normalizeRelation"),__name(mapRelationalRow,"mapRelationalRow")}}),Ru=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/functions/aggregate.js"(){Bt()}}),Nu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/functions/vector.js"(){Bt()}}),Lu=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/functions/index.js"(){Bt(),Ru(),Nu()}}),$u=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/sql/index.js"(){Bt(),yu(),Lu(),ga()}}),Du=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/view-base.js"(){Bt(),hi(),ga(),wu=class extends ua{static{__name(this,"PgViewBase")}static[ai]="PgViewBase"}}}),Ou=__esm({"../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@4.20260130.0_@opentelemetry+api@1.9.0_@typ_ff87cf668fd5ce504890f2a2e75118cb/node_modules/drizzle-orm/pg-core/dialect.js"(){Bt(),ya(),uu(),fi(),hi(),du(),$c(),Gc(),Mu(),$u(),ga(),Xi(),da(),_a(),ta(),Du(),Su=class{static{__name(this,"PgDialect")}static[ai]="PgDialect";casing;constructor(e){this.casing=new Jc(e?.casing)}async migrate(e,t,n){const r="string"==typeof n?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",o="string"==typeof n?"drizzle":n.migrationsSchema??"drizzle",s=sql`
3
3
  CREATE TABLE IF NOT EXISTS ${sql.identifier(o)}.${sql.identifier(r)} (
4
4
  id SERIAL PRIMARY KEY,
5
5
  hash text NOT NULL,
@@ -321,4 +321,4 @@ import*as e from"path";import t,{join as n,dirname as r,parse as o,relative as s
321
321
  ░█▀▀░█▀▄▀█░█▀▄░
322
322
  ░█░░░█░▀░█░█░█░
323
323
  ░▀▀▀░▀░░░▀░▀▀░░
324
- `,jP=getMaxLineWidth(FP),UP=$P,BP=__name(e=>{const t=e??getTerminalWidth();return t>=LP?"full":t>=UP?"compact":"minimal"},"getHeaderLayout");Bt(),Vr();var qP=__name(({children:e})=>{const t=[];let n="",r=!0;const o=__name(()=>{0!==n.length&&(t.push({text:n,panel:r}),n="")},"flush");for(const t of e){const e="░"===t;0===n.length?r=e:e!==r&&(o(),r=e),n+=t}return o(),re.createElement(Y,null,t.map((e,t)=>re.createElement(Y,{key:t,backgroundColor:Br.BG,color:e.panel?Br.BG:Br.TEXT},e.panel?e.text.replaceAll("░"," "):e.text)))},"CommandLogoBanner");Bt(),Vr();var zP=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:o=0,titleColor:s=br.GRAY,dividerChar:i="─",dividerColor:a=br.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*o),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return re.createElement(Q,{paddingLeft:o,paddingRight:o,marginBottom:1,...l},(t||n)&&re.createElement(Y,{color:a},d),e&&re.createElement(Y,{color:s},m),re.createElement(Y,{color:a},f),r&&re.createElement(Y,{color:br.DIM},g))},"Divider");hC(),Vr(),Bt(),Vr();var HP=[{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}],WP=__name(({onComplete:e,onExit:t})=>{const[n,r]=se(0),[o,s]=se(!1),i=n>=HP.length;return ae(()=>{if(n>=HP.length)return;if(o)return;const e=HP[n],t=setTimeout(()=>{r(e=>Math.min(e+1,HP.length))},e.duration);return()=>clearTimeout(t)},[n,o]),Z((n,o)=>{""===n||o.ctrl&&"c"===n?t?t():e():o.escape?e():i?(o.return||" "===n)&&e():" "===n?s(e=>!e):o.return&&r(e=>Math.min(e+1,HP.length))}),re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Meet Your Coding Taste")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Command Code learns your coding style as you work.")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Here's how your preferences evolve in real-time:")),re.createElement(Q,{flexDirection:"column",marginY:1},HP.slice(0,n).map((e,t)=>"user"===e.type?re.createElement(Q,{key:t},re.createElement(Y,null,Re.pointer," ",e.text)):re.createElement(Q,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"⎿ "),re.createElement(Y,{color:vr.TEXT},e.text)),e.details&&re.createElement(Q,{marginLeft:3},re.createElement(Y,{color:br.DIM},"Saved(",e.details,")"))))),i?re.createElement(Q,{flexDirection:"column",marginY:1},re.createElement(Q,null,re.createElement(Y,{bold:!0,color:vr.TEXT},"Demo Complete!")),re.createElement(Q,null,re.createElement(Y,null,"Command Code will now use these preferences to generate")),re.createElement(Q,null,re.createElement(Y,null,"better suggestions tailored to your coding style. The")),re.createElement(Q,null,re.createElement(Y,null,"more you code, the smarter it gets.")),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Enter to get started →"))):re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(o?" (paused)":""))))},"TasteDemoComponent"),GP=__name(({onClose:e,onExit:t})=>{const[n,r]=se(FC.getEvents()),[o,s]=se(0);Z((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),ae(()=>{const e=__name(()=>{r(FC.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return FC.on("new-event",e),FC.on("cleared",t),()=>{FC.off("new-event",e),FC.off("cleared",t)}},[]),ae(()=>{const e=__name(()=>{uC(),s(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=le(()=>n.find(e=>"analyzing"===e.type),[n]),l=le(()=>n.find(e=>"analyzed"===e.type),[n]),u=le(()=>n.find(e=>"no_learnings"===e.type),[n]),d=le(()=>n.find(e=>"learned"===e.type||"refactored"===e.type),[n]),m=u?n.indexOf(u):1/0,g=d?n.indexOf(d):1/0,h=!!u&&m<g,f=!!a||!!l||h,y=le(()=>n.filter(e=>"analyzing"!==e.type&&"analyzed"!==e.type&&"no_learnings"!==e.type),[n]),w=le(()=>[...y].reverse(),[y]),S=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const i={learned:"LEARNED",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),E=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),v=__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"),C=le(()=>(process.stdout.rows??24)-1,[o]);return re.createElement(Q,{flexDirection:"column",width:"100%",height:C,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(qP,null,DP())),re.createElement(zP,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),re.createElement(Q,{flexDirection:"column"},0===n.length?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Q,null,re.createElement(Y,null,"Start using Command Code and it will begin recording your coding taste.")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Your preferences, patterns, and style will appear here in real-time."))),re.createElement(ne,{count:2}),re.createElement(zP,{title:"DEMO",titleColor:"white",subPrefix:!0}),re.createElement(WP,{onComplete:()=>{e()},onExit:t})):re.createElement(Q,{flexDirection:"column"},y.length>0&&re.createElement(Q,{flexDirection:"column",gap:1},w.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:o}=S(e.message),s="moved"===t?v(e.details):null,i="upgraded"===t||"downgraded"===t?E(r):null,a=s?.fullPath??e.details;let l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:br.DIM}," ","(",o,")"));return i&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",i.text," ("),re.createElement(Y,{color:br.DIM},"confidence:"," "),re.createElement(Y,{color:br.DIM},i.oldPercent,"%"),re.createElement(Y,null," ",Re.arrowRight," "),re.createElement(Y,{color:i.diff>0?br.GREEN:br.RED},i.newPercent,"%"),re.createElement(Y,null,")"))),s&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",s.category," ","package ("),re.createElement(Y,{color:br.DIM},s.oldPath),re.createElement(Y,null," ",Re.arrowRight," ",s.newPath),re.createElement(Y,null,")"))),re.createElement(Q,{key:e.id},re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:vr.BADGE_BG,color:vr.BADGE_FG,bold:!0},`${Lx}${n}${Lx}`)),a&&re.createElement(Y,{color:br.DIM}," ","(",a,")")),re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM},"⎿"," "),l)))}return re.createElement(Q,{key:e.id},re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",e.message))})),f&&re.createElement(Q,{flexDirection:"column",marginTop:y.length>0?1:0},a&&re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",a.message)),l&&re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",l.message)),h&&u&&re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",u.message))))))},"LearningFeedFull");function useListNavigation({items:e,onSelect:t,onCancel:n,validate:r,initialIndex:o=0,searchCursorIndex:s=0,searchQuery:i,onSearchChange:a,isActive:l=!0,disableSearch:u=!1,selectByNumber:d=!1,onReset:m}){const[g,h]=se(o),[f,y]=se(null);ae(()=>{i||h(o)},[o,i]);const w=e.length-1,S=__name(e=>{a(e),h(s)},"updateSearch");return Z((o,s)=>{if(s.escape)return!u&&i?void S(""):void n();if(u||!s.backspace&&!s.delete){if(u&&m&&"r"===o&&!s.ctrl&&!s.meta){const t=e[g];return void(t&&m(t))}if(0!==e.length){if(s.upArrow)return y(null),void h(e=>Math.max(e-1,0));if(s.downArrow)return y(null),void h(e=>Math.min(e+1,w));if(s.return){const n=e[g];if(!n)return;if(r){const e=r(n);if(e)return void y(e)}return void t(n)}if(d&&1===o.length&&o>="1"&&o<="9"&&!s.ctrl&&!s.meta){const n=Number(o)-1,s=e[n];if(!s)return;if(h(n),r){const e=r(s);if(e)return void y(e)}return void t(s)}!u&&!s.ctrl&&!s.meta&&!s.tab&&o&&1===o.length&&o>=" "&&S(i+o)}}else S(i.slice(0,-1))},{isActive:l}),{cursor:g,error:f,setError:y}}Bt(),Bt(),Vr(),Bt(),__name(useListNavigation,"useListNavigation");var VP=[{scope:"project",label:"This project"},{scope:"global",label:"User"}],KP=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=se(!0),[s,i]=se(void 0),[a,l]=se(void 0),[u,d]=se(!0),m="local"===a,g=ce(async()=>{try{const e=await getTasteLearningSettings();o(e.global),i(e.project),l(e.projectSource)}catch{}},[]);ae(()=>{g().finally(()=>d(!1))},[g]);const h=__name(async(e,n,r)=>{e();try{await r(),t?.(),await g()}catch(e){n()}},"persist"),f=__name(e=>{if("global"===e.scope){const e=!r;return h(()=>o(e),()=>o(!e),()=>setTasteLearning({tasteLearning:e,scope:"global"}))}if(m)return;const t=s,n=!(t??r);return h(()=>i(n),()=>i(t),()=>setTasteLearning({tasteLearning:n,scope:"project"}))},"toggleRow"),y=__name(e=>{if("global"===e.scope){if(r)return;return h(()=>o(!0),()=>o(!1),()=>setTasteLearning({tasteLearning:!0,scope:"global"}))}if(m)return;const t=s;return void 0!==t?h(()=>i(void 0),()=>i(t),()=>clearProjectTasteLearning()):void 0},"resetRow"),{cursor:w}=useListNavigation({items:VP,onSelect:__name(e=>{f(e)},"onSelect"),onReset:__name(e=>{y(e)},"onReset"),onCancel:e,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:!u});if(u)return re.createElement(Q,{key:n,borderStyle:"single",borderColor:br.BLUE,padding:1,flexDirection:"column"},re.createElement(Y,{color:br.BLUE,bold:!0},"Taste Settings"),re.createElement(Y,{color:br.DIM},"Loading configuration..."));const S=__name(e=>"project"===e.scope?s??r:r,"valueFor");return re.createElement(Q,{key:n,borderStyle:"single",borderColor:br.GRAY,padding:1,flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Taste Learning"),re.createElement(Y,{color:br.DIM},"Learn from your interactions."),re.createElement(Q,{marginTop:1}),VP.map((e,t)=>{const n=t===w,r=S(e),o="project"===e.scope&&m;return re.createElement(Q,{key:e.scope},re.createElement(Y,{color:n?br.CYAN:br.GRAY},n?`${Re.pointer} `:" "),re.createElement(Y,{color:n?br.CYAN:br.WHITE},e.label.padEnd(16)),re.createElement(Y,{color:r?br.GREEN:br.DIM},r?"enabled":"disabled"),o?re.createElement(Y,{color:br.DIM}," ","(set in settings.local.json)"):null)}),re.createElement(Q,{marginTop:1}),re.createElement(Y,{color:br.DIM},"Taste data stored in .commandcode/taste/taste.md"),m?re.createElement(Y,{color:br.DIM},"This project is pinned by .commandcode/settings.local.json — edit that file to change it."):null,re.createElement(Y,{color:br.DIM},"↑/↓ navigate · enter to toggle · r reset to default · esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(KP,{onClose:t,onSettingsChange:n,staticKey:e})))}function fuzzyMatch(e,t){let n=0;for(const r of e)if(r===t[n]&&(n++,n===t.length))return!0;return!1}function fuzzyScore(e,t){let n=0;for(const r of e)fuzzyMatch(r.text.toLowerCase(),t)&&(n+=r.weight);return n}function fuzzyFilter(e,t,n){if(!t.trim())return e;const r=t.toLowerCase().split("");return e.map(e=>({item:e,score:fuzzyScore(n(e),r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score).map(({item:e})=>e)}__name(TasteConfigView,"TasteConfigView"),Bt(),Bt(),_n(),Bt(),__name(fuzzyMatch,"fuzzyMatch"),__name(fuzzyScore,"fuzzyScore"),__name(fuzzyFilter,"fuzzyFilter"),Vr(),Bt(),Vr();var QP=__name(({query:e,resultCount:t,placeholder:n="Type to search..."})=>re.createElement(Q,{width:"100%"},re.createElement(Y,{color:br.GRAY},Re.pointerSmall," "),re.createElement(Y,{color:e?br.WHITE:br.GRAY},e||n),e&&void 0!==t&&re.createElement(Y,{dimColor:!0}," (",t," found)")),"SearchInput");function useTerminalHeight(){const{stdout:e}=X(),[t,n]=se(()=>e?.rows??24);return ae(()=>{const t=__name(()=>n(e?.rows??24),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function skillIdentifier(e){const n=t.basename(e);return"skill.md"===n.toLowerCase()?t.basename(t.dirname(e)):n}Bt(),__name(useTerminalHeight,"useTerminalHeight"),Bt(),_n(),Vr(),Bt(),hC(),Vr(),ko(),Bt(),__name(skillIdentifier,"skillIdentifier");var YP=new Set(["Invalid YAML","Missing fields","Missing SKILL.md"]);function categoryColor(e){return YP.has(e)?br.RED:br.YELLOW}function formatWarningsAsMarkdown(e){const t=groupWarnings(e),n=[`# Skipped skills (${e.length})`,""];for(const e of t){n.push(`## ${e.category} (${e.items.length})`,"");for(const t of e.items)n.push(`- \`${skillIdentifier(t.path)}\` — \`${t.path}\``),n.push(` - ${t.reason}`);n.push("")}return n.join("\n").replace(/\n+$/,"")+"\n"}async function copyAllWarnings(e,t){try{const{isClipboardAvailable:n}=await Promise.resolve().then(()=>(so(),ro));if(!n())return void t({text:"Clipboard unavailable — copy the skipped skill paths manually",color:br.YELLOW});const r=await import("@crosscopy/clipboard");await r.default.setText(formatWarningsAsMarkdown(e));const o=e.length;t({text:`Copied ${o} issue${1===o?"":"s"} to clipboard`,color:br.GREEN})}catch{t({text:"Clipboard write failed",color:br.YELLOW})}}__name(categoryColor,"categoryColor"),__name(formatWarningsAsMarkdown,"formatWarningsAsMarkdown"),__name(copyAllWarnings,"copyAllWarnings");var JP=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,i]=se(null),a=ie(null),l=ie(!0);ae(()=>()=>{l.current=!1,a.current&&(clearTimeout(a.current),a.current=null)},[]);const u=__name(e=>{l.current&&(a.current&&clearTimeout(a.current),i(e),a.current=setTimeout(()=>{l.current&&(i(null),a.current=null)},3e3))},"showStatus");return Z((n,r)=>r.escape||" "===n&&o?(uC(),void t()):void("c"===n&&o&&copyAllWarnings(e,u)),{isActive:n}),re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Skills"," "),re.createElement(Y,{color:br.DIM},"› "),re.createElement(Y,{color:Er,bold:!0},"Skipped"," "),re.createElement(Y,{color:br.WHITE},e.length)),o&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Press c to copy all issues")),o?re.createElement(Q,{flexDirection:"column"},r.map(e=>re.createElement(Q,{key:e.category,flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:categoryColor(e.category)},e.category)),e.items.map(e=>re.createElement(Q,{key:e.path,flexDirection:"column",marginBottom:1},re.createElement(Q,{paddingLeft:2},re.createElement(Eo,{url:m(e.path).href,text:skillIdentifier(e.path),color:br.WHITE})),re.createElement(Q,{paddingLeft:4},re.createElement(Y,{color:br.WHITE},e.reason))))))):re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"No issues — every skill loaded.")),s&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:s.color},s.text)),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),XP=__name(({warnings:e=[],onClose:t})=>{const[n,r]=se("list");return Z((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?re.createElement(JP,{warnings:e,onClose:()=>r("list"),isActive:!0}):re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Skills"),e.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.YELLOW},e.length," skipped"))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"No skills found")),re.createElement(Y,{color:br.DIM},"Create skills in:"),re.createElement(Y,{color:br.DIM}," ","~/",".commandcode","/","skills","/ (user)"),re.createElement(Y,{color:br.DIM}," ","~/.agents/","skills","/ (user, .agents)"),re.createElement(Y,{color:br.DIM}," ",".commandcode","/","skills","/ (project)"),re.createElement(Y,{color:br.DIM}," ",".agents/","skills","/ (project, .agents)"),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},e.length>0&&"space to view issues · ","Press ",re.createElement(Y,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");function clampScrollOffset(e){const{cursor:t,total:n,maxVisible:r,currentOffset:o}=e;if(n<=r)return 0;let s=o;t<s?s=t:t>=s+r&&(s=t-r+1);const i=Math.max(0,n-r);return Math.min(Math.max(0,s),i)}function sliceSectionForWindow(e){const{section:t,sectionBase:n,windowStart:r,windowEnd:o}=e,s=Math.min(Math.max(r-n,0),t.length),i=Math.min(Math.max(o-n,0),t.length);return{rows:t.slice(s,i),baseIndex:n+s}}Bt(),__name(clampScrollOffset,"clampScrollOffset"),__name(sliceSectionForWindow,"sliceSectionForWindow"),Bt();var ZP=__name(e=>Math.ceil(e.length/4),"estimateTokens"),eI=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),tI={user:"user settings",projectShared:"project shared",projectLocal:"project local"},nI=__name(()=>"win32"===process.platform?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===process.platform?"~/.zshrc":"~/.bashrc"),"getEditorSetupMessage");Bt(),Vr();var rI=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Q,null,re.createElement(Y,{color:Mr,bold:!0},e," "),re.createElement(Y,{color:Mr},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=eI(e.filePath),l=n?zr:void 0;return re.createElement(Q,{key:e.filePath},re.createElement(Y,{color:i?br.DIM:br.GREEN,backgroundColor:l},i?"[off] ":"[on] "),re.createElement(Y,{color:i?br.DIM:br.WHITE,backgroundColor:l},e.label),a&&re.createElement(Y,{color:br.DIM,backgroundColor:l}," [.agents]"),re.createElement(Y,{color:br.DIM,backgroundColor:l}," · ~",ZP(e.description)," tokens "))})),"SkillSection");Bt();var oI=__name(e=>[{text:e.label,weight:100}],"SKILL_SEARCH_FIELDS"),sI=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se([]),[s,i]=se(!0),[a,l]=se(null),[u,d]=se(""),[m,g]=se(new Set),[h,f]=se(new Map),[y,w]=se(!1),[S,E]=se(null),[v,C]=se("list"),[k,T]=se(0),_=useTerminalHeight(),x=ie(!1);ae(()=>{__name(async()=>{try{const e=findGitRoot(),t=getBundledSkillsDir(),[{global:r,project:s,warnings:i},a]=await Promise.all([loadAllSkillSummariesWithWarnings(),loadDisabledSkills({projectRoot:e})]),l=__name(e=>isBundledSkillPath({filePath:e,bundledDir:t}),"isBundled"),u=[...s.map(e=>({label:e.name,location:"project",description:e.description,filePath:e.filePath})),...r.filter(e=>!l(e.filePath)).map(e=>({label:e.name,location:"user",description:e.description,filePath:e.filePath})),...r.filter(e=>l(e.filePath)).map(e=>({label:e.name,location:"bundled",description:e.description,filePath:e.filePath}))];u.sort((e,t)=>{if(e.location!==t.location){const n={project:0,user:1,bundled:2};return n[e.location]-n[t.location]}return e.label.localeCompare(t.label)}),n(u),o(i),g(new Set(a.names)),f(new Map(a.bySkill)),w(a.noProjectRoot)}catch(e){l(e instanceof Error?e.message:"Failed to load skills")}finally{i(!1)}},"load")()},[]);const A=le(()=>fuzzyFilter(t.filter(e=>"project"===e.location),u,oI),[t,u]),P=le(()=>fuzzyFilter(t.filter(e=>"user"===e.location),u,oI),[t,u]),I=le(()=>fuzzyFilter(t.filter(e=>"bundled"===e.location),u,oI),[t,u]),M=le(()=>[...A,...P,...I],[A,P,I]),R=_-1,N=(A.length>0?1:0)+(P.length>0?1:0)+(I.length>0?1:0),L=Math.max(4,R-12-2*N),$=__name(async e=>{if(x.current)return;const t=m.has(e.label),n=h.get(e.label);if(t&&void 0!==n&&"projectLocal"!==n&&!y)return void E(`Cannot enable: "${e.label}" is disabled in ${tI[n]}. Edit that file to override.`);x.current=!0;const r=new Set(m);t&&r.delete(e.label),t||r.add(e.label),g(r),E(null);try{const n=findGitRoot(),r=await setSkillEnabled(e.label,t,{projectRoot:n}),o=new Map(h);t&&o.delete(e.label),t||o.set(e.label,r),f(o),"user"===r&&E("Saved to user settings — no project found.")}catch(e){g(m),E(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{x.current=!1}},"toggleSkill");ae(()=>{"issues"===v&&d("")},[v]);const D="list"===v&&t.length>0,{cursor:O}=useListNavigation({items:M,onSelect:$,onCancel:e,searchQuery:u,onSearchChange:d,initialIndex:0,isActive:D});if(ae(()=>{T(e=>clampScrollOffset({cursor:O,total:M.length,maxVisible:L,currentOffset:e}))},[O,M.length,L]),Z((t,n)=>{if(!n.tab)return;const r=M[O];r&&(async()=>{try{await Et([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(nI());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),Z((e,n)=>{"list"===v&&0!==t.length&&" "===e&&!n.ctrl&&!n.meta&&r.length>0&&0===u.length&&C("issues")},{isActive:"list"===v&&t.length>0}),s)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:Er,bold:!0},"Skills"),re.createElement(Y,{color:br.DIM},"Loading skills..."));if(a)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:br.RED,bold:!0},"Skills"),re.createElement(Y,{color:br.DIM},a),re.createElement(Q,{marginTop:1}),re.createElement(Y,{color:br.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close"));if(0===t.length)return re.createElement(XP,{warnings:r,onClose:e});if("issues"===v)return re.createElement(JP,{warnings:r,onClose:()=>C("list"),isActive:!0});const F=t.filter(e=>m.has(e.label)).length,j=k,U=k+L,B=sliceSectionForWindow({section:A,sectionBase:0,windowStart:j,windowEnd:U}),q=sliceSectionForWindow({section:P,sectionBase:A.length,windowStart:j,windowEnd:U}),z=sliceSectionForWindow({section:I,sectionBase:A.length+P.length,windowStart:j,windowEnd:U}),H=M.length>L;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Skills"," "),re.createElement(Y,{color:br.DIM},t.length," skill",1===t.length?"":"s"),F>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.YELLOW},F," off")),r.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.YELLOW},r.length," skipped"))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{dimColor:!0},y?"No project found — toggles will be saved to user settings.":"Toggle skills on or off for this project.")),re.createElement(Q,{marginBottom:1,flexDirection:"column",width:"100%"},re.createElement(QP,{query:u,resultCount:u?M.length:void 0,placeholder:"Type to search skills..."})),0===M.length?re.createElement(Q,{marginY:1},re.createElement(Y,{color:br.GRAY},'No skills match "',u,'"')):re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},B.rows.length>0&&re.createElement(rI,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:B.rows,baseIndex:B.baseIndex,cursor:O,disabled:m}),q.rows.length>0&&re.createElement(rI,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:q.rows,baseIndex:q.baseIndex,cursor:O,disabled:m}),z.rows.length>0&&re.createElement(rI,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:z.rows,baseIndex:z.baseIndex,cursor:O,disabled:m})),H&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",j+1,"–",Math.min(U,M.length)," of"," ",M.length,j>0?" · ↑ more":"",U<M.length?" · ↓ more":""))),S&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.YELLOW},S)),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},"type to search · ↑/↓ navigate · enter to toggle · tab to edit",r.length>0&&!u&&re.createElement(re.Fragment,null," · space to view issues"),u?" · esc to clear":" · esc to close"),re.createElement(Y,{color:br.DIM},"add skills:"," ",re.createElement(Y,{color:br.CYAN},"cmd skills add ","<owner/repo>"))))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return re.useEffect(()=>{hardResetForResize()},[]),re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(sI,{onClose:t,staticKey:e})))}function getUsageColor(e){return e>=80?br.RED:e>=50?br.YELLOW:br.GREEN}function buildBlockBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e));let r=Math.round(n/100*t);n>.5&&0===r&&(r=1),n<99.5&&r===t&&(r=t-1);const o=t-r;return{filled:"█".repeat(r),empty:"░".repeat(o)}}function getStudioUsageUrl(e){const t=e?.org?.login??e?.user?.userName;return t?`https://commandcode.ai/${t}/settings/usage`:null}__name(SkillsConfigView,"SkillsConfigView"),Bt(),Bt(),Vr(),Bt(),Vr(),__name(getUsageColor,"getUsageColor"),__name(buildBlockBar,"buildBlockBar"),ko(),__name(getStudioUsageUrl,"getStudioUsageUrl");var iI=__name(e=>e.replace(/^https?:\/\//,""),"stripScheme");function getProgressBarWidth({terminalWidth:e}){return e<50?Math.max(10,e-10):e<70?Math.max(15,e-15):Math.min(30,e-15)}function getDaysColor(e){if(null!==e)return e<3?br.RED:e<7?br.YELLOW:void 0}__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var aI=__name(({plan:e,status:t})=>re.createElement(Q,{marginBottom:0},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:br.BLUE,color:"#f4f4f4",bold:!0},`${Lx}USAGE${Lx}`)),e&&re.createElement(re.Fragment,null,re.createElement(Y,null," "),re.createElement(Y,{color:br.GRAY},`${e.name} Plan`)),t&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:"active"===t?br.GREEN:br.YELLOW},t))),"UsageBadge"),lI=__name(({showRetry:e})=>re.createElement(Q,{marginTop:1},e&&re.createElement(Y,{color:br.DIM},re.createElement(Y,{bold:!0},"r")," to retry · "),re.createElement(Y,{color:br.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close")),"UsageFooter"),cI=__name(({onClose:e})=>{const[t,n]=se("loading"),[r,o]=se(null),[s,i]=se(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ce(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return i(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),u=re.useRef(null);Z((r,o)=>{if(o.escape&&e(),"r"===r&&"error"===t){n("loading"),u.current?.abort();const e=new AbortController;u.current=e,l(e.signal)}}),ae(()=>{const e=new AbortController;return u.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?.subscription?.data??null,m=d?getPlanInfo({planId:d.planId??""}):null;if("loading"===t)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(aI,{plan:m,status:d?.status??null}),re.createElement(Y,{color:br.DIM},"Loading…"),re.createElement(lI,null));if("error"===t)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(aI,{plan:m,status:d?.status??null}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),re.createElement(lI,{showRetry:!s}));if(!r)return null;const g=r.credits||r.subscription,h=getStudioUsageUrl(r.whoami);if(!g)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(aI,{plan:m,status:d?.status??null}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"No billing data found."),h&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," Visit "),re.createElement(Eo,{url:h,text:"Studio",color:br.CYAN}),re.createElement(Y,{color:br.DIM}," for usage details."))),re.createElement(lI,null));const f=r.credits?.credits,y=r.summary,w=Math.max(0,f?.monthlyCredits??0)+Math.max(0,f?.purchasedCredits??0)+Math.max(0,f?.freeCredits??0),S=Math.max(0,y?.totalCost??0),E=getUsagePercent({used:S,total:S+w}),v=w>0||S>0,C=d?.currentPeriodEnd?getDaysRemaining(d.currentPeriodEnd):null,k=getDaysColor(C),T=getUsageColor(E),_=buildBlockBar({percentage:E,width:a});return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,{marginBottom:1},re.createElement(aI,{plan:m,status:d?.status??null})),v?re.createElement(Q,null,re.createElement(Y,{color:T},_.filled),re.createElement(Y,{color:Mr},_.empty),re.createElement(Y,{bold:!0,color:T},` ${Math.round(E)}% used`)):re.createElement(Y,{color:br.DIM},"Plan details unavailable"),v&&re.createElement(Q,null,d?.currentPeriodEnd&&re.createElement(Y,{color:br.DIM},"Cycle: "),re.createElement(Y,null,formatCredits(w)),re.createElement(Y,{color:br.DIM}," left"),y&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,null,y.totalCount.toLocaleString()),re.createElement(Y,{color:br.DIM}," requests")),null!==C&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),0===C?re.createElement(Y,{color:k},"renewal today"):re.createElement(re.Fragment,null,re.createElement(Y,{color:k},`${C} day${1===C?"":"s"}`),re.createElement(Y,{color:br.DIM}," to renewal")))),h&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Full breakdown at "),re.createElement(Eo,{url:h,text:iI(h),color:br.CYAN})),re.createElement(lI,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(cI,{onClose:t})))}__name(UsageView,"UsageView"),Bt(),Bt(),_n(),SE(),QS(),Gb(),Co();var uI="System prompt",dI="Messages";function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&!isHiddenTranscriptMessage({message:r})&&t++,"assistant"===r.message.role&&n++;return{user:t,assistant:n}}function countToolCalls({messages:e}){let t=0,n=0;for(const r of e){if(isHiddenTranscriptMessage({message:r}))continue;const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)isHiddenTranscriptMessage({message:n})||(t+=estimateTokens(n.message));return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:Cn.TIER_1_THRESHOLD,description:`Prune to last ${Cn.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:Cn.TIER_2_THRESHOLD,description:`Prune to last ${Cn.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:Cn.TIER_3_THRESHOLD,description:"Full summarization"}];let o=0;const s=r.map(r=>{const s=Math.round(r.threshold*t),i=Math.max(0,s-e);let a="upcoming";return n>=r.threshold&&(a="passed",o=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:s,description:r.description,status:a,tokensAway:i}}),i=s.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?s.map((e,t)=>t===i?{...e,status:"current"}:e):s,currentTier:o,keepRecentTokens:Cn.KEEP_RECENT_TOKENS}}function getPrimaryTip({percentage:e,conversationPct:t}){return e>=90?"Tier 3 auto-compact imminent — /compact now to control what gets summarized":e>=80?"Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in":t>60&&e>40?`${t}% is conversation — /compact to reclaim tokens`:e>=50?"/compact to free space · /model to switch models":null}function getSecondaryTip({mcpToolCount:e,imageCount:t,messageCount:n,percentage:r}){return e>0&&r>30?`${e} MCP tools loaded — disconnect unused servers to save tokens`:t>0&&r>30?`${t} image${t>1?"s":""} in context — images use ~1.5k tokens each`:n>50&&r>40?`${n} messages — consider starting a new session for a fresh context`:null}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:o,imageCount:s}){if(0===n)return[];const i=getPrimaryTip({percentage:e,conversationPct:Math.min(100,Math.round(t/n*100))}),a=getSecondaryTip({mcpToolCount:r,imageCount:s,messageCount:o,percentage:e}),l=[];return i&&l.push(i),a&&l.push(a),0===l.length&&l.push("/compact to summarize and free context · /model to switch models"),l}async function collectMemoryItems(){const e=(await discoverMemoryFiles(process.cwd())).filter(e=>e.exists),t=[];for(const n of e){const e=await loadMemoryFile(n.path),r=e?estimateTokens(e):0,o=process.env.HOME??"",s=o&&n.path.startsWith(o)?`~${n.path.slice(o.length)}`:n.path;t.push({name:n.description,tokens:r,source:s})}return t}function collectBuiltInTools(){const e=[];for(const t of T_){const n=JSON.stringify(t.input_schema??{}),r=estimateTokens(`${t.name} ${t.description??""} ${n}`);e.push({name:t.name,tokens:r})}for(const t of __){const n=estimateTokens(`${t.name} ${t.type}`);e.push({name:t.name,tokens:n})}return e}function collectMcpTools(){const e=getMcpConnectionManager().getConnectedServers(),t=[];for(const n of e)if("connected"===n.status)for(const e of n.tools){const r=JSON.stringify(e.inputSchema??{}),o=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:o,source:n.name})}return t}async function collectSkillItems(){const[e,{names:t}]=await Promise.all([loadAllSkillSummaries(),loadDisabledSkills()]);return deduplicateSkills({project:e.project.filter(e=>!t.has(e.name)),global:e.global.filter(e=>!t.has(e.name))}).map(e=>({name:e.name,tokens:estimateTokens(`${e.name} ${e.description}`)}))}async function collectAgentItems(){const e=await loadAllAgents(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.personal){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"user"})}return t}function sumTokens(e){let t=0;for(const n of e)t+=n.tokens;return t}async function analyzeContext({contextEngine:e}){const t=e.getContextTokensUsed(),n=e.getSystemPromptBreakdown(),r=getConfiguredModel(),o=getContextLimit(r),s=e.getHistory(),i=countMessagesByRole({messages:s}),a=countToolCalls({messages:s}),l=countImages({messages:s}),u=estimateConversationTokens({messages:s}),d=collectBuiltInTools(),m=collectMcpTools(),[g,h,f]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),y=sumTokens(d),w=sumTokens(m),S=sumTokens(g),E=sumTokens(h),v=sumTokens(f),C=t>0,k=n?n.memory:v,T=null!==n&&Math.abs(v-n.memory)>50,_=n?n.taste:0,x=y+w+S+E,A=C?t:u+x+k+_,P=!C&&s.length>0,I=Math.min(A/o*100,100),M=Math.max(0,o-A),R=[];if(A>0){const e=n?n.systemPrompt:Math.max(0,A-u-x-k-_);if(e>0&&R.push({name:uI,tokens:e,detail:n?"identity":"identity + taste"}),k>0&&R.push({name:"Memory",tokens:k,detail:T?"memory files (modified, refreshes next request)":"memory files"}),_>0&&R.push({name:"Taste",tokens:_,detail:"taste.md"}),y>0&&R.push({name:"System tools",tokens:y,detail:`${d.length} built-in`}),w>0){const e=Array.from(new Set(m.map(e=>e.source).filter(e=>"string"==typeof e)));let t=`${m.length} tools`;e.length>3&&(t=`${e.length} servers`),e.length>=1&&e.length<=3&&(t=e.join(", ")),R.push({name:"MCP",tokens:w,detail:t})}S>0&&R.push({name:"Skills",tokens:S,detail:`${g.length} loaded`}),E>0&&R.push({name:"Subagents",tokens:E,detail:`${h.length} loaded`});const r=e+k+_+x,o=C?Math.max(0,t-r):u;o>0&&R.push({name:dI,tokens:o,detail:`${i.user} user · ${i.assistant} assistant`})}R.sort((e,t)=>e.name===uI?-1:t.name===uI||e.name===dI?1:t.name===dI?-1:t.tokens-e.tokens);const N=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:A,tokenLimit:o,percentage:I,tokensRemaining:M,isEstimated:P,model:r,breakdown:R,autoCompact:buildAutoCompactStatus({tokensUsed:A,tokenLimit:o}),stats:{messageCount:s.length,userMessages:i.user,assistantMessages:i.assistant,toolCalls:a.calls,toolResults:a.results,imageCount:l,sessionStartTime:N},tips:generateTips({percentage:I,conversationTokens:u,totalTokens:A,mcpToolCount:m.length,messageCount:s.length,imageCount:l})}}function formatK(e){if(e<1e3)return String(e);if(e>=1e6){const t=Math.round(e/1e5)/10;return Number.isInteger(t)?`${t}M`:`${t.toFixed(1)}M`}const t=e/1e3;return Number.isInteger(t)?`${t}k`:`${t.toFixed(1)}k`}function formatBreakdownValue(e){return e<1e3?String(e):`${(e/1e3).toFixed(1)}k`}function getLayoutSizes({terminalWidth:e}){const t=Math.max(20,e),n=Math.min(50,Math.max(30,Math.floor(.5*t)));return{labelWidth:16,progressBarWidth:Math.max(10,Math.min(n,t-10)),showBreakdownDetail:t>=70}}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildBlockBar({percentage:e.percentage,width:t});return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:br.BLUE,color:"#f4f4f4",bold:!0},`${Lx}CONTEXT${Lx}`)),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.GRAY},getModelDisplayName(e.model))),re.createElement(Q,null,re.createElement(Y,{color:n},r.filled),re.createElement(Y,{color:Mr},r.empty),re.createElement(Y,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),re.createElement(Q,null,re.createElement(Y,null,formatK(e.tokensUsed)),re.createElement(Y,{color:br.GRAY},` / ${formatK(e.tokenLimit)}`),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:n},formatK(e.tokensRemaining)),re.createElement(Y,{color:br.GRAY}," remaining"),e.isEstimated&&re.createElement(Y,{color:br.DIM}," (estimated)")))}function CompactionDistance({analysis:e}){if(e.percentage<40)return null;const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const{tokensAway:n}=t;let r=br.GRAY;return n<=5e4&&(r=br.YELLOW),n<=2e4&&(r=br.RED),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:r},`~${formatK(n)}`),re.createElement(Y,{color:br.DIM}," until auto-compact"))}function BreakdownRow({item:e,labelWidth:t,numWidth:n,showDetail:r}){return re.createElement(Q,null,re.createElement(Y,null,e.name.padEnd(t)),re.createElement(Y,{bold:!0},formatBreakdownValue(e.tokens).padStart(n)),re.createElement(Y,{color:br.GRAY}," tokens"),r&&e.detail&&re.createElement(Y,{color:br.DIM},` · ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,showBreakdownDetail:n}){const r=e.breakdown.filter(e=>e.tokens>0);if(0===r.length)return null;const o=Math.max(4,...r.map(e=>formatBreakdownValue(e.tokens).length));return re.createElement(Q,{flexDirection:"column",marginTop:1},r.map(e=>re.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t,numWidth:o,showDetail:n})))}function ContextTips({tips:e}){return 0===e.length?null:re.createElement(Q,{flexDirection:"column",marginTop:1},e.map(e=>re.createElement(Q,{key:e},re.createElement(Y,{color:br.CYAN},Re.pointer),re.createElement(Y,{color:br.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return re.createElement(Q,{flexDirection:"column",paddingTop:1},re.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),re.createElement(CompactionDistance,{analysis:e}),re.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,showBreakdownDetail:t.showBreakdownDetail}),re.createElement(ContextTips,{tips:e.tips}))}function ContextConfigView({staticKey:e,contextEngineRef:t,onClose:n,setInput:r}){const[o,s]=se(null),[i,a]=se(null);return ae(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&s(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),Z((e,t)=>{t.escape&&(r(""),n())}),re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},i?re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Context"),re.createElement(Y,{color:br.DIM},i)):o?re.createElement(ContextMessage,{analysis:o}):re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Context"),re.createElement(Y,{color:br.DIM},"Loading context analysis...")),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Esc to return to conversation"))))}__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(getPrimaryTip,"getPrimaryTip"),__name(getSecondaryTip,"getSecondaryTip"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),Bt(),bo(),Vr(),__name(formatK,"formatK"),__name(formatBreakdownValue,"formatBreakdownValue"),__name(getLayoutSizes,"getLayoutSizes"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),Vr(),__name(ContextConfigView,"ContextConfigView"),Bt(),Bt(),_n(),ri(),QS(),Go(),Ro(),Co();var mI="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson().version,updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkAuthStatus(),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(){try{const e=await getSelectedModel(),t=getProviderDisplayName((await loadUserConfig()).provider||null);return{id:e,displayName:getModelDisplayName(e),provider:t}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}async function getSkillsAgentsStatus(){let e=0,t=0,n=0,r=0,o=0;try{const r=await loadAllSkillSummaries();e=r.global.length,t=r.project.length;const{names:o}=await loadDisabledSkills();n=[...r.global,...r.project].filter(e=>o.has(e.name)).length}catch{}try{const e=await loadAllAgents();r=e.personal.length,o=e.project.length}catch{}return{personalSkills:e,projectSkills:t,disabledSkills:n,personalAgents:r,projectAgents:o}}function execGitAsync(e){return new Promise(t=>{Te("git",e,{encoding:"utf8",cwd:process.cwd(),timeout:3e3},(e,n)=>{t(e?null:n.trim()||null)})})}async function getGitStatus2(){const e=await execGitAsync(["rev-parse","--abbrev-ref","HEAD"]);if(!e)return{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null};const[t,n]=await Promise.all([execGitAsync(["rev-parse","--show-toplevel"]),execGitAsync(["remote","get-url","origin"])]);return{branch:e,worktreePath:t,remoteUrl:n?formatRemoteUrl(n):null,remoteHttpUrl:n?buildHttpUrl(n):null}}function parseSSHUrl(e){const t=e.match(/@([^:]+):(.+?)(?:\.git)?$/);return t?.[1]&&t[2]?{host:t[1],path:t[2]}:null}function formatRemoteUrl(e){const t=parseSSHUrl(e);if(t)return t.path;const n=e.match(/\/\/[^/]+\/(.+?)(?:\.git)?$/);return n?.[1]?n[1]:e}function buildHttpUrl(e){const t=parseSSHUrl(e);if(t)return`https://${t.host}/${t.path}`;const n=e.match(/^ssh:\/\/[^@]+@([^/]+)\/(.+?)(?:\.git)?$/);return n?.[1]&&n[2]?`https://${n[1]}/${n[2]}`:/^https?:\/\//.test(e)?e.replace(/\.git$/,""):e}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}async function hasTasteMdFiles(e){if(!O(e))return!1;try{return(await I(e,{recursive:!0,encoding:"utf-8"})).some(e=>e.endsWith(".md"))}catch{return!1}}async function getTasteStatus(){const e=t.join(process.cwd(),".commandcode","taste"),n=t.join(e,"taste.md"),r=O(n),o=r||await hasTasteMdFiles(e);let s=!0;try{s=await isTasteLearningEnabled()}catch{}return{fileExists:o,filePath:r?n:e,learningEnabled:s}}function detectProxy(){const e=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy;return e?sanitizeProxyUrl(e):null}function sanitizeProxyUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString().replace(/\/$/,"")}catch{return"[malformed proxy URL]"}}function getSystemStatus(){let e,t,n,r;try{e=nA(S.platform()),t=wA(),n=SA(),r=bA()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:S.arch(),shell:n,terminal:t,nodeVersion:process.version,ide:"N/A"!==r?r:null,proxy:detectProxy()}}async function gatherStatusData(){const e=safeSync(getVersionStatus,{current:"Unknown",updateAvailable:null}),t=safeSync(getSystemStatus,{cwd:process.cwd(),os:"Unknown",arch:S.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,o,s,i]=await Promise.all([safeAsync(getAuthStatus,{authenticated:!1,username:null}),safeAsync(getModelStatus,{id:"Unknown",displayName:"Unknown",provider:"Unknown"}),safeAsync(getTasteStatus,{fileExists:!1,filePath:"",learningEnabled:!1}),safeAsync(getSkillsAgentsStatus,{personalSkills:0,projectSkills:0,disabledSkills:0,personalAgents:0,projectAgents:0}),safeAsync(getGitStatus2,{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null})]),a=safeSync(()=>getPrStatus(i.branch),null);return{version:e,auth:n,model:r,git:i,pr:a,taste:o,skillsAgents:s,system:t}}function safeSync(e,t){try{return e()}catch{return t}}async function safeAsync(e,t){try{return await e()}catch{return t}}function formatCountValue(e,t){const n=e+t;return 0===n?"None":`${n} (${e} user, ${t} project)`}function formatSkillsValue(e){const{personal:t,project:n,disabled:r}=e,o=t+n;return 0===o?"None":0===r?formatCountValue(t,n):`${o-r} active · ${r} off · (${t} user, ${n} project installed)`}function formatSystemValue({system:e}){const t=[`${e.os} ${e.arch}`];return e.ide&&t.push(e.ide),!e.terminal||e.ide&&e.ide.toLowerCase().startsWith(e.terminal.toLowerCase())||t.push(e.terminal),t.push(e.shell),t.push(`Node ${e.nodeVersion}`),t.join(" · ")}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getSkillsAgentsStatus,"getSkillsAgentsStatus"),__name(execGitAsync,"execGitAsync"),__name(getGitStatus2,"getGitStatus"),__name(parseSSHUrl,"parseSSHUrl"),__name(formatRemoteUrl,"formatRemoteUrl"),__name(buildHttpUrl,"buildHttpUrl"),__name(getPrStatus,"getPrStatus"),__name(hasTasteMdFiles,"hasTasteMdFiles"),__name(getTasteStatus,"getTasteStatus"),__name(detectProxy,"detectProxy"),__name(sanitizeProxyUrl,"sanitizeProxyUrl"),__name(getSystemStatus,"getSystemStatus"),__name(gatherStatusData,"gatherStatusData"),__name(safeSync,"safeSync"),__name(safeAsync,"safeAsync"),Bt(),_n(),dv(),Vr(),ko(),__name(formatCountValue,"formatCountValue"),__name(formatSkillsValue,"formatSkillsValue"),__name(formatSystemValue,"formatSystemValue");var pI=__name(({label:e,value:t,valueColor:n,dimValue:r})=>re.createElement(Q,null,re.createElement(Y,{dimColor:!0},`${e}:`.padEnd(14)),r?re.createElement(Y,{dimColor:!0},t):re.createElement(Y,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=e,n=t.version.updateAvailable?`v${t.version.current} → v${t.version.updateAvailable} available`:`v${t.version.current}`,r=`${t.model.provider} · ${t.model.displayName}`,o=t.git.branch||"N/A",s=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?Re.tick:Re.cross,a=t.auth.authenticated?br.WHITE:Pr.ERROR,l=t.skillsAgents.personalSkills+t.skillsAgents.projectSkills,u=t.skillsAgents.personalAgents+t.skillsAgents.projectAgents,d=t.taste.fileExists?"Active · "+(t.taste.learningEnabled?"Learning on":"Learning off"):"No taste.md";return re.createElement(Q,{flexDirection:"column",paddingX:0},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Command Code"," "),re.createElement(Y,{dimColor:!0},n)),re.createElement(Q,null,re.createElement(Y,{dimColor:!0},"Visit "),re.createElement(Eo,{url:mI,text:mI,color:br.CYAN}),re.createElement(Y,{dimColor:!0}," for usage and billing")),re.createElement(Q,{marginTop:1},re.createElement(Y,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?re.createElement(re.Fragment,null,re.createElement(Eo,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:br.CYAN}),re.createElement(Y,{color:a}," ",i)):t.auth.authenticated?re.createElement(re.Fragment,null,re.createElement(Y,null,"Authenticated"),re.createElement(Y,{color:a}," ",i)):re.createElement(re.Fragment,null,re.createElement(Y,{color:Pr.WARNING},"Not signed in"),re.createElement(Y,{color:a}," ",i),re.createElement(Y,{dimColor:!0}," — run "),re.createElement(Y,{bold:!0},"/login"))),re.createElement(pI,{label:"Model",value:r}),re.createElement(pI,{label:"Branch",value:o,dimValue:!t.git.branch}),s?re.createElement(pI,{label:"Worktree",value:s}):null,t.git.remoteUrl?re.createElement(Q,null,re.createElement(Y,{dimColor:!0},"Repository:".padEnd(14)),re.createElement(Eo,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:br.CYAN}),t.pr?re.createElement(re.Fragment,null,re.createElement(Y,{dimColor:!0}," · "),re.createElement(Eo,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?br.CYAN:br.GRAY}),re.createElement(Y,{dimColor:!0}," ","(",t.pr.state.toLowerCase(),")")):null):t.pr?re.createElement(Q,null,re.createElement(Y,{dimColor:!0},"Pull Request:".padEnd(14)),re.createElement(Eo,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?br.CYAN:br.GRAY}),re.createElement(Y,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,re.createElement(pI,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),re.createElement(pI,{label:"Directory",value:toRelativePath(t.system.cwd)}),re.createElement(pI,{label:"Skills",value:formatSkillsValue({personal:t.skillsAgents.personalSkills,project:t.skillsAgents.projectSkills,disabled:t.skillsAgents.disabledSkills}),dimValue:0===l}),re.createElement(pI,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),re.createElement(pI,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?re.createElement(pI,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,onClose:t,setInput:n}){const[r,o]=se({phase:"loading"});return ae(()=>{let e=!1;return gatherStatusData().then(t=>{e||o({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";o({phase:"error",message:n})}),()=>{e=!0}},[]),Z((e,r)=>{r.escape&&(n(""),t())}),re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},"ready"===r.phase?re.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?re.createElement(Y,{dimColor:!0},"Could not load status: ",r.message):re.createElement(Y,{dimColor:!0},"Gathering status…"),re.createElement(Q,{marginTop:1},re.createElement(Y,{dimColor:!0},"Press Esc to return to conversation"))))}function moveFocusDown(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?n>0?{...e,zone:"suggestions",suggestionIndex:0}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:e:"suggestions"===e.zone?e.suggestionIndex<n-1?{...e,suggestionIndex:e.suggestionIndex+1}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:{...e,zone:"input"}:e.activeDirIndex<r-1?{...e,activeDirIndex:e.activeDirIndex+1}:{...e,zone:"input"}}function moveFocusUp(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?r>0?{...e,zone:"active-dir",activeDirIndex:r-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:e:"suggestions"===e.zone?e.suggestionIndex>0?{...e,suggestionIndex:e.suggestionIndex-1}:{...e,zone:"input"}:e.activeDirIndex>0?{...e,activeDirIndex:e.activeDirIndex-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:{...e,zone:"input"}}function getAdjustedSuggestionOffset(e){const{selectedIndex:t,currentOffset:n,maxVisible:r,totalSuggestions:o}=e;return o<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),o=e.replace(/\\/g,"/");if(o.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${o.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:o};const s=o.lastIndexOf("/");return-1===s?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:o.slice(0,s+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),o=n.startsWith(".")||r.includes("/.");return D.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!o||!e.name.startsWith(".")).filter(e=>!n||e.name.toLowerCase().startsWith(n.toLowerCase())).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>`${r}${e.name}/`)}catch(e){const t=e.code;return"ENOENT"!==t&&"ENOTDIR"!==t&&console.error(`Warning: Could not list directory suggestions: ${t}`),[]}}function getFooterText(e){return"active-dir"===e.focusZone?"[Del] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}__name(StatusMessage,"StatusMessage"),__name(StatusConfigView,"StatusConfigView"),Bt(),Bt(),Xo(),Bt(),Xo(),__name(function createInitialFocusState(){return{zone:"input",suggestionIndex:0,activeDirIndex:0}},"createInitialFocusState"),__name(moveFocusDown,"moveFocusDown"),__name(moveFocusUp,"moveFocusUp"),__name(getAdjustedSuggestionOffset,"getAdjustedSuggestionOffset"),__name(getSuggestionBase,"getSuggestionBase"),__name(getDirectorySuggestions,"getDirectorySuggestions"),__name(getFooterText,"getFooterText"),Vr(),Xr();var gI=__name(({onClose:e})=>{const[t,n]=se(""),[r,o]=se(null),[s,i]=se([]),[a,l]=se(getAdditionalDirectories()),[u,d]=se({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=se(0);ae(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),ae(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),f=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());o({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");Z((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&s[u.suggestionIndex]?void h(s[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[u.activeDirIndex]);else{if(r.tab&&s.length>0){const e=s[u.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),ae(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,s.length]),ae(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=s.length?{...e,zone:"input",suggestionIndex:Math.max(0,s.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[s.length,a.length]);const y=s.slice(m,m+8),w=getFooterText({focusZone:u.zone});return re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:br.CYAN,paddingX:1,paddingY:0},re.createElement(Y,{bold:!0,color:br.CYAN},"Add directory to workspace"),re.createElement(Y,{color:br.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.GRAY},"Added directories"),0===a.length?re.createElement(Y,{color:br.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return re.createElement(Y,{key:e,color:n?br.YELLOW:br.GREEN,bold:n&&isLightTheme()},n?` ${Re.pointer} `:" ",formatDirectoryForDisplay(e))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0,color:br.WHITE},"Path")),re.createElement(Q,null,re.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?Re.pointer:" "} `,prefixColor:"input"===u.zone?br.CYAN:br.GRAY,onChange:e=>{n(e),o(null)},onSubmit:h})),!t&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:{error:br.RED,warning:br.YELLOW,success:br.GREEN}[r.tone]},r.text)),s.length>0&&re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:br.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return re.createElement(Y,{key:e,color:r?br.CYAN:br.GRAY,bold:r&&isLightTheme()},r?` ${Re.pointer} `:" ",e)})),re.createElement(Q,{marginTop:1},re.createElement(BracketedText,{text:w,color:br.DIM})))},"AddDirModal");Bt(),Bt(),_n(),Bt(),Bt(),_n(),Vr();var hI=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),fI=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),yI=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=se("idle"),[i,a]=se(""),l=[...T_.map(e=>e.name),...__.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void a("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?hI():fI();await k.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),i=Array.from(e.selectedTools).map(e=>P_[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await k.writeFile(s,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>P_[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Name:"),re.createElement(Y,{color:br.GRAY},e.agentType)),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Location:"),re.createElement(Y,{color:br.GRAY},m)),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Tools:"),re.createElement(Y,{color:br.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Description"),re.createElement(Y,{color:br.GRAY},"(Tells ","Command Code"," when to use this agent):")),re.createElement(Y,{color:br.GRAY},e.ccToolDefinition),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"System Prompt:")),re.createElement(Y,{color:br.GRAY},e.sysPrompt),!r&&re.createElement(Q,{marginTop:1},"idle"===o&&re.createElement(Q,{gap:1},re.createElement(Y,{color:br.GREEN,dimColor:!0},"Press"),re.createElement(Y,{color:br.GREEN,bold:!0},"Enter"),re.createElement(Y,{color:br.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===o&&re.createElement(Y,{color:br.YELLOW},"Saving agent..."),"saved"===o&&re.createElement(Y,{color:br.GREEN},Re.tick," ",i),"error"===o&&re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.RED},Re.cross," Error: ",i),re.createElement(Y,{color:br.GRAY},"Press Enter to retry"))))},"AgentSummary");Vr();var wI=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=se("menu"),i=[...T_.map(e=>e.name),...__.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>I_[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect"),m=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],g=__name(async r=>{if("confirm-delete"===r.value)try{await k.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return Z((e,n)=>{if(n.escape)"menu"===o?t():s("menu");else if(n.return&&"view"===o)s("menu");else if(1===e.length&&e>="1"&&e<="9"){const t=Number(e)-1;if("menu"===o){const e=u[t];e&&d(e)}else if("delete"===o){const e=m[t];e&&g(e)}}}),"view"===o?re.createElement(Q,{flexDirection:"column"},re.createElement(yI,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},"Press Enter to go back"))):"edit"===o?re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.YELLOW},"Edit functionality coming soon..."),re.createElement(Y,{color:br.GRAY},"Press Esc to go back")):"delete"===o?re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.RED},"Delete agent"),re.createElement(Y,{color:br.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),re.createElement(Q,null,re.createElement(ft,{items:m,onSelect:g,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e},` ${t} `)}))):re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE,bold:!0},e.name),re.createElement(Q,{marginTop:1},re.createElement(ft,{items:u,onSelect:d,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e},` ${t} `)})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");Vr();var SI=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=se([]),[s,i]=se([]),[a,l]=se([]),[u,d]=se(!0),[m,g]=se(!1),[h,f]=se(null),[y,w]=se(!1),[E,v]=se(0),[C,T]=se(0),_=useTerminalHeight(),x=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),A=__name(async(e,n)=>{try{g(!1);const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=qe(s);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");ae(()=>{__name(async()=>{d(!0);const[e,...t]=await Promise.all([A(x(),"personal"),...getProjectAgentDirs().map(e=>A(e,"project"))]),n=new Set,r=[];for(const e of t.flat())n.has(e.name)||(n.add(e.name),r.push(e));const s=ZT.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));o(e),i(r),l(s),d(!1)},"loadAgents")()},[m]);const P=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{P.push({label:e.name,value:e.filePath})}),s.forEach(e=>{P.push({label:e.name,value:e.filePath})});const I=r.length+s.length,M=(r.length>0?1:0)+(s.length>0?1:0),R=__name(e=>0===e?"action":e<=r.length?"user":"project","sectionOf"),N=_-1,L=Math.max(4,N-11-a.length-2*M),$=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(f(e),w(!0))}},"handleAgentSelect");if(Z((e,t)=>{if(t.upArrow)v(e=>Math.max(0,e-1));else if(t.downArrow)v(e=>Math.min(P.length-1,e+1));else if(t.return){const e=P[E];e&&$(e)}},{isActive:!u&&!y}),ae(()=>{v(e=>Math.min(e,Math.max(0,P.length-1)))},[P.length]),ae(()=>{T(e=>clampScrollOffset({cursor:E,total:P.length,maxVisible:L,currentOffset:e}))},[E,P.length,L]),u)return re.createElement(Y,{color:br.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return re.createElement(wI,{agent:h,onBack:()=>{w(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const D=C,O=C+L,F=P.slice(D,O),j=P.length>L;let U=null;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Agents"),I>0?re.createElement(Y,{color:br.GRAY}," ","(",I," agent",I>1?"s":"",")"):re.createElement(Y,{color:br.GRAY}," (No custom agents)")),n&&re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{color:br.GREEN,dimColor:!0},"Created agent: ",n)),re.createElement(Q,{flexDirection:"column"},F.map((e,t)=>{const n=D+t,r=R(n),o="action"!==r&&r!==U;U=r;const s=n===E,i="user"===r?"User agents":"Project agents";return re.createElement(re.Fragment,{key:e.value},o&&re.createElement(Q,{marginTop:0===t?0:1},re.createElement(Y,{color:Mr,bold:!0},i)),re.createElement(Q,null,re.createElement(Y,{color:s?br.WHITE:br.GRAY,backgroundColor:s?zr:void 0,bold:s},e.label," ")))})),j&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",D+1,"–",Math.min(O,P.length)," of ",P.length,D>0?" · ↑ more":"",O<P.length?" · ↓ more":"")),a.length>0&&re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:Mr,bold:!0},"Default agents"),a.map(e=>re.createElement(Y,{key:e.filePath,color:br.DIM},e.name.charAt(0).toUpperCase()+e.name.slice(1)))),re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:br.DIM},"Create specialized subagents that Command Code can delegate to."),re.createElement(Y,{color:br.DIM},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Bt(),_n(),li(),Vr(),Bt(),Bt(),_n(),Vr();var bI=__name(({onSelect:e})=>re.createElement(ft,{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})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},` ${t}`)}),"LocationSelector");Bt(),Xr(),_n(),so(),Qr(),Vr();var EI=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=se(!1),[g,h]=se(!1),f=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),y=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(P_).some(e=>ze(e)===ze(t))||Object.keys(P_).some(e=>ze(e)===ze(t)))&&re.createElement(Y,{color:br.RED},Re.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(ze(t))&&re.createElement(Y,{color:br.RED},Re.warning," This name is reserved. Reserved names: ",XT.join(", "))),re.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=ze(t);Object.values(P_).some(t=>ze(t)===e)||Object.keys(P_).some(t=>ze(t)===e)||isReservedAgentName(e)||a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE},"Enter the system prompt for your agent:"),re.createElement(Y,{color:br.GRAY},"Be comprehensive for best results.")),re.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?re.createElement(re.Fragment,null,re.createElement(Y,{color:br.WHITE},"When should ","Command Code"," use this agent?"),re.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Bt(),Vr();var vI=__name(({onSelect:e})=>re.createElement(ft,{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})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},` ${t}`)}),"MethodSelector");Bt(),Xr(),Bt(),gC(),Vr();var CI=["·","○","◇","☆","✧","☆","◇","○","⌘"],kI=[12,5,4,4,4,4,4,5,16],TI=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<kI.length;e++)if(n+=kI[e],t<n)return CI[e];const r=t-58;n=0;for(let e=0;e<TI.length;e++)if(n+=TI[e],r<n)return CI[7-e];return CI[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=le(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<jr.length?jr[n]:Ur},"getCharColor");return re.createElement(Y,null,r.map((e,t)=>re.createElement(Y,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return re.createElement(Y,{color:t??Er,bold:!0},`${getWaveSymbol(e)} `)}function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var _I=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=se(0),[s,i]=se(0),a=ie(n);a.current=n;const l=getTerminalWidth(),[u,d]=se(()=>l>=72?"all":l>=42?"medium":"none");ae(()=>{d(e=>"all"===e?l<68?l>=42?"medium":"none":"all":"medium"===e?l>=72?"all":l<38?"none":"medium":l>=72?"all":l>=42?"medium":"none")},[l]),ae(()=>{const e=setInterval(()=>{o(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const m=r%(e.length+10),g="all"===u,h="medium"===u;return aC.statusRender({width:l,layoutMode:u,status:e,frame:r}),re.createElement(Q,{width:l,height:1,paddingLeft:0,marginLeft:0},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:xr.BG,color:xr.FG}," "),re.createElement(Y,{backgroundColor:xr.BG},re.createElement(CMDIcon,{frame:4*r,color:xr.FG})),re.createElement(ShimmerText,{text:e,offset:m,bg:xr.BG}),re.createElement(Y,{backgroundColor:xr.BG,color:xr.FG}," ")),g&&re.createElement(Q,{columnGap:1,marginLeft:1},re.createElement(Y,{bold:!0,color:br.GRAY},"esc"),re.createElement(Y,{color:br.DIM},"to interrupt"),re.createElement(Y,{color:br.DIM},"•"),re.createElement(Y,{color:br.DIM},formatTime3(t)),re.createElement(Y,{color:br.DIM},"•"),re.createElement(Y,{color:br.GRAY},Re.arrowDown),re.createElement(Y,{color:br.DIM},formatToken(Math.round(s)))),h&&re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM},formatToken(Math.round(s)))))},"Status");Qr(),so(),Vr();var xI=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=se(!1),[a,l]=se(0),[u,d]=se(0);ae(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=ce(()=>{0!==e.trim().length&&n()},[e,n]),g=ce(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return re.createElement(Q,{flexDirection:"column"},r?re.createElement(Q,null,re.createElement(CMDIcon,{frame:u}),re.createElement(Y,{color:br.WHITE},"Generating agent from description...")):re.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),o&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.RED},`${Re.warning} ${o}`)))},"RecommendedFlow");Bt(),Vr();var AI=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=se(!1),[i,a]=se(0),[l,u]=se(0),d=useTerminalHeight(),m=le(()=>[...T_.map(e=>e.name),...__.map(e=>e.name)],[]),g=le(()=>[{name:"All tools",tools:m},{name:"Read-only tools",tools:m.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:m.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:m.filter(e=>"shell_command"===e)},{name:"Search tools",tools:m.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:m.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),[m]),h=le(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(g.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:"}),m.forEach(t=>{e.push({type:"tool",value:t})})):(g.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,g,e,m]),f=h.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=g.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]":"[ ]"} ${P_[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),y=f.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type),w=Math.max(5,d-1-10),S=y[i]?.value??0;ae(()=>{u(e=>clampScrollOffset({cursor:S,total:f.length,maxVisible:w,currentOffset:e}))},[S,f.length,w]);const E=l,v=l+w,C=f.slice(E,v),k=f.length>w;return Z((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?y.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=y.length?0:t});else if(l.return||" "===e){const e=y[i];if(e){const i=h[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(s(!o),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),re.createElement(Q,{flexDirection:"column"},C.map(e=>{const t=y.findIndex(t=>t.value===e.value),n=-1!==t&&t===i;if("divider"===e.type)return re.createElement(Q,{key:`divider-${e.value}`},re.createElement(Y,{color:br.GRAY}," ",e.label));if("spacer"===e.type)return re.createElement(Q,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return re.createElement(Q,{key:`label-${e.value}`},re.createElement(Y,{color:br.GRAY}," ",e.label));const r="continue"===e.type;return re.createElement(Q,{key:`item-${e.value}`},re.createElement(Y,{color:n?br.WHITE:br.GRAY,bold:r&&n},n?">":" "," ",e.label))}),k&&re.createElement(Q,null,re.createElement(Y,{color:br.GRAY}," ","Showing ",E+1,"–",Math.min(v,f.length)," of"," ",f.length,E>0?" · ↑ more":"",v<f.length?" · ↓ more":"")),re.createElement(Q,{marginTop:1},e.size===m.length&&re.createElement(Y,{color:br.GRAY},"All tools selected"),e.size>0&&e.size<m.length&&re.createElement(Y,{color:br.GRAY},e.size," tools selected"),0===e.size&&re.createElement(Y,{color:br.GRAY},"No tools selected")))},"ToolsSelector");No(),VS(),LS(),oi(),xC(),Co();var PI=__name(({onComplete:e})=>{const[t,n]=se("location"),[r,o]=se(!1),[s,i]=se(null),[a,l]=se("agentType"),u=le(()=>[...T_.map(e=>e.name),...__.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=se(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[Wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[Wt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(a[Wt.OAUTH_PROVIDER]=s));const l=getApiBaseUrl(),u=new hS({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:Gt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:ze(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof Vs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:ze(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),v=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),C=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE,bold:!0},"Create new agent"),re.createElement(Y,{color:br.GRAY},f())),re.createElement(Q,null,"location"===t&&re.createElement(bI,{onSelect:y}),"method"===t&&re.createElement(vI,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&re.createElement(xI,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:S}),"configuration"===t&&"manual"===m.method&&re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(EI,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:v,onCCToolDefinitionSubmit:C})),"tools"===t&&re.createElement(AI,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&re.createElement(yI,{config:m,onSaveComplete:h})))},"AgentNew"),II=__name(({onCancel:e})=>{const[t,n]=se(null),[r,o]=se(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),re.createElement(Q,{width:"100%",flexDirection:"column"},null===t&&re.createElement(SI,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&re.createElement(PI,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");Vr(),Bt(),Co(),Vr();var MI=[{label:"Compact Normal (default)",value:"default",description:"Summarize session when context limit reached."},{label:"Compact Fast",value:"fast",description:"Fast tiered compaction. Higher quality, uses more tokens."}],RI=__name(({onSelect:e,onCancel:t})=>{const[n,r]=se(null);ae(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(Z((e,n)=>{n.escape&&t()}),null===n)return null;const s=MI.findIndex(e=>e.value===n);return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Select a compact mode to compact sessions")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Choose how Command Code handles automatic context compaction.")),re.createElement(ft,{items:MI,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>{const r=MI.find(e=>e.label===t),o=r?.value===n,s=MI.findIndex(e=>e.label===t),i=e?zr:void 0;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:e||!o?br.WHITE:br.GREEN,backgroundColor:i,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&re.createElement(Y,{color:br.GREEN}," ",Re.tick)),re.createElement(Y,{color:e?br.WHITE:br.DIM,backgroundColor:i},` ${r?.description??""} `))}}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to cancel")))},"CompactModeSelector");Bt(),_n(),bo(),Ro(),Co(),Po(),Bt(),_n(),Vr();var NI=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0})=>{const i=Sn[t],a=o??i?.showProviderLabelInSelector??!1,l=e.vendorLabel??yn[e.provider],u=s&&e.id===fn,d="free"===e.badge,m=u?`${e.label} (default)`:e.label,g=d?" (FREE)":"",h=" ".repeat(Math.max(0,32-m.length-g.length)),f=n?zr:void 0,y=e.description?`${a?`${l} · `:""}${e.description}`:"",w=useTerminalWidth()>=70&&y;return re.createElement(Q,null,re.createElement(Y,{backgroundColor:f,color:r?br.GREEN:br.WHITE,bold:r},m),d&&re.createElement(Y,{backgroundColor:f,color:br.GREEN,bold:!0},g),w&&re.createElement(re.Fragment,null,re.createElement(Y,{backgroundColor:f},h),re.createElement(Y,{backgroundColor:f,color:br.DIM},y)),re.createElement(Y,{backgroundColor:f,color:br.GREEN},r?` ${Re.tick} `:" "))},"ModelRow");Vr();var LI=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,LI);e.length>0&&n.push({...r,models:e})}return n}function groupByModelProvider(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups,"searchGroups"),__name(groupByModelProvider,"groupByModelProvider");var $I=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,onPick:r,onBack:o})=>{const[s,i]=se(""),a=le(()=>isInternalTeamFlagEnforced(),[]),[l,u]=se(()=>getCachedBillingContext());ae(()=>{if(l)return;let e=!0;return getBillingContext().then(t=>{e&&u(t)}),()=>{e=!1}},[l]);const d=null!==l,m=le(()=>a?bn:groupByModelProvider(En.flatMap(e=>e.models),Sn["command-code"].id),[a]),g=le(()=>l?m.map(e=>({...e,models:e.models.filter(e=>checkModelAccess({model:{id:e.id,provider:e.provider,name:e.name},planId:l.planId,purchasedCredits:l.purchasedCredits,freeCredits:l.freeCredits}).allowed)})).filter(e=>e.models.length>0):[],[m,l]),h=le(()=>searchGroups(g,s),[g,s]),f=le(()=>{const e=[];for(const t of h)for(const n of t.models)e.push({kind:"model",providerId:t.providerId,model:n});return[{kind:"reset"},...e]},[h]),y=le(()=>{if(!n)return 0;const e=f.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[f,n]),{cursor:w}=useListNavigation({items:f,initialIndex:y,searchCursorIndex:1,searchQuery:s,onSearchChange:i,onSelect:__name(e=>{d&&r("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:o}),[S,E]=se(0),v=useTerminalHeight()-1,C=Math.max(4,v-11-2*h.length);ae(()=>{E(e=>clampScrollOffset({cursor:w,total:f.length,maxVisible:C,currentOffset:e}))},[w,f.length,C]);const k=S,T=S+C,_=0===k;let x=1;const A=h.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:x,windowStart:k,windowEnd:T});return x+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),P=f.length>C;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},e," › select model")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{dimColor:!0},"Pick a model for this task, or reset it to the default.")),isCmdZdrEnabled()&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.YELLOW},"Your pick is saved but stays paused until CMD_ZDR is unset.")),re.createElement(Q,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(QP,{query:s,resultCount:s?f.length-1:void 0,placeholder:"Type to search models..."})),d?re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},_&&re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{bold:!0,dimColor:!0},"Default"),re.createElement(Q,null,re.createElement(Y,{backgroundColor:0===w?zr:void 0,color:n?br.WHITE:br.GREEN},t," "),!n&&re.createElement(Y,{color:br.GREEN},Re.tick))),A.map(({group:e,groupWindow:t},r)=>re.createElement(Q,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||_?1:0},re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(NI,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===w,isCurrent:r.id===n,showProviderLabel:!!a&&void 0,showDefaultBadge:!1}))))),P&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",k+1,"–",Math.min(T,f.length)," of"," ",f.length,k>0?" · ↑ more":"",T<f.length?" · ↓ more":""))):re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Loading available models…")),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"type to search · ↑/↓ navigate · enter select"),s?re.createElement(Y,{color:br.DIM}," · esc to clear"):re.createElement(Y,{color:br.DIM}," · esc back")))},"FeatureModelPicker");function sanitizeFeatureOverrides(e){const t={};for(const{key:n}of a_){const r=e?.[n];"string"==typeof r&&r&&(t[n]=r)}return t}__name(sanitizeFeatureOverrides,"sanitizeFeatureOverrides");var DI=__name(({onClose:e})=>{const[t,n]=se(null),[r,o]=se(null),[s,i]=se(null);ae(()=>{loadUserConfig().then(e=>{n(sanitizeFeatureOverrides(e.featureModels))})},[]);const a=r?"picker":"list",{cursor:l}=useListNavigation({items:a_,initialIndex:0,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:"list"===a&&null!==t,onSelect:__name(e=>{i(null),o(e.key)},"onSelect"),onCancel:e,onReset:__name(async e=>{try{await setFeatureModel({feature:e.key,model:void 0}),n(t=>{const n={...t??{}};return delete n[e.key],n}),i({text:`${e.label} reset to default`})}catch{i({text:`Couldn't reset ${e.label} — try again`,error:!0})}},"onReset")});if(null===t)return null;const u=a_.find(e=>e.key===r)??null;if("picker"===a&&u)return re.createElement($I,{featureLabel:u.label,defaultLabel:getFeatureDefaultLabel(u),currentModelId:t[u.key],onBack:()=>o(null),onPick:async e=>{try{await setFeatureModel({feature:u.key,model:e}),n(t=>{const n={...t??{}};return void 0===e?delete n[u.key]:n[u.key]=e,n}),i({text:void 0===e?`${u.label} reset to default`:`${u.label} → ${getModelDisplayName(e)}`})}catch{i({text:`Couldn't save ${u.label} — try again`,error:!0})}o(null)}});const d=isCmdZdrEnabled();return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Configure models")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Pick a model for each task. Applies to all sessions."," ",createOSC8Link("https://commandcode.ai/docs/troubleshooting/faqs#why-do-i-see-small-background-requests","Why background requests?",!1))),d&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.YELLOW},"Model overrides were reverted to ZDR safe defaults. Your overrides will be restored when CMD_ZDR is unset.")),a_.map((e,n)=>{const r=t[e.key],o=e.defaultLabel?`Default (${getFeatureDefaultLabel(e)})`:`Uses current model (${getFeatureDefaultLabel(e)})`,s=r?getModelDisplayName(r):null,i=!!r&&!d,a=i&&s?s:o,u=n===l;return re.createElement(Q,{key:e.key},re.createElement(Y,{backgroundColor:u?zr:void 0,color:br.WHITE},e.label.padEnd(20)),re.createElement(Y,{backgroundColor:u?zr:void 0},re.createElement(Y,{color:i?br.GREEN:br.DIM},a),s&&d&&re.createElement(Y,{color:br.DIM},` · ${s} paused`)))}),s&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:s.error?br.RED:br.GREEN},s.text)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑/↓ navigate · enter to change · r to reset · esc to close")))},"ConfigureModelsSelector");function settingsFilePaths(e){return[getProjectLocalPath(e),getProjectSharedPath(e),getUserSettingsPath()]}function readInputSettings(e){try{const t=$.readFileSync(e,"utf-8");return parseJSON(t)?.input}catch{return}}function shouldCollapsePastedText(e=process.cwd()){for(const t of settingsFilePaths(e)){const e=readInputSettings(t)?.collapsePastedText;if("boolean"==typeof e)return e}return!0}Bt(),Vr(),Bt(),Xr(),_n(),so(),Bt(),No(),__name(settingsFilePaths,"settingsFilePaths"),__name(readInputSettings,"readInputSettings"),__name(shouldCollapsePastedText,"shouldCollapsePastedText"),Yn(),Bt();var OI=n(E(),"commandcode-images"),FI={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{O(OI)||B(OI,{recursive:!0});const r=FI[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(OI,o),i=Buffer.from(e.data,"base64");return q(s,i),s}catch{return null}}function stripInputAfterSuffix(e,t){return t&&e.endsWith(t)?e.slice(0,e.length-t.length):e}function extractAppendedChunk(e,t,n){const r=t+n;return e.length>=r.length&&e.startsWith(r)?e.slice(r.length):null}function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedContent:n,setInput:r,setDetectedImages:o,setDetectedContent:s,incrementInputKey:i,setInitialCursor:a,collapsePastedText:l=!0}=e,u=ce((e,t,n="")=>{o(t=>[...t,e]),r(t+n),a(t.length),i()},[o,r,a,i]),d=ie(!1),m=ie(""),g=ie(null),h=ie(""),f=ie(""),y=ce(async(e,t,n)=>{let o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const d=await detectDroppedImageFile(o);if(d)return void u(d,t,n);const m=await detectClipboardImage();if(m)return void u(m,t,n);let g=o;if(0===g.length){const e=await detectClipboardText();g=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(!g&&!n)return;if(!g)return r(t+n),a(t.length),void i();if(l&&g.length>300){const e=t+pastedTextToken(g);return s(e=>[...e,g]),r(e+n),a(e.length),void i()}const h=t+g;r(h+n),a(h.length),i()},[u,n.length,s,r,a,i,l]),w=ce(()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(async()=>{if(d.current){const e=m.current,t=h.current,n=f.current;m.current="",h.current="",f.current="",d.current=!1,g.current=null,e?await y(e,t,n):n&&await y("",t,n)}},500)},[y]);return{handlePaste:ce(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return d.current&&(d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)),await y(n.pastedContent??n.cleanedContent,n.textBeforePaste??"",n.textAfterPaste??""),!0;if(n.isPasteStart&&!d.current){d.current=!0;const e=n.textBeforePaste??t,r=t.slice(e.length);h.current=e,f.current=r;const o=n.pastedContent??n.cleanedContent;return m.current=stripInputAfterSuffix(o,r),w(),!0}if(d.current&&!n.isPasteEnd){const e=h.current,t=f.current;if(void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(n.cleanedContent){const r=extractAppendedChunk(n.cleanedContent,e,t);m.current=null!==r?m.current+r:accumulateDelta(n.cleanedContent,m.current,e)}return w(),!0}if(d.current&&n.isPasteEnd){g.current&&(clearTimeout(g.current),g.current=null);const e=h.current,t=f.current,r=n.textAfterPaste??"";let o=n.cleanedContent??"";if(r&&o.endsWith(r)&&(o=o.slice(0,o.length-r.length)),void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(o){const n=extractAppendedChunk(o,e,t);m.current=null!==n?m.current+n:accumulateDelta(o,m.current,e)}const s=m.current,i=e,a=r||t;return m.current="",h.current="",f.current="",d.current=!1,await y(s,i,a),!0}if(n.isPasteEnd&&!n.isPasteStart&&!d.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return u(e,t),!0}return!1},[t,y,w,u]),resetPasteState:ce(()=>{d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)},[]),isPasting:ce(()=>d.current,[])}}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=se(!1),[l,u]=se(null),d=ce(async()=>{if(!i){a(!0),u(null);try{let i=e.replace(/\n+$/,"");r.forEach(e=>{const t=pastedTextToken(e);i.includes(t)&&(i=i.replace(t,e))});const a=await openInEditor2(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){u(e instanceof Gx?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{a(!1)}}},[e,t,n,r,o,s,i]),m=ce(()=>{u(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:m}}__name(saveTempImage,"saveTempImage"),gr(),No(),Bt(),Qr(),so(),__name(stripInputAfterSuffix,"stripInputAfterSuffix"),__name(extractAppendedChunk,"extractAppendedChunk"),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),Qr(),Bt(),Qr(),__name(useExternalEditor,"useExternalEditor"),Bt();var jI=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=se(null),o=ie(!1);return ae(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,zx().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");Vr(),Bt(),Bt();var UI=1e5,BI=null,qI=new Map;function memoKey(e,t){return`${e}\0${t}`}function memoize(e,t){if(qI.size>=128){const e=qI.keys().next().value;void 0!==e&&qI.delete(e)}return qI.set(e,t),t}function loadGitignore(e){const t=it(),r=n(e,".gitignore");if(O(r))try{t.add(j(r,"utf8"))}catch{}return t.add(".git"),t}function isIgnored(e,t,n){return!!e.ignores(t)||n&&e.ignores(`${t}/`)}function listDirectory(e,t){const r=loadGitignore(t),o=[],i=H(e,{withFileTypes:!0});for(const a of i){const i=n(e,a.name),l=a.isDirectory();isIgnored(r,s(t,i),l)||o.push({name:a.name,path:i,isDirectory:l})}return sortDirectoriesFirst(o)}function sortDirectoriesFirst(e){return e.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name))}function buildFileIndex(e){const t=loadGitignore(e),r=[],o=[{dirPath:e,depth:0}];for(let i=0;i<o.length;i++){const{dirPath:a,depth:l}=o[i];if(r.length>=UI)break;let u;try{u=H(a,{withFileTypes:!0})}catch{continue}for(const i of u){if(r.length>=UI)break;const u=n(a,i.name),d=s(e,u),m=i.isDirectory();isIgnored(t,d,m)||(r.push({name:d,path:u,isDirectory:m,nameLower:d.toLowerCase(),filenameLower:i.name.toLowerCase(),depth:l+1}),m&&"node_modules"!==i.name&&l<8&&o.push({dirPath:u,depth:l+1}))}}return r}function getFileIndex(e){if(BI&&BI.basePath===e&&Date.now()-BI.builtAt<3e4)return BI.entries;const t=buildFileIndex(e);return BI={basePath:e,entries:t,builtAt:Date.now()},qI.clear(),t}function invalidateFileIndex(){BI=null,qI.clear()}function compareByRelevance(e,t,n){const r=e.nameLower===n,o=t.nameLower===n;if(r&&!o)return-1;if(!r&&o)return 1;const s=e.filenameLower.includes(n),i=t.filenameLower.includes(n);return s&&!i?-1:!s&&i?1:e.depth!==t.depth?e.depth-t.depth:e.name.localeCompare(t.name)}function searchIndex(e,t){const n=e.toLowerCase(),r=[];for(const e of getFileIndex(t)){if(!e.nameLower.includes(n))continue;if(50===r.length&&compareByRelevance(e,r[r.length-1],n)>=0)continue;let t=0,o=r.length;for(;t<o;){const s=t+o>>1;compareByRelevance(e,r[s],n)<0?o=s:t=s+1}r.splice(t,0,e),r.length>50&&r.pop()}return r.map(({name:e,path:t,isDirectory:n})=>({name:e,path:t,isDirectory:n}))}function searchFiles(e,t=process.cwd()){if(!e.trim())return[];const r=memoKey(t,e),o=qI.get(r);if(o)return o;if(/[/\\]$/.test(e))try{return memoize(r,listDirectory(n(t,e),t).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}if(/[/\\]/.test(e)){const o=e.split(/[/\\]/),i=(o.pop()||"").toLowerCase();try{return memoize(r,listDirectory(n(t,...o),t).filter(e=>!i||e.name.toLowerCase().includes(i)).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}}return memoize(r,searchIndex(e,t))}__name(memoKey,"memoKey"),__name(memoize,"memoize"),__name(loadGitignore,"loadGitignore"),__name(isIgnored,"isIgnored"),__name(listDirectory,"listDirectory"),__name(sortDirectoriesFirst,"sortDirectoriesFirst"),__name(buildFileIndex,"buildFileIndex"),__name(getFileIndex,"getFileIndex"),__name(invalidateFileIndex,"invalidateFileIndex"),__name(compareByRelevance,"compareByRelevance"),__name(searchIndex,"searchIndex"),__name(searchFiles,"searchFiles"),Vr();var zI=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[o,s]=se(process.cwd()),[i,l]=se([]),[u,d]=se(0),[m,g]=se(0),h=n.trim()?15:10;ae(()=>{invalidateFileIndex()},[]);const f=ce(e=>{try{const t=[];"/"!==e&&t.push({name:"..",path:r(e),isDirectory:!0}),t.push(...listDirectory(e,process.cwd())),l(t),d(0),g(0)}catch{}},[]);ae(()=>{if(n.trim()){const e=searchFiles(n);l(e),d(0),g(0)}else f(o)},[o,f,n]),Z((r,o)=>{if(o.escape)t();else if(o.upArrow)d(e=>{const t=Math.max(0,e-1);return t<m&&g(t),t});else if(o.downArrow)d(e=>{const t=Math.min(i.length-1,e+1);return t>=m+h&&g(t-h+1),t});else{if(o.rightArrow){const e=i[u];if(!e)return;return void(e.isDirectory&&!n.trim()&&s(a(e.path)))}if(o.return){const t=i[u];if(!t)return;return void e(t.path)}}});const y=i.slice(m,m+h);return re.createElement(Q,{flexDirection:"column",paddingLeft:1},re.createElement(Q,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${o}`),re.createElement(Y,{color:br.DIM},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===y.length?re.createElement(Y,{color:br.DIM},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):y.map((e,t)=>{const n=m+t,r=e.name,o=n===u;return re.createElement(Y,{key:e.path,color:o?br.GREEN:br.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}))},"FileList");Bt(),_n(),Ro(),Vr(),Bt(),Vr();var HI=__name(e=>{if(e>=1e6){const t=e/1e6;return`${t%1==0?t.toFixed(0):t.toFixed(1)}M`}return`${Math.round(e/1e3)}k`},"formatTokens"),WI=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20&&e.current>=18e4)return re.createElement(Q,{paddingRight:3},re.createElement(Y,{color:br.DIM},"~",HI(e.current)," tokens in context · try"," "),re.createElement(Y,{color:br.DIM,bold:!0},"/compact"));if(n>20)return null;const r=__name(e=>e>=90?br.RED:e>=70?br.YELLOW:br.DIM,"getColor"),o=t>=90?6:Math.round(t/100*6),s=6-o,i=Re.square.repeat(o),a=Re.squareLightShade.repeat(s),l=r(t);return re.createElement(Q,{paddingRight:3},re.createElement(Y,{color:l},`Context left before auto-compact ${n}% `),re.createElement(Y,{color:l},i),s>0&&re.createElement(Y,{color:br.DIM},a))},"ContextUsage");Bt(),Rs(),Vr();var GI=__name(()=>{const[e,t]=se("continuous learning"),[n,r]=se(!1),[o,s]=se(!1),i=ie([]),a=ie(0),l=ie(null),u=ie(!1);ae(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),s(!1),i.current=[],a.current=0,l.current&&(clearTimeout(l.current),l.current=null),void t(e.message)):u.current&&"analyzed"!==e.type?void i.current.push(e):"analyzed"===e.type?(u.current=!1,void(i.current.length>0?(a.current=0,n()):(r(!1),s(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),s(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const o="learned"===e.type||"refactored"===e.type;s(o);const u="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;l.current=setTimeout(()=>{a.current++,n()},u)},"cycleThroughNextEvent");return FC.on("new-event",e),()=>{FC.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?Re.squareSmallFilled:Re.squareSmall} TASTE`,m=9+e.length+d.length>Cs;let g=e;g=truncateString(m?{text:e,maxChars:Cs}:{text:e,maxChars:Cs-d.length-9-10});const h=o?void 0:br.DIM;return re.createElement(Q,{paddingRight:2},!m&&re.createElement(re.Fragment,null,re.createElement(BracketWrap,{color:br.DIM},"ctrl+t"),re.createElement(Y,{color:br.DIM}," ")),re.createElement(Y,{color:h},g),!m&&re.createElement(Y,{color:vr.TEXT},d))},"LearningFeedMini");Bt(),Vr();var VI=__name(({mode:e,pendingExitKey:t})=>t?re.createElement(Y,{color:br.DIM},"Press Ctrl+C again to exit"):"bypass"===e?re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:br.RED},"» permission bypass on "),re.createElement(BracketWrap,{color:br.DIM},"shift+tab")):"auto-accept"===e?re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:$r},"» accept edits on "),re.createElement(BracketWrap,{color:br.DIM},"shift+tab")):"plan"===e?re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:Lr},"plan mode "),re.createElement(BracketWrap,{color:br.DIM},"shift+tab")):re.createElement(Y,{color:br.DIM},"? for shortcuts"),"ModeIndicator");Bt(),Vr(),ko();var KI=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?br.DIM:Dr.MERGED;return re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:n},"PR "),re.createElement(Eo,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),QI=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:"connected"===e.type?br.GREEN:br.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),YI=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const v=e>=60;return re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r||l?re.createElement(Q,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(Q,{flexDirection:"row",columnGap:0},n&&!l?re.createElement(Y,{color:Ir},t):re.createElement(VI,{mode:r,pendingExitKey:l}),!l&&re.createElement(KI,{prInfo:o}),!l&&re.createElement(QI,{indicator:a})),v&&re.createElement(Q,{flexDirection:"column",alignItems:"flex-end"},s&&re.createElement(GI,null),i&&re.createElement(WI,{usage:i}))):re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(VI,{mode:r}),v&&s&&re.createElement(GI,null)),re.createElement(Q,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(Q,{flexDirection:"row",columnGap:0},re.createElement(Y,{color:n?Ir:br.DIM},t),re.createElement(KI,{prInfo:o}),re.createElement(QI,{indicator:a})),v&&i&&re.createElement(WI,{usage:i}))),(u||d||g&&m)&&re.createElement(Q,{flexDirection:"row",columnGap:1},u&&re.createElement(Y,null,Re.tick," ","Command Code"," updated:"," ",re.createElement(Y,{color:br.DIM},"v",u.updatedFrom),re.createElement(Y,{color:br.DIM}," ",Re.arrowRight," "),re.createElement(Y,null,"v",u.updatedTo)),!u&&d&&re.createElement(Y,{color:br.YELLOW,dimColor:!0},Re.info," Update available:"," ",d.currentVersion," ",Re.arrowRight," ",d.latestVersion),g&&m&&re.createElement(Y,{color:br.GREEN,dimColor:!0},Re.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:br.GREEN},"! for bash mode")),y&&f&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:Er},"SHARED: ",f.url," (copied to clipboard)")),w&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:w.includes("NOT SHARED")?br.RED:Er},w)),S&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:Er},S)),E&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:br.YELLOW},Re.warning," ",E)))},"BottomIndicator");Bt(),Sv(),Rs(),Vr();var JI=__name((e,t)=>e.padEnd(t),"padCell"),XI=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getDeleteErrorMessage"),ZI=__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"),eM=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),tM=__name(e=>truncateString({text:eM(e),maxChars:Es}),"truncateMessage"),nM=__name(e=>e.title?eM(e.title):tM(e.firstMessage),"getSessionSummary"),rM=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=se([]),[o,s]=se(0),[i,a]=se(0),[l,u]=se(!0),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w]=se(()=>getCurrentGitBranch()),S=useTerminalHeight(),E=Math.max(6,S-14),v=ce(async()=>{u(!0);const e=await fv.listSessions();r(e),u(!1)},[]);ae(()=>{v()},[v]);const C=ce(async e=>{try{await fv.deleteSession(e),h(!1),y(null),s(0),a(0),await v()}catch(e){h(!1),y(`Failed to delete session: ${XI(e)}`)}},[v]),k=d&&w?n.filter(e=>e.gitBranch===w):n;if(Z((n,r)=>{if(g)if(r.return){if(k.length>0&&o<k.length){const e=k[o];C(e.id)}}else h(!1);else if(r.delete||r.ctrl&&"d"===n)k.length>0&&(y(null),h(!0));else{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),s(0),void a(0)):void(r.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?s(e=>{const t=Math.min(k.length-1,e+1);return t>=i+E&&a(t-E+1),t}):r.return&&k.length>0&&o<k.length&&e(k[o].id));t()}}),l)return re.createElement(Q,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:br.GRAY},"Loading sessions..."));if(0===k.length)return re.createElement(Q,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:br.GRAY},d&&w?`No sessions found for branch "${w}"`:"No previous sessions found"),re.createElement(Y,{color:br.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const T=k.slice(i,i+E),_=o<k.length?k[o]:null,x=g&&_?`Delete "${nM(_)}"? Press Enter to confirm, any other key to cancel.`:null;return re.createElement(Q,{flexDirection:"column",paddingLeft:1,width:"100%"},re.createElement(Y,{color:br.CYAN,bold:!0},"Resume Session"),re.createElement(Q,{marginTop:1}),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Mr,bold:!0},JI("#",6),JI("Modified",12),JI("Git Branch",22),JI("Messages",12),"Summary")),re.createElement(Q,{flexDirection:"column"},T.map((e,t)=>{const n=i+t,r=o===n,s=truncateString({text:e.gitBranch||"-",maxChars:20});return re.createElement(Y,{key:e.id,color:r?br.WHITE:br.GRAY,backgroundColor:r?zr:void 0,bold:r,wrap:"truncate-end"},JI(`${n+1}.`,6),JI(ZI(e.lastModified),12),JI(s,22),JI(String(e.messageCount),12),nM(e)," ")})),re.createElement(Q,{marginTop:1}),x&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},x)),f&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},f)),k.length>E&&re.createElement(Y,{color:br.DIM},"Showing ",i+1,"–",Math.min(i+E,k.length)," ","of ",k.length,i>0?" · ↑ more":"",i+E<k.length?" · ↓ more":""),re.createElement(Y,{color:br.DIM},"↑↓ navigate · Enter select · Del delete · ctrl+b ",d?`[branch: ${w??"unknown"}]`:"branch filter"," · ESC cancel"))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],o=0;for(let s=0;s<e;s++){const e=`[Image #${s+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&o+i>t?(n.push(r),r=[s],o=e):(r.push(s),o+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return re.createElement(Y,null,r?" ":"",t?re.createElement(Y,{inverse:!0},o):s)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:o}){if(0===e.length)return null;const s=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:o}),i=Math.max(1,r-(s.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return re.createElement(Q,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>re.createElement(Q,{key:r,flexDirection:"row"},re.createElement(Q,{flexShrink:0,marginRight:1},0===r&&re.createElement(Y,{color:br.DIM},s)),re.createElement(Q,{flexDirection:"row"},e.map((e,r)=>re.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Bt(),Vr(),Bt(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),Po(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Bt();var oM=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=se(null),[s,i]=se(!1),a=ie(!1),l=ie(null),u=ie(n),[d,m]=se(!1),[g,h]=se("connected"),f=ie(null),y=ie(null),w=ce((e,t)=>{y.current&&(clearTimeout(y.current),y.current=null),h(e),m(!0),void 0!==t&&(y.current=setTimeout(()=>{m(!1)},t))},[]),S=ce(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),E=ce(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new OT,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=f.current;if(null===r?n&&w("connected",3e3):r!==n&&(n?w("connected",2e3):w("disconnected",5e3)),f.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),o(r)}else o(null)}catch{!0===f.current&&w("disconnected",5e3),f.current=!1,i(!1),o(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[w]);ae(()=>{const e=u.current;u.current=n,e&&!n&&t&&null!==xT()&&E(!1)},[n,t,E]),ae(()=>{if(!t)return;if(null===xT())return;let e=null,n=!1,r=0;function schedule(t){n||(e=setTimeout(()=>{tick(!1)},t))}async function tick(e){if(u.current)return void schedule(500);if(await E(e),n)return;if(l.current?.isConnected)return r=0,void schedule(500);r+=1;const t=Math.min(r,6);schedule(Math.min(3e4,500*2**t)+250*Math.random())}return __name(schedule,"schedule"),__name(tick,"tick"),tick(!0),()=>{n=!0,e&&clearTimeout(e),S(),l.current?.disconnect(),l.current=null}},[t,E,S]);const v=xT(),C={visible:d,message:"connected"===g?`${v?Zx[v]??"IDE":"IDE"} ${Re.tick}`:"run /ide",type:g};return{context:r,connected:s,refresh:E,connectionIndicator:C}},"useVSCodeContext");Bt();var sM=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language??"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;").replace(/[\u202A-\u202E\u2066-\u2069\u200B-\u200D\uFEFF]/g,"");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");function basename5(e){return t.win32.basename(e)}function resolvePastedTextTokens({input:e,detectedContent:t}){return t.reduce((e,t)=>{const n=pastedTextToken(t);return e.includes(n)?e.replace(n,()=>t):e},e)}Bt(),Qr(),__name(basename5,"basename"),__name(resolvePastedTextTokens,"resolvePastedTextTokens");var iM=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),aM=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const o=e?t?.activeFile:null;if(o?.relativePath){const e=basename5(o.relativePath),t=n<80?15:n<120?25:40;return`In ${e.length>t?e.slice(0,t-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText");function getModelShortName(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getModelHintLayout(e){const{currentModel:t,terminalWidth:n}=e,r=getCommandMenuDescriptionWidth(n),o=modelSupportsReasoningEffort(t)?getReasoningEffort(t):null,s=o?` with ${o} effort`:"";return{descriptionWidth:r,text:truncateString({text:`${getModelShortName(t)}${s} (current)`,maxChars:r})}}Bt(),bo(),Co(),Rs(),__name(getModelShortName,"getModelShortName"),__name(getModelHintLayout,"getModelHintLayout");var lM=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}function getCommandMenuStateFromQuery(e){return isDesignSubmenu(e)?{showMenu:!0,query:e}:e.includes(" ")?{showMenu:!1,query:""}:{showMenu:!0,query:e}}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace"),__name(getCommandMenuStateFromQuery,"getCommandMenuStateFromQuery");var cM=__name(()=>re.createElement(Q,{flexDirection:"column",paddingLeft:1},re.createElement(Y,{color:br.DIM,bold:!0},"Available Shortcuts:"),re.createElement(Q,{columnGap:4},re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.DIM},"! for bash mode"),re.createElement(Y,{color:br.DIM},"/ for commands"),re.createElement(Y,{color:br.DIM},"@ for file paths"),re.createElement(Y,{color:br.DIM},"shift + tab to toggle auto-accept")),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.DIM},"double tap esc to clear input"),re.createElement(Y,{color:br.DIM},"ctrl + j / shift + ⏎ for newline"),re.createElement(Y,{color:br.DIM},"ctrl + g to open in editor"),re.createElement(Y,{color:br.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),uM=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,currentModel:T,showProviderInfo:_,permissionMode:x="standard",onToggleAutoAccept:A,hintMessage:P,historyManager:I,pendingExitKey:M=null,onOverlayVisibilityChange:R,onDoubleEscapeEmpty:N,onAltP:L,isProcessing:$=!1,ideContextEnabled:D=!0})=>{const[O,F]=se(0),[j,U]=se(!1),[B,q]=se(!1),[z,H]=se(!1),[W,G]=se(!1),[V,K]=se(""),[J,ee]=se(null),[te,ne]=se(!1),oe=ie(0),ue=ie(0),[de,me]=se([]),[pe,ge]=se([]),[he,fe]=se(-1),[ye,we]=se(""),Se=ie(!1),be=ie(!1),Ee=ie(void 0),[ve,Ce]=se(-1),[ke,Te]=se(""),_e=ie(0),{isEditorOpen:xe,editorError:Ae,handleOpenInEditor:Pe,clearEditorError:Ie}=useExternalEditor({input:e,setInput:n,setInputKey:F,detectedContent:de,setDetectedContent:me,onEditorClose:__name(()=>{Se.current=!1},"onEditorClose")}),Me=le(()=>shouldCollapsePastedText(),[]),{handlePaste:Ne,resetPasteState:Le,isPasting:$e}=useBracketedPaste({input:e,detectedContent:de,setInput:n,setDetectedImages:ge,setDetectedContent:me,incrementInputKey:__name(()=>F(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Ee.current=e},"setInitialCursor"),collapsePastedText:Me}),{context:De,connected:Oe,refresh:Fe,connectionIndicator:je}=oM({enabled:D,paused:$}),{stdout:Ue}=X(),Be=Ue?.columns??80,{pr:qe}=jI();ae(()=>{const e=i||W||te;R?.(e)},[i,W,te,R]);const ze=ce(()=>{ge([]),fe(-1)},[]),He=ce(()=>{G(!1),ee(null)},[]),We=ce(()=>{n(""),q(!1),He(),K(""),ne(!1),me([]),ze(),we(""),Le(),Ce(-1),Te(""),F(e=>e+1)},[n,Le,ze,He]),Ge=ce(()=>{Se.current=!0;const{text:t,cursor:r}=insertTextAt(e,_e.current,"\n");n(t),Ee.current=r,F(e=>e+1),setTimeout(()=>{Se.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==he&&r.leftArrow)return void fe(prevImageIndex({currentIndex:he,imageCount:pe.length}));if(-1!==he&&r.rightArrow)return void fe(nextImageIndex({currentIndex:he,imageCount:pe.length}));if(r.upArrow){if(i||W||te)return;const t=e.indexOf("\n"),r=-1===t||_e.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:pe.length,selectedImageIndex:he,historyIndex:ve}))return void fe(pe.length-1);if(-1!==he&&fe(-1),0!==e.length&&-1===ve&&!r)return;const o=I?.count()??0;if(0===o)return;-1===ve&&Te(e);const s=Math.min(ve+1,o-1);return void(s!==ve&&(Ce(s),n(I?.getAt(s)||""),F(e=>e+1)))}if(r.downArrow){if(i||W||te)return;if(-1===ve)return;const t=e.lastIndexOf("\n");if(!(-1===t||_e.current>t))return;const r=ve-1;return Ce(r),n(-1===r?ke:I?.getAt(r)||""),void F(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void ze();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return Se.current=!0,void Pe();if(getIsExpandToolShortcut(r,t))return Se.current=!0,n(e),F(e=>e+1),void setTimeout(()=>{Se.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:$e()}))return be.current=!0,Ge(),void setTimeout(()=>{be.current=!1},0);if(r.meta&&r.backspace)return void We();if(r.meta&&"w"===t)return Se.current=!0,void We();const o=r.ctrl&&"v"===t||lM.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e;Se.current=!0;const r=await detectClipboardImage();return r&&(ge(e=>[...e,r]),n(t),F(e=>e+1)),void(Se.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return H(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==he&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:pe,index:he});return ge([...e]),void fe(t)}if(r.escape){if(-1!==he)return void fe(-1);if(W)return;if(te)return ne(!1),n(ye),void F(e=>e+1);const t=Date.now();return t-oe.current<500?(e.length>0?We():N?.(),oe.current=0,ue.current=0):(oe.current=t,j||B||(ue.current=t)),U(!1),void q(!1)}j&&(r.backspace||r.delete)&&0===e.length&&U(!1)}});const Ve=ce(async t=>{if(xe)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void L?.();const o=processBracketedPaste(t);if((o.isPasteStart||o.isPasteEnd||$e())&&await Ne(t))return;if(Se.current)return void(Se.current=!1);-1!==ve&&Ce(-1);const s=1===t.length,l=t.slice(-1);if(s){if("?"===l&&!j)return U(!0),n(""),void F(e=>e+1);if("!"===l&&!B)return U(!1),q(!0),n(""),void F(e=>e+1)}if("/"!==l||W||"/"!==t||(G(!0),K("")),W)if(t.startsWith("/")){const e=t.substring(1),{showMenu:n,query:r}=getCommandMenuStateFromQuery(e);n?G(!0):He(),K(r)}else He(),K("");"@"!==l||i||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(a(!0),u(""));const d=t.lastIndexOf("@");if(t.length<e.length&&-1!==d&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(d+1),n=!e.includes(" "),r=d>0?t[d-1]:"";n&&isPrecededByWhitespace(r)&&(a(!0),u(e))}if(i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!1),u("");else{const n=t.substring(e+1);u(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);u(e),a(!1)}else u(n)}}j&&(t!==e||t.length<e.length)&&U(!1),Ae&&Ie(),0===t.length&&(q(!1),He(),K(""),ne(!1),me([]),u(""),we(""),Le()),n(t)},[j,e,n,i,a,W,B,pe,ve,Ne,Le,L,Ae,Ie,xe,He]),Ke=ce(async()=>{if(Fe(),ue.current=0,j)return void U(!1);const r=e.trim(),o=!B&&r.startsWith("/");let s=r;!B&&de.length>0&&(s=resolvePastedTextTokens({input:s,detectedContent:de}));const i=!B&&pe.length>0?[...pe]:[],a=De?sM(De):void 0;if(o&&d&&(n(""),"handled"===(await d(s,i,a)).status))return I?.add(s),q(!1),He(),K(""),ze(),me([]),Ce(-1),void Te("");Ce(-1),Te(""),s.length>0&&I?.add(s);const l=De?.selection?{lines:De.selection.lineCount,file:basename5(De.activeFile?.relativePath??De.activeFile?.path??"")||"unknown",ide:Zx[xT()??""]??"IDE"}:void 0;t({input:s,role:B?"bash":"user",images:i,ideContext:a,ideHint:l}),q(!1),He(),K(""),ze(),me([])},[t,d,j,e,B,pe,de,I,Fe,ze,He,n]),Qe=ce(t=>{const r=s(process.cwd(),t);let o;if(i&&""!==l){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),a(!1),u(""),F(e=>e+1)},[n,a,e,i,l,u]),Ye=ce(()=>{a(!1),u("")},[a,u]),Je=ce(e=>{const t=YA.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();n(t+" "),K(t.substring(1)+" ")}else He(),K(""),n(e+" ");F(e=>e+1)},[n,He]),Xe=ce(t=>{if("/resume"===t||"/sessions"===t)return I?.add(t),Ce(-1),Te(""),we(e),He(),K(""),ne(!0),n(""),void F(e=>e+1);if("/design help"===t)return He(),K(""),n(""),F(e=>e+1),I?.add(t),void d?.("/design help");if(QA.has(t))return He(),K(""),I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),void d?.(t);const r=YA.has(t),o=JA.has(t);r?Je(t):(He(),K(""),o?(I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),d?.(t)):(n(t+" "),F(e=>e+1)))},[d,n,e,I,Je,He]),Ze=ce(()=>{He(),K(""),n(""),Ce(-1),Te(""),F(e=>e+1)},[n,He]),et=ce(e=>{ne(!1),n(""),we(""),Ce(-1),Te(""),F(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),tt=ce(()=>{ne(!1),n(ye),Ce(-1),Te(""),F(e=>e+1)},[ye,n]),nt=ce(e=>{_e.current=e,Ee.current=void 0},[]),rt=le(()=>{const t=qe&&("OPEN"===qe.state||"MERGED"===qe.state);return"auto-accept"===x||"plan"===x||"bypass"===x||Oe||t?!j&&!te:!j&&0===e.length&&!B&&!te},[j,e,B,te,x,Oe,qe]),ot=ie(new Map),st=le(()=>pe.map((e,t)=>{if(ot.current.has(e))return ot.current.get(e)??null;const n=saveTempImage(e,t+1);return ot.current.set(e,n),n}),[pe]),it=__name(()=>j||i||W||te||z?0:rt||M||B?3:4,"getBottomMargin");return re.createElement(Q,{width:"100%",flexDirection:"column",marginBottom:it()},!te&&re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(ImageRowsDisplay,{detectedImages:pe,selectedImageIndex:he,imageTempPaths:st,termWidth:Be,inHistory:-1!==ve}),re.createElement(Y,{color:B?br.GREEN:br.GRAY},Re.line.repeat(Be)),(()=>{const t=__name(()=>{if(!be.current)return Date.now()-ue.current<100?(ue.current=0,void Ge()):void(i||W||te||xe||Ke());be.current=!1},"handleTextInputSubmit"),n=__name(n=>re.createElement(TextInput,{key:O,value:e,placeholder:xe?"Save and close the editor to continue...":o,onChange:Ve,onSubmit:t,showCursor:!xe&&r&&-1===he,onCursorChange:nt,initialCursor:Ee.current,prefix:`${B?"!":Re.pointer} `,prefixColor:B?br.GREEN:br.WHITE,singleLine:n?.singleLine,maxWidth:n?.maxWidth}),"renderTextInput");if(W&&T&&"/model"===J){const e=getModelHintLayout({currentModel:T,terminalWidth:Be});return re.createElement(Q,{flexDirection:"row",width:"100%"},re.createElement(Q,{width:25},n({singleLine:!0,maxWidth:25})),re.createElement(Q,{width:e.descriptionWidth},re.createElement(Y,{color:br.DIM,wrap:"truncate"},e.text)))}return n()})(),re.createElement(Y,{color:B?br.GREEN:br.GRAY},Re.line.repeat(Be))),j&&re.createElement(cM,null),z&&re.createElement(Q,{paddingTop:1},re.createElement(Y,{color:br.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&re.createElement(zI,{onSelectFile:Qe,onClose:Ye,searchQuery:l}),W&&re.createElement(eP,{onSelectCommand:Xe,onInsertCommand:Je,onClose:Ze,searchQuery:V,onSelectedCommandChange:ee}),te&&re.createElement(rM,{onSelectSession:et,onClose:tt}),!W&&(rt||M)&&re.createElement(YI,{termWidth:Be,indicatorText:aM(Oe,De,Be),isIDEIndicator:iM(Oe,De),permissionMode:x,prInfo:qe,tasteLearning:g,contextUsage:m,connectionIndicator:je,pendingExitKey:M,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:_,isBashMode:B,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),Ae&&re.createElement(Q,{paddingLeft:1,flexDirection:"column"},re.createElement(Y,{color:br.YELLOW},Ae)))},"InputBox");Bt(),Rs(),Vr();var dM=__name(({messages:e})=>0===e.length?null:re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Q,{marginBottom:0},re.createElement(Y,{color:kr,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>re.createElement(Q,{key:t},re.createElement(Y,{color:br.DIM},Re.pointerSmall," "),re.createElement(Y,{color:br.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),mM=re.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:R,pendingExitKey:N,onResetPendingExitKey:L,onDoubleEscapeEmpty:$,retryAttempt:D,onAltP:O})=>{const[F,j]=se(0),U=ie(o);return ae(()=>{N&&o!==U.current&&o.length>0&&L?.(),U.current=o},[o,N,L]),ae(()=>{if(!t)return void j(0);const e=setInterval(()=>{j(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),re.createElement(Q,{flexDirection:"column"},re.createElement(dM,{messages:e}),re.createElement(Q,{flexDirection:"row",justifyContent:"space-between"},re.createElement(Q,{flexDirection:"column"},(t||n.isExecuting)&&null===D&&re.createElement(_I,{tokens:g,timeElapsed:F,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),M&&re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM}," ","⎿"," ","Tip: ",M)))),re.createElement(uM,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:R,pendingExitKey:!N||t||n.isExecuting?null:N,onDoubleEscapeEmpty:$,onAltP:O,isProcessing:t}))});Bt(),_v(),Mv(),To(),Ro();var pM=__name(({onComplete:e,onCancel:t})=>{const[n,r]=se(!1),[o,s]=se(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");g()}}),n?re.createElement(vo,{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}`)}}):re.createElement(Av,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");function buildOAuthMetadataUrl(e){const t=new g(e),n="/"===t.pathname?"":t.pathname.replace(/\/+$/,"");return t.pathname=`/.well-known/oauth-authorization-server${n}`,t.search="",t.hash="",t.toString()}function buildOidcMetadataUrl(e){const t=new g(e),n=t.pathname.replace(/\/+$/,"");return t.pathname=`${n}/.well-known/openid-configuration`,t.search="",t.hash="",t.toString()}async function tryFetchAsMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.authorization_endpoint&&n.token_endpoint?{authorizationEndpoint:n.authorization_endpoint,tokenEndpoint:n.token_endpoint,registrationEndpoint:n.registration_endpoint,scopes:n.scopes_supported}:null}catch(t){return dlog(`[MCP] OAuth metadata fetch failed for ${e}`,t),null}}async function discoverOAuthMetadataFromIssuer(e){return await tryFetchAsMetadata(buildOAuthMetadataUrl(e))||await tryFetchAsMetadata(buildOidcMetadataUrl(e))}async function discoverOAuthMetadata(e){const t=new g(e),n=`${t.protocol}//${t.host}`;return await tryFetchAsMetadata(`${n}/.well-known/oauth-authorization-server`)||await tryFetchAsMetadata(`${n}/.well-known/openid-configuration`)}function parseResourceMetadataUrl(e){if(!e)return null;const t=e.match(/resource_metadata\s*=\s*"([^"]+)"|resource_metadata\s*=\s*([^\s,]+)/i);return t?t[1]??t[2]??null:null}async function fetchProtectedResourceMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{authorizationServers:n.authorization_servers,scopesSupported:n.scopes_supported}}catch(e){return dlog("[MCP] Protected resource metadata fetch failed",e),null}}async function checkServerAuthRequirements(e){try{const t=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"initialize",id:0,params:{protocolVersion:zb,capabilities:{},clientInfo:Hb}})});if(401===t.status||403===t.status){const n=parseResourceMetadataUrl(t.headers?.get?.("www-authenticate")??null);if(n){const e=await fetchProtectedResourceMetadata(n),t=e?.authorizationServers?.[0];if(t){const n=await discoverOAuthMetadataFromIssuer(t);if(n)return e?.scopesSupported&&(n.scopes=e.scopesSupported),{requiresAuth:!0,metadata:n}}}return{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}}return{requiresAuth:!1}}catch(e){return{requiresAuth:!1,error:`Server unreachable: ${e instanceof Error?e.message:String(e)}`}}}async function registerOAuthClient({registrationEndpoint:e,clientName:t,redirectUris:n}){try{const r=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:t,redirect_uris:n,token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]})});if(r.ok){const e=await r.json();return{clientId:e.client_id,clientSecret:e.client_secret}}}catch(e){dlog("[MCP] OAuth client registration failed",e)}return null}async function discoverAndAuthenticate({serverName:e,serverUrl:t,onStatus:n}){const r=n??(()=>{});r("Probing server for OAuth requirements...");const o=await checkServerAuthRequirements(t);if(o.error)return{success:!1,error:o.error};if(!o.requiresAuth)return{success:!1,error:"Server does not require authentication"};if(!o.metadata)return{success:!1,error:"Server returned 401 but did not advertise OAuth metadata. Add `oauth` config manually via `mcp add-json`."};const{authorizationEndpoint:s,tokenEndpoint:i,registrationEndpoint:a,scopes:l}=o.metadata;if(!a)return{success:!1,error:"Server requires pre-registered OAuth credentials (no Dynamic Client Registration endpoint advertised). Register an OAuth client with the server, then add it via `mcp add-json` with an `oauth.clientId` field."};const u=`http://${cE}:${lE}/callback`;r("Registering OAuth client...");const d=await registerOAuthClient({registrationEndpoint:a,clientName:Hb.name,redirectUris:[u]});if(!d)return{success:!1,error:"Dynamic client registration failed at "+a};const m={authorizationUrl:s,tokenUrl:i,clientId:d.clientId,clientSecret:d.clientSecret,scopes:l},g=await performOAuthFlow(e,t,m,{onStatus:n});return g.success&&(await storeDiscoveredClient(e,{authorizationUrl:s,tokenUrl:i,clientId:d.clientId,scopes:l}),d.clientSecret?await storeClientSecret(e,d.clientSecret):await deleteClientSecret(e)),g}Bt(),Bt(),eE(),Vb(),rE(),tE(),sE(),hE(),SE(),vE(),Bt(),SE(),vE(),Jb(),gE(),Bt(),aE(),Vb(),ir(),__name(buildOAuthMetadataUrl,"buildOAuthMetadataUrl"),__name(buildOidcMetadataUrl,"buildOidcMetadataUrl"),__name(tryFetchAsMetadata,"tryFetchAsMetadata"),__name(discoverOAuthMetadataFromIssuer,"discoverOAuthMetadataFromIssuer"),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(parseResourceMetadataUrl,"parseResourceMetadataUrl"),__name(fetchProtectedResourceMetadata,"fetchProtectedResourceMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),Bt(),Vb(),gE(),Jb(),__name(discoverAndAuthenticate,"discoverAndAuthenticate"),Vr(),ko();var gM=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(!0),[s,i]=se(0),[a,l]=se("list"),[u,d]=se(null),[m,g]=se(0),h=useTerminalHeight(),f=ce(async()=>{o(!0);try{const e=await listMcpServers(),t=getMcpConnectionManager().getConnectedServers(),r=await Promise.all(e.map(async e=>{const n=t.find(t=>t.name===e.name);let r,o,s="disconnected";return!1===e.config.enabled?s="disabled":n&&"connected"===n.status?(s="connected",r=n.tools.length):n&&"error"===n.status?(s="error",o=n.error):(e.config.oauth||"http"===e.config.transport)&&(await hasTokens(e.name)?s="authenticated":e.config.oauth&&(s="requires_auth")),{name:e.name,config:e.config,scope:e.scope,status:s,toolCount:r,error:o}}));n(r)}catch{}finally{o(!1)}},[]);ae(()=>{f()},[f]);const y=le(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),w=y[s]??null,S=h-1,E=le(()=>new Set(y.map(e=>e.scope)).size,[y]),v=Math.max(4,S-8-2*E);ae(()=>{g(e=>clampScrollOffset({cursor:s,total:y.length,maxVisible:v,currentOffset:e}))},[s,y.length,v]),Z((t,n)=>{if(n.ctrl&&"c"===t)e();else if(n.escape)"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e();else if("list"===a){if(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow){if(0===y.length)return;const e=Math.max(0,y.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&w&&(l("actions"),d(null))}});const C=__name((e,t)=>{const n=__name((e,n)=>re.createElement(Y,{color:e,backgroundColor:t},n),"icon");switch(e){case"connected":return n(br.GREEN,Re.tick);case"authenticated":return n(br.CYAN,Re.tick);case"requires_auth":return n(br.YELLOW,Re.warning);case"error":return n(br.RED,Re.cross);default:return n(br.GRAY,Re.circle)}},"getStatusIcon"),k=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";case"disabled":return"disabled";default:return"not connected"}},"getStatusText"),T=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),_=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),x=__name(async e=>{if(w)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)if("remove"!==e.value)if("disable"!==e.value)if("enable"!==e.value);else{d({text:`Enabling ${w.name}...`,color:br.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:w.name,enabled:!0,scope:w.scope}))return void d({text:`${Re.cross} Failed to enable ${w.name}, server may no longer exist in ${w.scope} scope`,color:br.YELLOW});await f(),d({text:`${Re.tick} Enabled ${w.name}`,color:br.GREEN})}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else{d({text:`Disabling ${w.name}...`,color:br.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:w.name,enabled:!1,scope:w.scope}))return void d({text:`${Re.cross} Failed to disable ${w.name}, server may no longer exist in ${w.scope} scope`,color:br.YELLOW});await e.disconnectServer(w.name),await f(),d({text:`${Re.tick} Disabled ${w.name}`,color:br.GREEN})}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else l("confirm-remove");else{if(!(w.config.oauth||"http"===w.config.transport&&w.config.url))return void d({text:"Authentication requires an http server with a url",color:br.YELLOW});d({text:`Authenticating ${w.name}...`,color:br.CYAN,loading:!0});try{let e;if(w.config.oauth){const t={authorizationUrl:w.config.oauth.authorizationUrl,tokenUrl:w.config.oauth.tokenUrl,clientId:w.config.oauth.clientId,clientSecret:w.config.oauth.clientSecret,scopes:w.config.oauth.scopes};e=await performOAuthFlow(w.name,w.config.url??"",t,{onStatus:__name(()=>{},"onStatus")})}else e=await discoverAndAuthenticate({serverName:w.name,serverUrl:w.config.url});if(e.success){d({text:`${Re.tick} Authenticated with ${w.name}`,color:br.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name)}catch{}await f()}else d({text:`${Re.cross} Auth failed: ${e.error}`,color:br.RED})}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else{d({text:`Connecting ${w.name}...`,color:br.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name),d({text:`${Re.tick} Connected to ${w.name}`,color:br.GREEN}),await f()}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else d({text:"Already authenticated",color:br.GREEN});else d({text:"Already connected",color:br.GREEN});else l("list")},"handleActionSelect"),A=__name(async e=>{if(w)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===w.status&&await e.disconnectServer(w.name),await removeMcpServer({name:w.name,scope:w.scope}),l("list"),await f(),i(e=>Math.min(e,Math.max(0,y.length-2)))}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:br.DIM},"Loading..."));if("confirm-remove"===a&&w)return re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.RED,bold:!0},"Remove ",w.name,"?"),re.createElement(Y,{color:br.DIM},"This will remove the server from ",w.scope," ","config."),re.createElement(Q,{marginTop:1},re.createElement(ft,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:A,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e}," ",t," ")})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&w){const e=[],t="disabled"===w.status,n="connected"===w.status,r="authenticated"===w.status||n;t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"});const o=!t&&(w.config.oauth||"http"===w.config.transport);return o&&r&&e.push({label:"Authenticated",value:"authenticated"}),o&&!r&&e.push({label:"Authenticate",value:"auth"}),t||e.push({label:"Disable",value:"disable"}),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},w.name),re.createElement(Q,null,C(w.status),re.createElement(Y,{color:br.DIM}," ",k(w))),re.createElement(Q,{marginTop:1},re.createElement(ft,{items:e,onSelect:x,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e}," ",t," ")})),u&&re.createElement(Q,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(We,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let P=null;const I=m,M=m+v,R=y.slice(I,M),N=y.length>v;return re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:br.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},"No MCP servers configured."),re.createElement(Y,{color:br.DIM},'Use "cmd mcp add" to add a server.'),re.createElement(Eo,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:br.CYAN,dimColor:!0})):re.createElement(Q,{marginTop:1,flexDirection:"column"},R.map((e,t)=>{const n=I+t,r=e.scope!==P;P=e.scope;const o=n===s;return re.createElement(re.Fragment,{key:e.name},r&&re.createElement(Q,{marginTop:0===t?0:1},re.createElement(Y,{bold:!0},T(e.scope)),re.createElement(Y,{color:br.DIM}," ","(",_(e.scope),")")),re.createElement(Q,null,re.createElement(Y,{color:o?br.WHITE:void 0,backgroundColor:o?zr:void 0,bold:o},e.name),re.createElement(Y,{color:br.DIM,backgroundColor:o?zr:void 0}," · "),C(e.status,o?zr:void 0),re.createElement(Y,{color:"connected"===e.status?br.GREEN:"authenticated"===e.status?br.CYAN:"requires_auth"===e.status?br.YELLOW:br.GRAY,backgroundColor:o?zr:void 0}," ",k(e)," ")))})),N&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",I+1,"–",Math.min(M,y.length)," of"," ",y.length,I>0?" · ↑ more":"",M<y.length?" · ↓ more":"")),u&&re.createElement(Q,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(We,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},0===t.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Bt(),_n(),Xn(),Vr();var hM=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(0),[s,i]=se(!0),[a,l]=se(null);ae(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(Z((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),s)return re.createElement(Q,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:br.DIM},"Loading memory files..."));if(a)return re.createElement(Q,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:br.RED},Re.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return re.createElement(Q,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:br.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},re.createElement(Q,null,re.createElement(Y,{color:br.WHITE,bold:!0},"Select memory to edit:")),re.createElement(Q,{columnGap:4,marginTop:1},re.createElement(Q,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?br.WHITE:br.DIM},r===t?`${Hn} `:" ",e.label))),re.createElement(Q,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?br.WHITE:br.DIM},e.description)))))},"MemorySelector");Bt(),Vr(),Bt(),Xn(),Po(),Vr();var fM={"Interrupted by user":"Interrupted by user","Insufficient credits":qn};function UserMessage({content:e,images:t,imageCount:n=0,ideHint:r}){const o="Interrupted by user"===e,s="Insufficient credits"===e,i=e.startsWith("Error:"),a=o||s||i,l=a&&fM[e]||e,u=null!=t?t.length:n,d=ie(null);null===d.current&&t&&t.length>0&&(d.current=t.map((e,t)=>saveTempImage(e,t+1)));const m=d.current??[];return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{backgroundColor:a?void 0:Rr.BG,paddingRight:1},re.createElement(Y,{color:a?br.RED:Rr.POINTER,bold:!a},Re.pointer),re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:a?br.RED:Rr.FG,wrap:"wrap"},l))),u>0&&re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM},"⎿"," ",Array.from({length:u},(e,t)=>{const n=m[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))),r&&!a&&re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:qr},Rx),re.createElement(Y,{color:br.DIM}," ","Selected ",r.lines," ",1===r.lines?"line":"lines"," from"," ",r.file," in ",r.ide)))}function AutoCompactMessage({content:e}){return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},Re.bullet," ",e))}function ZdrPausedMessage(){return re.createElement(Q,{marginTop:1,marginBottom:1},re.createElement(Y,null,re.createElement(Y,{color:br.DIM},Re.bullet," "),re.createElement(Y,{color:br.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),re.createElement(Y,{color:Fr.CODE},"/configure-models"),re.createElement(Y,{color:br.DIM}," to review · esc to dismiss")))}function TasteSkipMessage(){return re.createElement(Q,{marginTop:1,marginBottom:1},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:vr.BADGE_BG,color:vr.BADGE_FG,bold:!0},$x)),re.createElement(Y,{color:br.DIM}," Skipped. Run "),re.createElement(Y,{color:Fr.CODE},"/learn-taste"),re.createElement(Y,{color:br.DIM}," or "),re.createElement(Y,{color:Fr.CODE},"cmd learn-taste"),re.createElement(Y,{color:br.DIM}," anytime."))}function HookWarningMessage({content:e}){return re.createElement(Q,null,re.createElement(Y,{color:br.YELLOW},Re.warning),re.createElement(Q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.YELLOW},e)))}function HookLineMessage({content:e}){return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return re.createElement(Q,{flexDirection:"column"},void 0!==t&&re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},` ${t}`)),e.map((e,t)=>re.createElement(Q,{key:t,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:qr},Rx),re.createElement(Y,{color:br.DIM,wrap:"wrap"}," ",e)),t?re.createElement(Q,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return re.createElement(Q,{flexDirection:"column"},re.createElement(UserMessage,{content:e}),re.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,null,re.createElement(Y,{color:br.GREEN},Re.tick," Goal achieved"),re.createElement(Y,{color:br.DIM},` (${e} · ${r})`))),re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},"Goal: ",n)))}function GoalStatusMessage({state:e,headline:t,goal:n,detail:r,hint:o}){const s="completed"===e?Re.tick:"paused"===e?"⏸":"idle"===e?Re.circle:Re.bullet,i="completed"===e?br.GREEN:"paused"===e?br.YELLOW:br.DIM;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:i},s," ",t)),re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},n)),r?re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},r)):null,o?re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},o)):null)}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return re.createElement(TasteSkipMessage,null);if(t?.isAutoCompact)return re.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return re.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return re.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return re.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return re.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.GREEN},Re.tick," ",e));if(t?.isGoalAccept)return re.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return re.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return re.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isGoalNotice){const n="cleared"===t.goalNoticeKind?Re.tick:"none"===t.goalNoticeKind?Re.circle:"paused"===t.goalNoticeKind?"⏸":Re.bullet;return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},n," ",e))}return t?.isGoalLine?re.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},Re.bullet," ",e))}__name(UserMessage,"UserMessage"),__name(AutoCompactMessage,"AutoCompactMessage"),__name(ZdrPausedMessage,"ZdrPausedMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(HookLineMessage,"HookLineMessage"),__name(HookLineContinuationMessage,"HookLineContinuationMessage"),__name(HookFrameMessage,"HookFrameMessage"),__name(GoalLineMessage,"GoalLineMessage"),__name(GoalAcceptMessage,"GoalAcceptMessage"),__name(GoalCompleteMessage,"GoalCompleteMessage"),__name(GoalStatusMessage,"GoalStatusMessage"),__name(InfoMessage,"InfoMessage"),Bt(),_n(),bo(),mv(),Go(),Ro(),Co(),Vr(),Bt(),Vr();var yM=bt()?"⠶":"#";function AssistantMessage({content:e}){return re.createElement(Q,null,re.createElement(Y,{color:Nr},yM),re.createElement(Q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=br.GREEN,s=Re.tick,i="default",a=t||"(No output)";n&&(o=br.YELLOW,s=Re.arrowRight,i=br.YELLOW,a="Executing…"),r&&(o=br.RED,s=Re.cross,i=br.RED);const l=le(()=>buildTreeConnectors(a),[a]);return re.createElement(Q,null,re.createElement(Y,{color:o},s),re.createElement(Q,{flexDirection:"column",marginLeft:1},re.createElement(Q,null,re.createElement(Y,{color:br.GRAY},"$ "),re.createElement(Y,{color:o,bold:!0},e)),re.createElement(Q,{columnGap:1,marginLeft:1},re.createElement(Y,{color:qr},l),re.createElement(Y,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?br.YELLOW:void 0,o=le(()=>buildTreeConnectors(e),[e]);return re.createElement(Q,{flexDirection:"column",marginBottom:0,marginTop:-1},re.createElement(Q,{columnGap:1},re.createElement(Y,{color:qr},o),re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:r},e))),t&&re.createElement(Q,{marginLeft:3},re.createElement(Y,{color:br.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return re.createElement(Q,null,re.createElement(Y,{color:br.RED},t?Re.pointer:Re.warning),re.createElement(Q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?re.createElement(Y,{color:br.RED,wrap:"wrap"},e):re.createElement(Markdown,{color:br.RED},e)))}__name(AssistantMessage,"AssistantMessage"),Bt(),Vr(),__name(BashMessage,"BashMessage"),Bt(),Vr(),__name(CommandResultMessage,"CommandResultMessage"),Bt(),Vr(),__name(ErrorMessage,"ErrorMessage"),Bt(),Vr();var wM={connected:{char:Re.tick,color:br.GREEN},installed:{char:Re.tick,color:br.GREEN},up_to_date:{char:Re.tick,color:br.GREEN},needs_reload:{char:Re.circle,color:br.YELLOW},failed:{char:Re.cross,color:br.RED},not_in_ide:{char:Re.circle,color:br.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getStatusHeadline(e,t),i=wM[e];return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,null,re.createElement(Y,{color:i.color},i.char),re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:br.CYAN},o),s&&re.createElement(Y,null,s))),n?.map((e,t)=>re.createElement(Y,{key:t,color:br.DIM}," ",e)))}function ReasoningMessage({content:e,expandedOutput:t,expandKey:n,isStreaming:r=!1}){const o=e?Math.max(1,Math.round(e.length/500)):1,s=Boolean(e),i=(s?e.split("\n"):[]).length,a=`${r?"Thinking…":`Thought for ${o} second${1!==o?"s":""}`}${r&&!t&&i>0?` (${i} line${1!==i?"s":""})`:""}`,l=t&&s,u=!t&&s,d=r&&t&&e.length>560,m=d?e.length-560:0,g=80*Math.floor(m/80),h=d?(e.slice(0,g).match(/\n/g)??[]).length:0,f=d?e.slice(g):e;return re.createElement(Q,{flexDirection:"column",width:"90%"},re.createElement(Q,null,re.createElement(Y,{color:Cr},"✻"," "),re.createElement(Y,{color:Cr},u?`${a} `:a),u&&re.createElement(BracketWrap,{color:br.DIM},`${n}+o to expand`)),l&&d&&re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:br.DIM},h>0?`… (${h} more line${1!==h?"s":""})`:"…")),l&&re.createElement(Q,{marginLeft:2,flexDirection:"column"},re.createElement(Y,{color:Cr,wrap:"wrap",italic:!0},f)))}__name(IDEStatusMessage,"IDEStatusMessage"),Bt(),Vr(),__name(ReasoningMessage,"ReasoningMessage"),Bt(),Bt(),_n();function HelpMessage(){const e=getInvokedCommandName(),t=le(()=>GT.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return re.createElement(Q,{flexDirection:"column",paddingY:1},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:br.GRAY}," v","0.38.7")),re.createElement(Y,{color:br.GRAY},BT)),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Usage"),re.createElement(Q,{paddingLeft:2},re.createElement(Y,null,e," <command> [options]"))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Options"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},WT.map(t=>re.createElement(Q,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(qT)),re.createElement(Y,{color:br.GRAY},t.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Commands"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},VT.map(t=>re.createElement(Q,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(qT)),re.createElement(Y,{color:br.GRAY},t.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Slash Commands"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},t.map(e=>re.createElement(Q,{key:e.key},re.createElement(Y,null,e.key.padEnd(qT)),re.createElement(Y,{color:br.GRAY},e.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Keyboard Shortcuts"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},HT.map(e=>re.createElement(Q,{key:e.key},re.createElement(Y,null,e.key.padEnd(qT)),re.createElement(Y,{color:br.GRAY},e.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Examples"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},QT.map(t=>re.createElement(Q,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(qT)),re.createElement(Y,{color:br.GRAY},t.description))))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.CYAN},Re.pointer),re.createElement(Y,{color:br.GRAY}," ",YT.replace(/cmd/,e))),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{bold:!0},"Links"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},KT.map(e=>re.createElement(Q,{key:e.key},re.createElement(Y,null,e.key.padEnd(qT)),re.createElement(Y,{color:br.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?re.createElement(HelpMessage,null):re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{wrap:"wrap"},re.createElement(Markdown,null,e)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0,n=e.metadata?.ideHint;return re.createElement(UserMessage,{content:e.input,images:t,ideHint:n})}return"assistant"===e.role?re.createElement(AssistantMessage,{content:e.input}):"reasoning"===e.role?re.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?re.createElement(ToolMessage,{name:av(e.name||""),input:e.input,output:e.output||"",isPending:ov(e),hasError:rv(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?re.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:ov(e),hasError:rv(e)}):"system"===e.role?re.createElement(SystemMessage,{content:e.input}):"info"===e.role?re.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?re.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?re.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?re.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName2(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getProviderShortName(e){return e?Sn[e]?.shortLabel??e.slice(0,4):""}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [ctrl+e to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Mr},o),re.createElement(BracketedText,{text:n,color:Mr}),re.createElement(Y,{color:Mr},o))}Vr(),uE(),Ro(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName2,"getModelShortName"),__name(getProviderShortName,"getProviderShortName"),__name(TranscriptDivider,"TranscriptDivider");var SM=re.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentProvider:s,hiddenCount:i=0})=>{const a=i>0?{role:"transcript-divider",count:i}:null,l=[...t?["header"]:[],...a?[a]:[],...e],u=useTerminalWidth(),d=le(()=>DP(u),[u]),m=le(()=>BP(u),[u]),g=le(()=>getPackageJson().version||"0.0.0",[]),h=le(()=>getGitHeaderInfo(),[]),f=le(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?getModelShortName2(o):"sonnet-4.6",w="taste-1",S=le(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=getReasoningEffort(o);return e?` with ${e} effort`:""},[o,n]),E=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO,v=E?" · co":"",C=E&&s?` · ${getProviderShortName(s)}`:"";return re.createElement(J,{items:l,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return re.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:u});if("header"===e)return"compact"===m?re.createElement(Q,{key:"header",marginBottom:1,flexDirection:"row"},re.createElement(Q,{width:jP,flexShrink:0},re.createElement(qP,null,FP)),re.createElement(Q,{flexDirection:"column",marginLeft:2},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Mr}," ","v",g)),re.createElement(Y,{color:Mr},"models: ",y,S," ·"," ",w,v),re.createElement(Y,{color:Mr},f,h&&h.isLocal&&h.branch&&` (${h.branch})`))):re.createElement(Q,{key:"header",marginBottom:1,flexDirection:"column"},re.createElement(qP,null,d.trimEnd()),re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Q,null,re.createElement(Y,{color:Mr},"# "),re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Mr}," v",g)),re.createElement(Y,{color:Mr},"# models: ",y,S," · ",w,C,v),re.createElement(Q,null,re.createElement(Y,{color:Mr},"# ",f,h&&h.isLocal&&h.branch&&re.createElement(Y,{color:Mr}," ","(branch:"," ",h.branch,")")))));const t=e,n=renderFeedEntry(t,r);return re.createElement(Q,{key:t.id,paddingBottom:1,width:"90%"},n)})});Bt(),mv(),No(),Vr();var bM=oe(__name(function LiveAgentStatusInner2({entry:e}){const t=av(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=se(".");return ae(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),re.createElement(Q,{flexDirection:"column",marginBottom:1,width:"90%"},re.createElement(Q,null,re.createElement(Y,{backgroundColor:Ar.BG,color:Ar.FG,bold:!0},` ${t} `),o&&re.createElement(Y,null," (",o,")")),re.createElement(Q,{columnGap:1,marginLeft:1},re.createElement(Y,null,"⎿"," "),re.createElement(Y,{color:br.GRAY},"Running (",formatTime2(i)," |"," ",formatTokens(s),")",l)),a.length>0&&re.createElement(Q,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=av(e.name);return re.createElement(Q,{key:t,columnGap:1},re.createElement(Y,{color:br.GRAY},"⎿"),re.createElement(Y,{color:br.GRAY}," ",n),e.input&&re.createElement(Y,{color:br.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),EM=oe(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:re.createElement(bM,{entry:e})},"LiveAgentStatus"));Bt(),_n(),bo(),Co(),No(),Ro(),Vr(),Bt(),Vr();var vM={low:"Fast responses with lighter reasoning",medium:"Balances speed and reasoning depth for everyday tasks",high:"Greater reasoning depth for complex problems",xhigh:"Extra reasoning depth for complex problems",max:"Maximum reasoning budget for the hardest problems"},CM={value:void 0,label:"Default",description:"Use the provider default reasoning level"},kM=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=le(()=>[CM,...t.map(e=>({value:e,label:e,description:vM[e]}))],[t]),i=le(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),a=__name((e,t)=>`${e+1}. ${t}`,"labelText"),l=le(()=>Math.max(...s.map((e,t)=>a(t,e.label).length))+4,[s]),{cursor:u}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:i,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Er,bold:!0},`Select reasoning effort for ${e}`)),re.createElement(Q,{flexDirection:"column"},s.map((e,t)=>{const r=t===u,o=e.value===n;return re.createElement(Q,{key:e.label},re.createElement(Y,{color:r||!o?br.WHITE:br.GREEN,backgroundColor:r?zr:void 0,bold:r||o},a(t,e.label).padEnd(l)),re.createElement(Y,{color:r?br.WHITE:br.DIM,backgroundColor:r?zr:void 0},e.description," "),o&&re.createElement(Y,{color:br.GREEN}," ",Re.tick))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑/↓ navigate · enter to select · esc to go back")))},"ReasoningEffortSelector");ir();var TM="Loading plan info…",_M=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups2(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,_M);e.length>0&&n.push({...r,models:e})}return n}function flattenGroups(e){const t=[];for(const n of e)for(const e of n.models)t.push({providerId:n.providerId,model:e});return t}function groupByModelProvider2(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups2,"searchGroups"),__name(flattenGroups,"flattenGroups"),__name(groupByModelProvider2,"groupByModelProvider");var xM=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0,refreshBanner:a})=>{const[l,u]=se(""),[d,m]=se(null),[g,h]=se(()=>new Set),f=le(()=>isInternalTeamFlagEnforced(),[]),y=le(()=>f?bn:groupByModelProvider2(En.flatMap(e=>e.models),Sn["command-code"].id),[f]),w=le(()=>searchGroups2(y,l),[y,l]),S=le(()=>flattenGroups(w),[w]),[E,v]=se(0),C=useTerminalHeight()-1,k=Math.max(4,C-14-2*w.length),T=void 0!==o,_=le(()=>T?null:getCachedBillingContext(),[T]),[x,A]=se(_),[P,I]=se(!T&&!_);ae(()=>{if(T)return;if(x)return;let e=!0;return getBillingContext().then(t=>{e&&(A(t),I(!1))}),()=>{e=!1}},[T,x]);const M=!T&&!0===x?.fetchFailed,R=T?o:x?.planId??null,N=T?s:x?.purchasedCredits??0,L=T?i:x?.freeCredits??0,$=f?Sn.anthropic.id:Sn["command-code"].id,D=r??$,O=n?Math.max(0,S.findIndex(e=>e.model.id===n&&e.providerId===D)):0,[F,j]=se("model"),[U,B]=se(null),{cursor:q,error:z,setError:H}=useListNavigation({items:S,onSelect:__name(t=>{const n=getSupportedEfforts(t.model.id);if(n&&n.length>0)return B(t),void j("effort");e(t.model.id,t.providerId)},"onSelect"),onCancel:t,initialIndex:O,searchQuery:l,onSearchChange:u,isActive:"model"===F,validate:__name(e=>{if(g.has(e.providerId))return`Run /provider to authenticate with ${getProviderConfig(e.providerId)?.displayName??e.providerId} first`;if(d&&!f){const t=Sn[d]?.supportedModelProviders;if(t&&!t.includes(e.model.provider))return`${Sn[d]?.label??d} does not support ${e.model.provider} models. Switch provider via /provider.`}if(P)return TM;const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:R,purchasedCredits:N,freeCredits:L});return t.allowed?null:t.errorMessage??"Model not available for your plan"},"validate")});ae(()=>{v(e=>clampScrollOffset({cursor:q,total:S.length,maxVisible:k,currentOffset:e}))},[q,S.length,k]);const W=ie(!1),G=__name(t=>{if(!U||W.current)return;W.current=!0;const{model:r,providerId:o}=U,s=getReasoningEffort(r.id),i=t!==s,l=r.id===n;(async()=>{try{i&&(await setReasoningEffort({modelId:r.id,effort:t}),l&&a?.())}catch(e){dlog(`[Model] Failed to persist reasoning effort: ${e}`)}finally{e(r.id,o)}})()},"handleEffortSelect"),V=__name(()=>{W.current||(B(null),j("model"))},"handleEffortCancel");if(ae(()=>{if(P)return;if(z!==TM)return;const e=S[q];if(!e||M)return void H(null);const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:R,purchasedCredits:N,freeCredits:L});H(t.allowed?null:t.errorMessage??"Model not available for your plan")},[P,M,z,H,S,q,R,N,L]),ae(()=>{(async()=>{await isOAuthEnforced()&&m(await getConfiguredProvider())})()},[]),ae(()=>{(async()=>{const e=new Set(y.map(e=>e.providerId)),t=new Set;for(const n of e){const e=getProviderConfig(n);e?.requiresAuth&&e.checkAuth&&(await e.checkAuth()||t.add(n))}h(t)})()},[y]),"effort"===F&&U){const e=getSupportedEfforts(U.model.id)??[];return re.createElement(kM,{modelLabel:U.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(U.model.id),onSelect:G,onCancel:V})}const K=E,J=E+k;let X=0;const Z=w.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:X,windowStart:K,windowEnd:J});return X+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),ee=S.length>k;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Select model")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{dimColor:!0},f?"Select a model and provider. Sets the default for new sessions; other open sessions are unaffected. Provider is saved.":"Switch between Command Code models. Sets the default for new sessions; other open sessions are unaffected.")),re.createElement(Q,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(QP,{query:l,resultCount:l?S.length:void 0,placeholder:"Type to search models..."})),0===S.length?re.createElement(Q,{marginY:1},re.createElement(Y,{color:br.GRAY},'No models match "',l,'"')):re.createElement(Q,{flexDirection:"column"},Z.map(({group:e,groupWindow:t},r)=>re.createElement(Q,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},f?re.createElement(Y,{bold:!0,color:Er},e.label):re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(NI,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===q,isCurrent:r.id===n&&e.providerId===D,showProviderLabel:!!f&&void 0}))))),ee&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",K+1,"–",Math.min(J,S.length)," of ",S.length,K>0?" · ↑ more":"",J<S.length?" · ↓ more":"")),z&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},z)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"type to search · ↑/↓ navigate · enter to select"),l?re.createElement(Y,{color:br.DIM}," · esc to clear"):re.createElement(Y,{color:br.DIM}," · esc to cancel")))},"ModelSelector");Bt(),bo(),Co(),ir();var AM=__name(({currentModel:e,onClose:t,refreshBanner:n})=>{const r=getSupportedEfforts(e)??[],o=findModelById(e)?.label??getModelDisplayName(e),s=ie(!1),i=__name(r=>{if(s.current)return;s.current=!0;const o=r!==getReasoningEffort(e);(async()=>{try{o&&(await setReasoningEffort({modelId:e,effort:r}),n())}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),a=__name(()=>{s.current||t()},"handleCancel");return re.createElement(kM,{modelLabel:o,supportedEfforts:r,currentEffort:getReasoningEffort(e),onSelect:i,onCancel:a})},"EffortSelector");Bt(),Ro(),Vr();var PM=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,i=n&&-1===s;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Select AI Provider")),n&&re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:br.DIM},"Current: "),re.createElement(Y,{color:br.GREEN},getProviderDisplayName(n)),i&&re.createElement(Y,{color:br.YELLOW}," ","[OAuth enforced]"))),re.createElement(Q,{marginBottom:0},re.createElement(Y,{color:br.DIM},"Available Providers:")),re.createElement(ft,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>re.createElement(Y,{color:e?br.CYAN:br.GRAY,bold:e&&isLightTheme()},e?Re.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.CYAN:br.DIM,bold:e&&isLightTheme()},` ${t}`)}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=se(0);if(ae(()=>{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 re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Or,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Bt(),Vr(),__name(RetryMessage,"RetryMessage"),Bt(),Rs(),Xn(),Vr();var IM=[{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"}],MM=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=le(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=se(Math.max(0,r.length-1)),[i,a]=se(Math.max(0,r.length-8)),[l,u]=se("checkpoint"),[d,m]=se(null),[g,h]=se(0),f=le(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),y=le(()=>f?IM:IM.filter(e=>"conversation"===e.mode),[f]);if(ae(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),Z((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[o]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:Er,bold:!0},"Rewind"),re.createElement(Y,{color:br.DIM},"No checkpoints available. Start a conversation to create checkpoints."),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to close")));if("mode"===l&&d)return re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:Er,bold:!0},"Rewind"),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Restore to: "),re.createElement(Y,{color:br.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),re.createElement(Q,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return re.createElement(Q,{key:e.mode,flexDirection:"column"},re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:n?Er:void 0},n?`${Hn} `:" "),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:n?Er:br.WHITE},e.label),re.createElement(Y,{color:br.DIM},e.description))),!r&&re.createElement(Y,null," "))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Enter"),re.createElement(Y,{color:br.DIM}," to confirm, "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to go back")));const w=r.slice(i,i+8);return re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:Er,bold:!0},"Rewind"),re.createElement(Y,{color:br.DIM},"Select a checkpoint to restore your session"),r.length>8&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),re.createElement(Q,{marginTop:1}),re.createElement(Q,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return re.createElement(Q,{key:e.messageId,flexDirection:"column"},re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:s?Er:void 0},s?`${Hn} `:" "),re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:s?Er:br.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),re.createElement(Y,{color:br.DIM}," • "),re.createElement(Y,{color:br.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),re.createElement(Y,{color:br.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&re.createElement(Y,null," "))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Enter"),re.createElement(Y,{color:br.DIM}," to select, "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to cancel")))},"RewindSelector");Bt(),Vr();var RM=[{label:"Complete brief",desc:"If the target, goal, audience, or artifact is clear, act without asking."},{label:"Composition",desc:"Choose layout from the work pattern: monitor, operate, compare, configure, learn, decide, or explore."},{label:"Scope",desc:"Broad prompts get the full mode pass. Narrow prompts stay narrow."},{label:"Truth",desc:"Only claim changes that exist in files and are visible or verifiable."},{label:"Templates",desc:"design-html and report-html are documentation templates, not UI inspiration."},{label:"Reports",desc:"Follow-up modes read markdown reports, apply relevant findings, then still run their own full mode pass."}],NM=['/design redesign "Make this dashboard feel like an operator console"','/design motion "Animate the whole page and add missing interactions"','/design checkup "Audit this UI and generate the design report"','/design "Build a landing page for a privacy-first contract review tool"'],LM=__name(({onCancel:e})=>(Z((t,n)=>{n.escape&&e()}),re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingRight:2},re.createElement(Q,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Use"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},re.createElement(Y,{color:br.DIM},'/design <mode> "target or request"'),re.createElement(Y,{color:br.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),re.createElement(Q,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Modes"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},WA.map(e=>re.createElement(Q,{key:e.name,columnGap:2},re.createElement(Q,{width:18,flexShrink:0},re.createElement(Y,{color:br.CYAN},"/design ",e.name)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},e.description)))))),re.createElement(Q,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Working rules"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},RM.map(e=>re.createElement(Q,{key:e.label,columnGap:2},re.createElement(Q,{width:16,flexShrink:0},re.createElement(Y,{color:br.CYAN},e.label)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},e.desc)))))),re.createElement(Q,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Quick examples:"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},NM.map(e=>re.createElement(Y,{key:e,color:br.DIM},e)))),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Bt(),ir(),Bt(),Bt();var $M=__name(e=>{const[t,n]=se(e),[r,o]=se(null);return ae(()=>{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 FC.on("reset",t),FC.on("new-event",r),()=>{FC.off("reset",t),FC.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new hS({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o,s;try{const e=await getOAuthCredentials({provider:n});o=e.token,s=e.oauthProvider,validateOAuthToken({token:o,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[Wt.PROJECT_SLUG]:fv.getCurrentProjectDirName(),[Wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(i[Wt.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Wt.OAUTH_PROVIDER]=s)),{request:t,headers:i}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}function buildObserverPrompt(e,t){return`Produce ${t} varied observations for these prompts:\n\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),FC.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()}`),FC.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){const r=getTasteObserverModel({sessionModel:getConfiguredModel()});dlog(`[ObserverAPI] calling ${Gt.ALPHA.GENERATE} with model: ${r}`);const o={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:r,system:"You scan prompts and produce casual observations like a dev friend glancing at someone's work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words per observation\n- one observation per line\n- sound human, not robotic\n- output only the observations, no preamble",max_tokens:200,temperature:.7,stream:!0},threadId:Me()},s=await e.post({endpoint:Gt.ALPHA.GENERATE,body:o,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const i=createInsightEmitter();await consumeSSEStream(s,{onText:__name(e=>{i.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${i.getChunkCount()} chunks received`),i.emitRemaining(),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(FC.observerHasRun)return;FC.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r={...n,[Wt.SESSION_ID]:`observer-${Me()}`},o=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${o.length} batches`);const s=Math.min(o.length,6);for(let t=0;t<s;t++){if(FC.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const n=o[t];try{await processBatch(e,r,n,t+1,o.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),FC.addEvent({type:"progress",message:"Continuing without live observations..."})}}Bt(),Bt(),LS(),VS(),ir(),Bt(),_n(),ir(),Bt(),Bt(),_n(),LS(),VS(),Sv(),ir(),Co(),No(),__name(createRequestClient,"createRequestClient"),Bt(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Bt(),Bt(),ir(),os(),Bt(),_n(),Co(),AE(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var DM=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(w.homedir(),".claude","projects");await C.access(r);const o=getProjectDirName2(process.cwd());dlog(`[Import] scanning project: ${o}`);const s=(await C.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await C.stat(s)).isDirectory())continue;const r=(await C.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),i=await C.stat(r),a=o.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{FC.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&FC.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async findCursorSessions(e=0){try{FC.addEvent({type:"progress",message:"Scanning Cursor sessions..."});const t=await findCursorSessions(process.cwd(),e);return dlog(`[Import] found ${t.length} Cursor sessions`),t}catch(e){return dlog("[Import] no cursor sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await C.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[],o=[];try{FC.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),i=s.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,o=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length},{name:"Cursor",count:n.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);FC.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${o.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&s.push({agent:"cursor",sessionIds:n.map(e=>e.id),displayName:"Cursor"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:r,learnedSessions:a+l+u,agentSessions:s,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));o.push(...e)}const y=n.length+r.length+o.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${o.length})`),FC.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:o,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){FC.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});FC.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const s=getApiBaseUrl(),i=new hS({baseUrl:s});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&FC.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),s=new fx({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await s.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),FC.markLearningComplete(),await E,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}if(o.length>0){const e=o.map(e=>e.id);await markSessionsAsLearned("cursor",e),dlog(`[Import] marked ${e.length} cursor sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const l=await this.extractLearningSummary(),u=[];if(n.length>0&&u.push(`Claude Code (${n.length})`),r.length>0&&u.push(`Codex (${r.length})`),o.length>0&&u.push(`Cursor (${o.length})`),!a){const s=FC.getEvents().some(e=>"error"===e.type&&e.message?.toLowerCase().includes("insufficient credits")),i="Learning failed - sessions not marked as learned";return e.push(i),s||FC.addEvent({type:"error",message:i}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}return FC.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),FC.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const t=e.join(process.cwd(),".commandcode","taste","taste.md"),n=await C.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},OM=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),FM=__name(e=>{const[t,n]=se({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return ae(()=>{FC.reset(),FC.markImportStarted(),(async()=>{try{const t=await Promise.race([DM.importAndLearn(),OM(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");Bt();var jM=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");Bt(),ir();var UM=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=se(null),[o,s]=se(null),i=ie(!1);return ae(()=>{if(i.current)return;let n=null;return(async()=>{try{i.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{FC.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{FC.reset(),e()}}Bt(),ir(),Bt(),ir(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var BM=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=ie(n),o=ce(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ce(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ce(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ce(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ce(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Bt(),ir();var qM=__name(({conditions:e,autoLearn:t})=>{const[n,r]=se("checking"),o=ie(!1);return ae(()=>{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]),ae(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Bt(),Bt(),Vr();var zM=__name(({error:e})=>re.createElement(Q,{padding:1},re.createElement(Q,{flexDirection:"column",borderColor:br.RED,padding:1},re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Error initializing onboarding: ",e)),re.createElement(Q,null,re.createElement(Y,null,"Continuing without onboarding...")))),"OnboardingError");Bt(),Bt(),Vr();var HM=__name(()=>re.createElement(Y,null,"Skip"),"SkipOptionText"),WM=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=se(1);return Z((e,t)=>{t.escape?r():"n"!==e&&"N"!==e?t.upArrow||t.downArrow?s(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===o?n():r()):r():n():dismissOnboardingForeverForProject().then(()=>r())}),re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:vr.TEXT,paddingX:1,paddingY:0},re.createElement(Y,{color:vr.TEXT,bold:!0},"Build Your Coding Taste"),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),re.createElement(Q,{marginTop:1},re.createElement(Y,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:1===o?vr.TEXT:br.GRAY},1===o?Re.pointer:" "," 1. Yes, learn (recommended)")),re.createElement(Q,null,re.createElement(Y,{color:2===o?vr.TEXT:br.GRAY},2===o?Re.pointer:" "," 2."," ",re.createElement(HM,null)))),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑↓ · "),re.createElement(Y,{color:Fr.CODE},"enter"),re.createElement(Y,{color:br.DIM}," ok · "),re.createElement(Y,{color:Fr.CODE},"esc"),re.createElement(Y,{color:br.DIM}," skip · "),re.createElement(Y,{color:Fr.CODE},"n"),re.createElement(Y,{color:br.DIM}," never")))},"ImportChoice");Bt(),Bt(),Vr();var GM=__name(({error:e})=>re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:br.RED,paddingX:2,paddingY:1,marginBottom:2},re.createElement(Y,{color:br.RED,bold:!0},"Oops, something went wrong:"),re.createElement(Q,{marginTop:1},re.createElement(Y,null,e))),"ErrorSection");Bt(),Bt(),Vr(),Bt(),Bt(),Bt(),Vr(),Bt(),Vr();var VM=__name(()=>re.createElement(Y,{backgroundColor:vr.BADGE_BG,color:vr.BADGE_FG},$x),"TasteBadge");Bt(),Vr(),Bt();var KM=["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"],QM="⎿",YM=__name(()=>{const[e,t]=se(()=>Math.floor(Math.random()*KM.length));return ae(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*KM.length))},2e3);return()=>clearInterval(e)},[]),re.createElement(Y,{color:br.YELLOW},KM[e],"...")},"PulsingText");Bt(),Vr();var JM=[Re.bullet,Re.squareSmallFilled,Re.lozenge,Re.star,Re.triangleRight,Re.triangleUp,Re.circleFilled,Re.pointer],XM=__name(e=>String(e).padStart(3," "),"padNum"),ZM=__name(e=>JM[e%JM.length],"getSymbol"),eR=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${XM(t)} ↓${XM(n)} (↑↓ scroll)`,"buildStatusLine"),tR=__name(({insights:e})=>{const[t,n]=se(0),[r,o]=se(!0),s=e.length,i=s>10,a=Math.max(0,s-10);if(ae(()=>{r&&i&&n(a)},[s,r,i,a]),Z((e,t)=>{if(i)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&o(!0),t}))}),0===s)return null;const l=e.slice(t,t+10),u=t,d=s-t-10;return re.createElement(Q,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&re.createElement(Y,{color:br.DIM},eR(s,u,d,r)),l.map((e,n)=>{const r=t+n;return re.createElement(Q,{key:r,marginBottom:0},re.createElement(Y,{color:br.DIM},ZM(r)," ",e))}))},"ScrollableInsights");Bt(),Vr();var nR=__name(()=>{const[e,t]=se(!0);return ae(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),re.createElement(Y,{color:br.YELLOW},e?Re.circleFilled:Re.circle)},"PulsingDot"),rR=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return re.createElement(Q,{flexDirection:"column",marginBottom:0},re.createElement(VM,null),re.createElement(Q,{marginTop:0},re.createElement(Y,{color:br.DIM},QM),re.createElement(Q,{marginLeft:2},a?re.createElement(Y,{color:vr.TEXT},"learned your coding taste"):re.createElement(YM,null))));const u=__name(()=>r?re.createElement(Y,{color:_r.BG},Re.square):n?re.createElement(nR,null):re.createElement(Y,{color:br.DIM},Re.circle),"getStatusIcon"),d=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||d?re.createElement(Q,{flexDirection:"column",marginBottom:0},(n||r)&&re.createElement(Q,{marginBottom:0},re.createElement(Q,{marginRight:1},u()),re.createElement(Y,{color:r?br.WHITE:n?br.YELLOW:br.DIM},e)),r&&t&&(!l||0===l.learningCount)&&re.createElement(Q,{marginLeft:3,marginBottom:0},re.createElement(Y,{color:br.DIM},t)),o.length>0&&re.createElement(Q,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>re.createElement(Y,{key:t,color:br.DIM},`${Re.bullet} ${e}`))),s.length>0&&re.createElement(tR,{insights:s}),r&&l&&l.learningCount>0&&re.createElement(Q,{flexDirection:"column",marginLeft:1,marginBottom:0},re.createElement(Q,{marginBottom:1,flexDirection:"row"},re.createElement(Y,null,QM),re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:vr.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),re.createElement(Q,{flexDirection:"column",marginLeft:1},re.createElement(Y,{color:br.DIM},Re.pointerSmall," Stored in ",l.storage),re.createElement(Y,{color:br.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),oR=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return re.createElement(Q,{flexDirection:"column",marginBottom:1},e.map((e,n)=>re.createElement(Q,{key:e.id,marginLeft:0===n?0:3},re.createElement(rR,{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"),sR=__name(({steps:e})=>re.createElement(oR,{steps:e}),"ProgressSection");Bt(),Vr();var iR=__name(({isImporting:e=!1,waitingForInput:t=!1})=>re.createElement(re.Fragment,null,e&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"ESC to cancel")),t&&re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Bt();var aR=[{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"}}],lR=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=$M(aR),{isImporting:s,waitingForInput:i,error:a}=FM(t);return jM({onEscape:__name(()=>{i&&((a||o)&&n?n():e())},"onEscape"),onEnter:__name(()=>{i&&((a||o)&&n?n():e())},"onEnter"),enabled:s||i}),re.createElement(Q,{flexDirection:"column",padding:1},o&&re.createElement(GM,{error:o}),!o&&re.createElement(sR,{steps:r}),re.createElement(iR,{isImporting:s,waitingForInput:i}))},"ImportProgress"),cR=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?re.createElement(WM,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?re.createElement(lR,{onComplete:r,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),uR=__name(({onComplete:e,autoLearn:t=!1})=>{ae(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=UM({autoLearn:t,onShouldSkip:e}),{step:s,setStep:i}=qM({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=BM({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?re.createElement(zM,{error:r}):"done"===s?null:re.createElement(cR,{step:s,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");Bt(),Co(),Vr();var dR=[{label:"Dark theme",value:"dark",description:"Use purple accent colors on dark backgrounds."},{label:"Light theme",value:"light",description:"Use higher-contrast colors for white terminal backgrounds."}],mR=__name(({onSelect:e,onCancel:t})=>{const[n,r]=se(null);ae(()=>{r(getCliTheme())},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(Z((e,n)=>{n.escape&&t()}),null===n)return null;const s=dR.findIndex(e=>e.value===n);return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Select a theme")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Choose the color palette for this terminal.")),re.createElement(ft,{items:dR,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>re.createElement(Y,{color:e?br.CYAN:br.GRAY,bold:e&&isLightTheme()},e?Re.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=dR.find(e=>e.label===t),o=r?.value===n,s=dR.findIndex(e=>e.label===t);return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:e?br.CYAN:o?br.GREEN:br.DIM,bold:e&&isLightTheme()},` ${s+1}. ${r?.label??t}`),o&&re.createElement(Y,{color:br.GREEN}," ",Re.tick)),re.createElement(Y,{color:br.DIM},` ${r?.description??""}`))}}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to cancel")))},"ThemeSelector");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const o=[];for(const e of n)if(o.unshift(e),r-=getEntryCharCount(e),r<=0)break;return o}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var pR=oe(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:i,tasteOnboardingEntryId:a,autoLearnTaste:l,showTasteSkipBanner:u,showZdrNotice:d,retryAttempt:m,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,showFileList:w,setShowFileList:S,showProviderSelector:E,showModelSelector:v,showEffortSelector:C,showMemorySelector:k,showMcpManager:T,showAgentsConfig:_,showRewindSelector:x,showLoginOverlay:A,showUsageOverlay:P,showAddDirModal:I,showCompactModeSelector:M,showConfigureModels:R,setShowConfigureModels:N,showThemeSelector:L,authComponentInfo:$,status:D,currentProvider:O,currentModel:F,showProviderNotification:j,shareInfo:U,showShareNotification:B,unshareNotificationMessage:q,updateStatus:z,updateFailedInfo:H,creditWarning:W,permissionMode:G,hintMessage:V,pendingExitKey:K,tasteLearningEnabled:J,interactionTokens:X,contextUsage:Z,historyManagerRef:ee,executionState:te,contextEngineRef:ne,onSubmit:oe,onCommand:se,onToggleAutoAccept:ie,onResetPendingExitKey:ae,onDoubleEscapeEmpty:ue,onTasteOnboardingComplete:de,permissionPanel:me,questionPanel:pe,designSuggestionPanel:ge,onRewindSelect:he,onRewindCancel:fe,onLoginComplete:ye,onLoginCancel:we,setShowProviderSelector:Se,setShowModelSelector:be,setShowEffortSelector:Ee,setShowMemorySelector:ve,setShowMcpManager:Ce,setShowAgentsConfig:ke,setShowAddDirModal:Te,setShowUsageOverlay:_e,handleProviderSelect:xe,handleProviderCancel:Ae,handleModelSelect:Pe,handleModelCancel:Ie,handleCompactModeSelect:Me,handleCompactModeCancel:Re,handleThemeSelect:Ne,handleThemeCancel:Le,handleAuthSuccess:$e,handleAuthCancel:De,showDesignGuide:Oe,setShowDesignGuide:Fe}){const je=le(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Ue=ce(()=>Fe(!1),[Fe]),Be=useTerminalWidth(),qe=le(()=>"off"===i?je:getBudgetedFeed(je,"limited"===i?15e3:5e4),[je,i]),ze=le(()=>"off"===i?0:Math.max(0,je.length-qe.length),[je.length,qe.length,i]),He=le(()=>0===ze?qe:qe.filter(e=>"user"!==e.role),[qe,ze]),We=ce(()=>ke(!1),[ke]),Ge=ce(()=>ve(!1),[ve]),Ve=ce(()=>Ce(!1),[Ce]),Ke=ce(()=>Te(!1),[Te]),Qe=ce(()=>be(!0),[be]),Ye=ce(()=>Ee(!1),[Ee]),Je=ce(()=>{hardResetForResize(),s(e=>e+1)},[s]),Xe=!("off"!==i||me||pe||ge||E||v||C||$||k||T||_||x||A||P||I||M||R||L||Oe||a);return re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(SM,{staticKey:o,feed:He,showHeader:!0,expandedToolOutput:"off"!==i,currentModel:F,currentProvider:O,hiddenCount:ze}),a&&re.createElement(uR,{onComplete:de,autoLearn:l}),u&&re.createElement(TasteSkipMessage,null),d&&re.createElement(ZdrPausedMessage,null),t.map(e=>e.metadata?.isAgent?re.createElement(EM,{key:e.id,entry:e}):re.createElement(Q,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==i))),re.createElement(RetryMessage,{attempt:m}),ge,pe,me,"off"!==i&&re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"─".repeat(Be))),re.createElement(Q,{paddingRight:1},re.createElement(Y,{backgroundColor:_r.BG,color:_r.FG,bold:!0},`${Lx}DETAILED TRANSCRIPT${Lx}`),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+o"),re.createElement(Y,{color:br.DIM}," to toggle"),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+e"),re.createElement(Y,{color:br.DIM}," ","to"," ","limited"===i?"show all":"collapse"),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{bold:!0},"esc"),re.createElement(Y,{color:br.DIM}," to exit"))),Xe&&re.createElement(mM,{queuedMessages:n,isProcessing:r,executionState:te,status:D,input:g,setInput:h,onSubmit:oe,showFileList:w,setShowFileList:S,fileSearchQuery:f,setFileSearchQuery:y,onCommand:se,outputTokens:X,contextUsage:Z,tasteLearning:J,shareInfo:U,showShareNotification:B,unshareNotificationMessage:q,updateStatus:z,updateFailedInfo:H,creditWarning:W,currentProvider:O,currentModel:F,showProviderInfo:j,permissionMode:G,onToggleAutoAccept:ie,hintMessage:V,historyManager:ee.current,pendingExitKey:K,onResetPendingExitKey:ae,onDoubleEscapeEmpty:ue,retryAttempt:m,onAltP:Qe,renderKey:o}),E&&re.createElement(Q,{marginY:1},re.createElement(PM,{onSelect:xe,onCancel:Ae,currentProvider:O})),v&&re.createElement(Q,{marginY:1},re.createElement(xM,{onSelect:Pe,onCancel:Ie,currentModel:F,currentProvider:O,refreshBanner:Je})),C&&re.createElement(Q,{marginY:1},re.createElement(AM,{currentModel:F,onClose:Ye,refreshBanner:Je})),Oe&&re.createElement(Q,{marginY:1},re.createElement(LM,{onCancel:Ue})),M&&re.createElement(Q,{marginY:1},re.createElement(RI,{onSelect:Me,onCancel:Re})),R&&re.createElement(Q,{marginY:1},re.createElement(DI,{onClose:()=>N(!1)})),L&&re.createElement(Q,{marginY:1},re.createElement(mR,{onSelect:Ne,onCancel:Le})),_&&re.createElement(Q,{marginY:1},re.createElement(II,{onCancel:We})),k&&re.createElement(Q,{marginY:1},re.createElement(hM,{onClose:Ge})),T&&re.createElement(Q,{marginY:1},re.createElement(gM,{onClose:Ve})),x&&ne.current&&re.createElement(Q,{marginY:1},re.createElement(MM,{checkpoints:ne.current.listCheckpoints(),onSelect:he,onCancel:fe})),$&&re.createElement(Q,{marginY:1},re.createElement($.Component,{onSuccess:$e,onCancel:De})),A&&re.createElement(Q,{marginY:1},re.createElement(pM,{onComplete:ye,onCancel:we})),I&&re.createElement(Q,{marginY:1},re.createElement(gI,{onClose:Ke})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:v,creditWarning:C,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:A,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return re.createElement(dP,{staticKey:o.staticKey,onTrust:k,onExit:T});if(o.showSessionSelector)return re.createElement(hP,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!s.projectTrusted)return null;const I=o.pendingDesignSuggestion?re.createElement(lP,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{f(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,M=a.pendingQuestion?re.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,R=a.pendingPermission?re.createElement(PP,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null,{closeFullScreenOverlay:N}=o;return o.showLearningFeed?re.createElement(GP,{onClose:()=>N(o.setShowLearningFeed),onExit:()=>i.setShouldExit(!0)}):o.showTasteConfig?re.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>N(o.setShowTasteConfig),loadTasteStatus:P}):o.showSkillsConfig?re.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>N(o.setShowSkillsConfig)}):o.showUsageOverlay?re.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>N(o.setShowUsageOverlay)}):o.showContextView?re.createElement(ContextConfigView,{staticKey:o.staticKey,contextEngineRef:u,onClose:()=>N(o.setShowContextView),setInput:w}):o.showStatusView?re.createElement(StatusConfigView,{staticKey:o.staticKey,onClose:()=>N(o.setShowStatusView),setInput:w}):re.createElement(pR,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:o.staticKey,setStaticKey:o.setStaticKey,transcriptMode:o.transcriptMode,tasteOnboardingEntryId:s.tasteOnboardingEntryId,autoLearnTaste:s.autoLearnTaste,showTasteSkipBanner:o.showTasteSkipBanner,showZdrNotice:o.showZdrNotice,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:o.showFileList,setShowFileList:o.setShowFileList,showProviderSelector:o.showProviderSelector,showModelSelector:o.showModelSelector,showEffortSelector:o.showEffortSelector,showMemorySelector:o.showMemorySelector,showMcpManager:o.showMcpManager,showAgentsConfig:o.showAgentsConfig,showRewindSelector:o.showRewindSelector,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,showConfigureModels:o.showConfigureModels,setShowConfigureModels:o.setShowConfigureModels,showThemeSelector:o.showThemeSelector,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:v,creditWarning:C,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:A,permissionPanel:R,questionPanel:M,designSuggestionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleThemeSelect:g.handleThemeSelect,handleThemeCancel:g.handleThemeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView");var gR=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u,sessionTitleHolder:d})=>{const{exit:m}=te(),{stdout:g}=X();ae(()=>{prefetchBillingContext()},[]);const[h,f]=se(""),[y,w]=se(""),S=ie(!1),E=ie(!1),v=ie(null),C=ie(null),k=useUiOverlays(),T=useFeed(),_=useSession(),x=useStatus(s),A=useAuth(),P=usePendingOps(),I=useOnboarding(),M=useExit(),{executeBash:R,executionState:N}=B_(),L=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:x.setStatus,contextEngineRef:C}),{createContextEngineCallbacks:$}=useContextEngine({sessionId:_.sessionId,sessionLoaded:_.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:I.projectTrusted,setFeed:T.setFeed,setLiveEntries:T.setLiveEntries,setQueuedMessages:T.setQueuedMessages,queuedMessagesRef:T.queuedMessagesRef,setStatus:x.setStatus,pinnedStatusRef:x.pinnedStatusRef,setRetryAttempt:x.setRetryAttempt,setInteractionTokens:x.setInteractionTokens,setContextUsage:x.setContextUsage,setCurrentProvider:A.setCurrentProvider,shareInfoRef:x.shareInfoRef,permissionsService:L.permissionsService,permissionModeRef:L.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:C}),{onCommand:D}=useCommandCtx({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,permissionState:L,contextEngineRef:C,isSubmittingRef:S,executeBash:R,createContextEngineCallbacks:$,setInput:f}),{loadTasteStatus:O,loadCurrentProvider:F,onSubmit:j}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:g,feedState:T,sessionState:_,statusState:x,authState:A,onboarding:I,uiOverlays:k,permissionState:L,contextEngineRef:C,isSubmittingRef:S,initialPromptSubmittedRef:E,historyManagerRef:v,executeBash:R,createContextEngineCallbacks:$,setInput:f,onCommand:D});useLifecycle({exit:m,feedState:T,exitState:M,statusState:x,authState:A,onboarding:I,uiOverlays:k,skipOnboarding:l,contextEngineRef:C,sessionTitleHolder:d});const{handleToggleAutoAccept:U,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,handleTrust:z,handleNoTrust:H}=useHandlers({resume:e,feedState:T,onboarding:I,uiOverlays:k,exitState:M,pendingOps:P,permissionState:L,statusState:x,authState:A,contextEngineRef:C,loadTasteStatus:O,loadCurrentProvider:F,setInput:__name(e=>f(e),"setInput")}),W=useMainActionCallbacks({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,permissionState:L,contextEngineRef:C,createContextEngineCallbacks:$,setInput:f}),{creditWarning:G}=useCreditWarning({interactionTokens:x.interactionTokens});return renderView({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,pendingOps:P,permissionState:L,contextEngineRef:C,historyManagerRef:v,executionState:N,actionCallbacks:W,onSubmit:j,onCommand:D,input:h,setInput:f,fileSearchQuery:y,setFileSearchQuery:w,updateFailedInfo:i,creditWarning:G,handleTrust:z,handleNoTrust:H,handleToggleAutoAccept:U,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,loadTasteStatus:O})},"InteractiveCLI");Qr(),uE(),ur(),Sv(),Vr(),Co();var hR=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),fR=ue.hex(br.DIM),yR=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName"),wR=__name(e=>{const t=yR(),n=st([e]);return`${fR("Resume this session with:")}\n${fR(`${t} --resume ${n}`)}\n`},"formatResumeHint"),SR=__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"),bR=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),ER=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),vR=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{let r;return e.permissionMode?r=e.permissionMode:e.plan&&(r="plan"),{resume:"boolean"==typeof e.resume?e.resume:void 0,resumeSessionId:t,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:r,sessionTitleHolder:n}},"buildInteractiveCLIProps"),CR=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),kR=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),TR=__name(()=>{kR()},"initializeTerminal"),_R=__name(async(e={})=>{const t=SR(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),TR(),"string"==typeof e.resume){const t=e.resume.trim();if(await fv.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1)),await fv.sessionExists(t))n=t;else{const e=await fv.findSessionByName(t);e||(console.error(`No session named "${t}" found.`),process.exit(1)),n=e.id}}if(bR(e)&&!n){const e=await fv.isProjectInitialized(),t=e?await fv.listSessions():[],n=ER({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture(),applyTuiTheme(getCliTheme());const r={},o=vR({options:e,resumeSessionId:n,sessionTitleHolder:r}),s=CR(),i=ee(re.createElement(gR,{...o}),s);registerInkControl({clear:i.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await i.waitUntilExit();const a=r.sessionId;if(a&&await fv.sessionExists(a)){const e=await(r.loadTitle?.()),t=e?hR(e):"";process.stdout.write(wR(t||a))}},"interactiveMode");Xo(),Bt(),_n(),cC(),Kv();var xR=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${Re.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${Re.cross} Login failed: ${getErrorMessage2(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||xR()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated"),Co(),Bt(),_n(),bo();var AR={bold:__name((e,t)=>t?`${e}`:e,"bold"),dim:__name((e,t)=>t?`${e}`:e,"dim"),green:__name((e,t)=>t?`${e}`:e,"green")};function modelNameOf(e){const t=e.lastIndexOf("/");return(-1===t?e:e.slice(t+1)).toLowerCase()}function displayModelId(e){return e.replace(ao,"")}function resolveModelFlag({model:e}){const t=resolveKnownModelId(e);if(t)return t;const n=modelNameOf(e),r=getAllModelOptions().filter(e=>modelNameOf(e.id)===n);return 1===r.length?r[0].id:void 0}function editDistance(e,t){const n=e.length+1,r=t.length+1;let o=Array.from({length:r},(e,t)=>t);for(let s=1;s<n;s++){const n=[s];for(let i=1;i<r;i++){const r=e[s-1]===t[i-1]?0:1;n[i]=Math.min(o[i]+1,n[i-1]+1,o[i-1]+r)}o=n}return o[r-1]}function suggestModel(e){const t=e.trim().toLowerCase();if(!t)return;let n;for(const e of getAllModelOptions()){const r=displayModelId(e.id),o=Math.min(editDistance(t,r.toLowerCase()),editDistance(t,modelNameOf(r)));(!n||o<n.distance)&&(n={id:r,distance:o})}if(!n)return;const r=Math.min(4,Math.ceil(t.length/3));return n.distance<=r?n.id:void 0}function formatModelList(e={}){const t=e.color??!1,n=getModelGroupsInOrder(),r=n.flatMap(e=>e.models),o=Math.max(...r.map(e=>displayModelId(e.id).length)),s=n.map(e=>{const n=e.models.map(e=>{const n=displayModelId(e.id).padEnd(o),r=AR.dim(e.description,t);return`${n} ${"free"===e.badge?`${AR.green("FREE",t)} `:""}${r}${e.id===fn?` ${AR.green("(default)",t)}`:""}`});return[AR.bold(e.label,t),"",...n].join("\n")});return[`${AR.bold("Available models",t)} ${AR.dim(`· ${r.length} models`,t)}`,"",s.join("\n\n"),"",AR.dim('Pass the full id, or just the short name after the last "/":',t),"cmd --model moonshotai/Kimi-K2.5","cmd --model kimi-k2.5","","Docs: https://commandcode.ai/docs/reference/cli/models"].join("\n")}function printModelList(){const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`)}function resolveModelFlagOrExit({model:e}){const t=resolveModelFlag({model:e});if(t)return t;const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "cmd --list-models" to see all available models\n`),process.exit(1)}__name(modelNameOf,"modelNameOf"),__name(displayModelId,"displayModelId"),__name(resolveModelFlag,"resolveModelFlag"),__name(editDistance,"editDistance"),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit");var PR=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),IR=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),MR=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),e.plan&&(t.plan=!0),e.permissionMode&&(t.permissionMode=e.permissionMode),t},"buildRuntimeOptions"),RR=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>{const r=e.resume??e.sessions;return r?{resume:r,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n}},"getInteractiveConfig"),NR=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(t.listModels)return void printModelList();if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)addDirectory(e);const n=t.model?resolveModelFlagOrExit({model:t.model}):void 0;if(void 0!==t.print){const r=NR(t,e);return void await printMode({query:r,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:n,benchmarkOutput:t.benchmarkOutput,resume:t.resume,continue:t.continue})}n&&setModelOverride(n),setGoalMaxTurnsOverride(t.maxTurns);const r=PR(e);await IR();const o=MR(t),s=RR({options:t,runtimeOptions:o,initialPrompt:r});await _R(s)}__name(interactiveModeAction,"interactiveModeAction"),Bt(),ir(),Bs(),Co(),Gv(),cC();var LR=new Set(["update"]),$R=__name(()=>process.argv.slice(2).find(e=>!e.startsWith("-")),"getInvokedCommand");globalThis.COMMAND_CODE_CWD=process.cwd();var DR=__name(()=>process.cwd(),"getCwd"),OR=__name(()=>process.argv.slice(2),"getArgs"),FR=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),jR=__name(()=>{const e=DR(),t=OR(),n=FR(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){if(jR(),process.argv.includes("--ide-setup")){const e=await runIDESetup();formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}const e=LR.has($R()??"");e||(notifyCompletedUpdate(),maybeRunPendingUpdate()),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),e||checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100).unref()}__name(preRun,"preRun"),Bt(),_n(),ir(),Go(),uE(),Ro();var UR=getPackageJson(),BR=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=UR.version,t=getInvokedCommandName(),n=GT.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ue.bold("Command Code")+ue.gray(` v${e}`)),console.log(ue.gray(BT)),console.log(),console.log(ue.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ue.bold("Options"));for(const e of WT){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(qT)+ue.gray(e.description))}console.log(),console.log(ue.bold("Commands"));for(const e of VT){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(qT)+ue.gray(e.description))}console.log(),console.log(ue.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(qT)+ue.gray(e.description));console.log(),console.log(ue.bold("Keyboard Shortcuts"));for(const e of HT)console.log(" "+e.key.padEnd(qT)+ue.gray(e.description));console.log(),console.log(ue.bold("Examples"));for(const e of QT){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(qT)+ue.gray(e.description))}console.log(),console.log(ue.cyan("❯")+" "+ue.gray(YT.replace(/cmd/,t))),console.log(),console.log(ue.bold("Links"));for(const e of KT)console.log(" "+e.key.padEnd(qT)+ue.cyan(e.description));console.log()}function createProgram(){const e=new Ne;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(UR.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by id or name, or pick from history").option("--sessions [name]","Alias of --resume — resume a session by id or name, or pick from history").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").addOption(new Le("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Le("--yolo","Bypass all permission prompts (alias for --dangerously-skip-permissions)").implies({dangerouslySkipPermissions:!0})).option("--plan","Start in plan mode (read-only exploration and planning)").addOption(new Le("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Le("--permission-mode <mode>","Set permission mode").choices(["standard","plan","auto-accept"])).option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--max-turns <number>","Max agentic turns (model API round trips): print mode limit (default 10); interactive mode sets the /goal turn budget (default 100)",e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new $e("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--ide-setup",zT).option("--add-dir <directory>","Add directory to workspace context",BR,[]).option("-m, --model <model>","Run on a specific model this session (e.g. claude-sonnet-4-6, kimi-k2.5). Unknown ids are rejected; see --list-models.").option("--list-models","List the models available for use").addOption(new Le("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Le("--experimental","Enable experimental features").hideHelp()).addOption(new Le(zt).hideHelp()).addOption(new Le(Ht).hideHelp()).addOption(new Le("-d, --debug","Enable debug mode").hideHelp()).addOption(new Le("--local","Use local server").hideHelp()).addOption(new Le("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Bt(),Bs(),ls(),Tv(),kC(),Fv(),Go(),cC(),Bt(),__name(isTTY,"isTTY");var qR=!1;function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=w.platform(),t=w.arch();let n,r,o,s;try{const e=await getAuthenticatedEntity();e.success&&(n=e.user?.userName,r=e.user?.id,o=e.org?.login,s=e.org?.id)}catch{}if(!r)try{const e=await loadCredentials();r=e?.userId}catch{}systemInfo({userName:n,userId:r,orgLogin:o,orgId:s,platform:e,arch:t})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){qR||(qR=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=w.platform(),r=w.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=De("Opening GitHub issues...").start();try{await he(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),cC(),Bt(),Po(),__name(openGitHubIssue,"openGitHubIssue");var zR=new Ne("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Bt();var HR=new Ne("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const t=getSystemInfo(),{waitUntilExit:n}=ee(re.createElement(mA,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}Bt(),Bt(),__name(runInfo,"runInfo");var WR=new Ne("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=ee(re.createElement(lR,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}Bt(),_n(),Bt(),__name(runLearnTaste,"runLearnTaste"),ir(),Bs();var GR=new Ne(an.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Ls.LEARN_TASTE_COMMAND,heading:"Learn taste render failed"}}),dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),await shutdownTelemetry(),process.exit(1)}});function addMcpCommand(){const e=new Ne("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new Le("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1)),"stdio"!==n.transport&&"http"!==n.transport&&(console.error(ue.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ue.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ue.red("Error: URL is required for http transport")),console.error(ue.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ue.red(`Error: Invalid URL '${t}'`)),process.exit(1)}s={transport:"http",enabled:!0,url:t,...Object.keys(n.header).length>0&&{headers:n.header},...Object.keys(n.env).length>0&&{env:n.env}},console.log(ue.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ue.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ue.cyan("Server requires OAuth authentication.")),isSecureOrLoopback(t)||(console.error(ue.red(`Error: Server '${e}' requires OAuth, but URL '${t}' is not secure.`)),console.error(ue.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ue.gray("Switch the URL to https:// or use a non-OAuth server.")),process.exit(1));let n,o="command-code";if(r.metadata.registrationEndpoint){console.log(ue.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${lE}/callback`]});e&&(o=e.clientId,n=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},console.log(ue.gray("A browser window will open for authentication.\n"));const a=await performOAuthFlow(e,t,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});a.success?console.log(ue.green("✓ Successfully authenticated")):(i=!0,console.log(ue.yellow(`Warning: Authentication failed: ${a.error}`)),console.log(ue.gray("You can retry with: cmd mcp auth "+e)),console.log(ue.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ue.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);looksLikeHttpUrl2(a)&&(console.error(ue.red(`Error: '${a}' looks like a URL, not a local command.`)),console.error(ue.gray(`Did you mean: cmd mcp add --transport http ${e} ${a}`)),process.exit(1)),s={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:s,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(ue.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===s.transport)console.log(ue.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function looksLikeHttpUrl2(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(ue.red(`Error: Invalid format '${e}', expected KEY=value`)),process.exit(1)),t[n]=r.join("="),t}function collectHeaders(e,t){const n=e.indexOf(":");-1===n&&(console.error(ue.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),o=e.substring(n+1).trim();return r||(console.error(ue.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new Ne("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ue.yellow("\nNo MCP servers configured\n")),console.log(ue.gray("Add a server with:")),console.log(ue.gray(" cmd mcp add --transport http <name> <url>")),console.log(ue.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ue.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ue.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ue.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ue.green("enabled"):ue.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ue.green(Re.tick):ue.red(Re.cross):o.config.headers||o.config.env?ue.green(Re.tick):ue.gray("-"),console.log(` ${ue.white(o.name.padEnd(t))} ${ue.cyan(o.config.transport.padEnd(n))} ${ue.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ue.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ne("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServer({name:e});t||(console.error(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ue.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ue.dim("Scope:")} ${r}`),console.log(` ${ue.dim("Transport:")} ${n.transport}`),console.log(` ${ue.dim("Status:")} ${n.enabled?ue.green("enabled"):ue.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ue.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ue.dim("Headers:")}`);for(const[e,t]of Object.entries(n.headers)){const n=e.toLowerCase().includes("auth")||e.toLowerCase().includes("token")||e.toLowerCase().includes("key")?"***":t;console.log(` ${e}: ${n}`)}}}else console.log(` ${ue.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ue.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ue.dim("Environment:")}`);for(const[e,t]of Object.entries(n.env)){const n=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token")||e.toLowerCase().includes("password")?"***":t;console.log(` ${e}=${n}`)}}console.log("")}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ne("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Le("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await getMcpServer({name:e});n||(console.error(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ue.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ue.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ue.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ne("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new Le("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("--client-secret <secret>","OAuth client secret (injected into oauth config)").action(async(e,t,n)=>{const r=getInvokedCommandName();try{let o,s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{o=JSON.parse(t)}catch{console.error(ue.red("Error: Invalid JSON")),console.error(ue.gray("Make sure to quote the JSON string properly")),console.error(ue.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}o?.oauth?.callbackPort&&(s=o.oauth.callbackPort,delete o.oauth.callbackPort),n.clientSecret&&o?.oauth&&(o.oauth.clientSecret=n.clientSecret);const i=Yb.safeParse(o);if(!i.success){console.error(ue.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ue.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ue.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ue.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ue.cyan("Starting OAuth authentication...")),console.log(ue.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,a.url??"",t,{...s&&{port:s},onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});n.success?console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ue.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ue.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ue.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(ue.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ue.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ne("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list){const e=await listServersWithTokens();if(0===e.length)return void console.log(ue.yellow("No servers with stored authentication."));console.log(ue.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ue.yellow("expired"):ue.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ue.red("Error: Server name is required")),console.error(ue.gray(`Usage: ${n} mcp auth <server>`)),console.error(ue.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ue.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ue.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ue.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ue.gray(" A refresh token is available for re-authentication"));else{if(console.log(ue.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ue.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ue.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ue.green(`✓ Cleared authentication for '${e}'`)):console.log(ue.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ue.red(`Error: MCP server '${e}' not found`)),console.error(ue.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),console.log(ue.cyan(`Authenticating with '${e}'...`)),console.log(ue.gray("A browser window will open for authentication.\n"));const o=__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus");let s;if(r.config.oauth){const t={authorizationUrl:r.config.oauth.authorizationUrl,tokenUrl:r.config.oauth.tokenUrl,clientId:r.config.oauth.clientId,clientSecret:r.config.oauth.clientSecret,scopes:r.config.oauth.scopes};s=await performOAuthFlow(e,r.config.url??"",t,{onStatus:o})}else"http"===r.config.transport&&r.config.url||(console.error(ue.red("Error: Discovery-based auth requires an http server with a url")),process.exit(1)),s=await discoverAndAuthenticate({serverName:e,serverUrl:r.config.url,onStatus:o});if(s.success)return console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ue.gray("Restart the session to connect with the authenticated server."));console.error(ue.red(`\nError: Authentication failed: ${s.error}`)),console.log(ue.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ne("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}async function runCommand(e){return new Promise((t,n)=>{const r=ve(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let o="",s="";r.stdout.on("data",e=>{o+=String(e)}),r.stderr.on("data",e=>{s+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${s?`: ${s.trim()}`:""}`)):t({stdout:o,stderr:s})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await C.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await C.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const o=parseGitHubSource({source:n});if(!o){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const s=String(t.maxCommits??200),i=`https://github.com/${o.owner}/${o.repo}.git`,a=await C.mkdtemp(e.join(w.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",s,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await C.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${o.owner}/${o.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${o.owner}/${o.repo}`,repoDir:a,repoName:o.repo,github:o,cleanup:__name(async()=>{await C.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),o=new hS({baseUrl:r}),s=new fx({request:o,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await s.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(ue.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let o=0;for(let s=0;shouldContinueExtraction({offset:s,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:o});s+=10){const i=t.slice(s,s+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;o++;const s=groupCrossFilePatterns(t);for(const t of s.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const o=[`Commit: ${e.subject}`];o.push(`File: ${t.file}`),t.context&&o.push(`In: ${t.context}`);const s=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(s&&o.push(s),r.push({text:`${truncate3(t.removed,60)} → ${truncate3(t.added,60)}`,evidence:o,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${o} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],o=e.branch?[e.branch]:[],s=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...o,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(s)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",o=""]=e.split("");return{hash:t.trim(),subject:o.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let o="",s="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:o,context:s||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),o=e.match(/b\/(.+)$/)?.[1]??"",s="",l=[],isNoiseFile(o)&&(o="");continue}if(e.startsWith("@@")){g(),m(),s=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!o)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Bt(),Bt(),uE(),__name(addMcpCommand,"addMcpCommand"),__name(looksLikeHttpUrl2,"looksLikeHttpUrl"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Bt(),__name(listMcpCommand,"listMcpCommand"),Bt(),__name(getMcpCommand,"getMcpCommand"),Bt(),__name(removeMcpCommand,"removeMcpCommand"),Bt(),uE(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Bt(),uE(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Bt(),_n(),Bt(),hC(),Bt(),_n(),Bt(),__name(runCommand,"runCommand"),Bt(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Bt(),LS(),VS(),Co(),No(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Bt(),Bt(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var VR=5,KR=3;function buildSnippet(e,t,n){const r=e??[],o=n??[],s=t.split("\n").map(e=>e.trimEnd());if(0===s.length&&0===r.length&&0===o.length)return;let i,a=0;s.length>KR?(i=s.slice(0,KR-1),a=s.length-i.length):i=s;const l=i.length+(a>0?1:0),u=Math.max(0,VR-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(o.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of o.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var QR=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return QR.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var YR=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),JR=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!YR.has(n)||!(!n.includes("[bot]")||!JR.some(e=>e.test(t)))}function truncate3(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let o=0;const s=__name(async()=>{for(;o<t.length;){const e=o++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>s())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:o}=e,s=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${s}Commits analyzed: ${o}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){FC.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await FC.waitForAuth()}catch{return FC.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),FC.markLearningComplete(),{summary:n()}}}t.isLocalSource||FC.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const o="github"===r.type,s=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=o?e.resolve(process.cwd(),s):i;o&&FC.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await C.mkdir(a,{recursive:!0}),FC.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{FC.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");FC.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),FC.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:s,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};FC.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return FC.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),FC.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate3,"truncate"),__name(runBounded,"runBounded"),Bt(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Bt(),Bt(),Bt();var XR=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return XR.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Bt(),Rs(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Bt(),Bt();var ZR=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],eN=[{id:"cloning",label:"Cloning repository"},...ZR],tN=[Re.bullet,Re.squareSmallFilled,Re.lozenge,Re.star,Re.triangleRight,Re.triangleUp];function createInitialRepoLearnSteps(e){return(e??ZR).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Bt();var nN={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var rN=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),oN=__name(e=>e??nN,"withBase");function useRepoLearnState(e){const t=e??ZR,[n,r]=se(()=>createInitialRepoLearnSteps(t)),[o,s]=se(""),[i,a]=se([]),[l,u]=se(null),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w,S]=se(0),E=ie(null),[v,C]=se(null),k=ce(()=>{E.current=Date.now()},[]);return ae(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),s(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,C(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(rN),void s("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),s(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=oN(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=oN(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):s(e.message):u(t=>{const n=oN(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),o=__name(()=>{h(e=>e||(r(rN),!0)),s(""),E.current&&C(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return FC.on("reset",e),FC.on("new-event",n),FC.on("learning-complete",o),()=>{FC.off("reset",e),FC.off("new-event",n),FC.off("learning-complete",o)}},[t]),{steps:n,currentMessage:o,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:v,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Bt(),Bt(),Vr();var sN=__name(({isComplete:e,hasError:t})=>re.createElement(Q,{flexDirection:"column",marginTop:1,marginBottom:0},re.createElement(VM,null),re.createElement(Q,{marginTop:0},re.createElement(Y,{color:br.DIM},QM),re.createElement(Q,{marginLeft:2},t?re.createElement(Y,{color:br.DIM},"learning interrupted"):e?re.createElement(Y,{color:vr.TEXT},"learned your coding taste"):re.createElement(YM,null)))),"RepoLearnTastePill");Bt(),Vr();var iN=__name(({status:e})=>"active"===e?re.createElement(Q,null,re.createElement(Y,{color:br.YELLOW},re.createElement(We,{type:"dots"})),re.createElement(Y,null," ")):"complete"===e?re.createElement(Y,{color:_r.BG},Re.square," "):re.createElement(Y,{color:br.DIM},Re.circle," "),"StepStatusIndicator"),aN=__name(({steps:e,currentMessage:t})=>re.createElement(Q,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return re.createElement(Q,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},re.createElement(Q,null,re.createElement(Q,{marginRight:1},re.createElement(iN,{status:e.status})),re.createElement(Y,{bold:n,color:"complete"===e.status?br.WHITE:n?br.YELLOW:br.DIM},e.label)),n&&t?re.createElement(Q,{marginLeft:3},re.createElement(Y,{color:br.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Bt(),Vr();var lN=__name(({insights:e,insightCount:t})=>0===e.length?null:re.createElement(Q,{flexDirection:"column",marginTop:1,marginLeft:4},re.createElement(Y,{color:br.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>re.createElement(Y,{key:`${t}-${e}`,color:br.DIM},tN[t%tN.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Bt(),Vr();var cN=__name(({message:e})=>re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:br.RED,paddingX:2,paddingY:1,marginTop:1},re.createElement(Y,{color:br.RED,bold:!0},"Oops, something went wrong:"),re.createElement(Q,{marginTop:1},re.createElement(Y,null,e))),"RepoLearnErrorPanel");Bt(),Vr(),ko();var uN=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return re.createElement(Q,{flexDirection:"column",marginLeft:3},re.createElement(Q,{marginBottom:1,flexDirection:"row"},re.createElement(Y,{color:br.DIM},QM),re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:vr.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),re.createElement(Q,{flexDirection:"column",marginLeft:1},re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," Taste stored in"," "),re.createElement(Eo,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:br.CYAN})),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," Share your coding taste:"," ",re.createElement(Y,{color:br.CYAN},"npx taste push --all")))),re.createElement(Q,{marginTop:1,marginLeft:1},re.createElement(Y,{color:br.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Bt(),Vr();var dN=__name(({done:e,error:t})=>t?re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0},"Press ESC to exit")):e?re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue")):re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"ESC to cancel")),"RepoLearnFooter");Bt(),Vr();var mN=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=le(()=>DP(n),[n]);return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(qP,null,r.trimEnd())),e?re.createElement(Y,{color:br.WHITE},e):re.createElement(re.Fragment,null,re.createElement(Y,{color:br.WHITE},"Learning your coding taste from"," ",re.createElement(Y,{bold:!0,color:br.CYAN},t??"repository")),re.createElement(Y,{color:br.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?re.createElement(cN,{message:e}):t?re.createElement(uN,{summary:n,elapsedSeconds:r}):re.createElement(lN,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=ie(!1);return ae(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),Z((e,n)=>{if(s.showLogin)return;const r=n.escape||""===e,o=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(s.done||s.error)&&o&&t({published:!1,cancelled:!!s.error})}),s.showLogin?re.createElement(Q,{flexDirection:"column"},re.createElement(mN,{text:r,repoName:o}),re.createElement(pM,{onComplete:(e,t)=>{s.setShowLogin(!1),e?FC.resolveAuth():FC.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),FC.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):re.createElement(Q,{flexDirection:"column"},re.createElement(mN,{text:r,repoName:o}),re.createElement(sN,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),re.createElement(aN,{steps:s.steps,currentMessage:s.currentMessage}),re.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),re.createElement(dN,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{FC.reset();const r=new AbortController;let o,s,i=!1,a=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,FC.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),FC.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),FC.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=ee(re.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{FC.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),cC();var pN=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new Ne("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",pN("--max-commits"),200).addOption(new Le("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(pN("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await C.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),o=await resolveDisplayName(t.source),s=!await getAuthKey();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:o}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:s,signal:e});return i=o?.cleanup,r},"runTask");if(r){const t=n?void 0:[...eN];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:o,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),uC(),await _R({skipOnboarding:!0})}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(w.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Bt(),Bt(),Bt(),_n(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Bt(),Bt();var gN=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||gN.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:gN.test(o)&&!o.startsWith("#")&&!o.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:o}=findLookaheadEnd(e,t),s=o?r+1:r;return{combined:[n,...e.slice(t,s).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:s}}function processRawLine(e,t){const n=e[t],r=t+1,o=n.trim();if(!o.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(gN.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:o}=processRawLine(e,n);t.push(r),n=o}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!gN.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),i=s.length>0?s[s.length-1]:null;if(!i)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?o.substring(0,i.index).trim():o.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r)}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),o=r.findIndex(e=>e.trim().startsWith("# "));return(-1===o?r:r.slice(0,o)).some(e=>e.includes("See [")&&e.includes("taste.md"))}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),o=t.filter(e=>"warning"===e.severity),s=0===r.length;if(0===t.length)return{valid:s,issues:[...t],summary:`${Re.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&i.push(`${o.length} warning${o.length>1?"s":""}`);const a=r.length>0?Re.cross:Re.warning;return{valid:s,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ue.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ue.dim(` → ${e.suggestion}`)),n}function formatIssueGroup(e,t,n){return 0===e.length?[]:[n,...e.flatMap(e=>formatSingleIssue(e,t)),""]}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${ue.green(e)} ${ue.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?ue.red(t.summary):ue.yellow(t.summary),"",...formatIssueGroup(r,ue.red,ue.bold(ue.red("Errors:"))),...formatIssueGroup(o,ue.yellow,ue.bold(ue.yellow("Warnings:")))].join("\n").trim()}__name(findLookaheadEnd,"findLookaheadEnd"),__name(joinMultiLineLearning,"joinMultiLineLearning"),__name(processRawLine,"processRawLine"),__name(preprocessLines,"preprocessLines"),__name(validateLearningLine,"validateLearningLine"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(buildResult,"buildResult"),Bt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var hN=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:o}=e;hN.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,o),r.currentCategory=t.trim().substring(2).trim(),r.categoryLineNumber=n,r.learningsInCurrentCategory=0)}function processLearning(e){const{line:t,lineNum:n,state:r}=e;r.currentCategory?(r.learningsInCurrentCategory++,r.issues.push(...validateLearningLine({line:t.trim(),lineNum:n}))):r.issues.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'})}__name(warnIfEmptyCategory,"warnIfEmptyCategory"),__name(processHeading,"processHeading"),__name(processLearning,"processLearning");var fN=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,yN=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:o}=e,s=t.trim();s&&(s.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:o}):s.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):fN.test(s)||yN.test(s)||r.issues.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"}))}function checkFinalCategory(e){const{state:t,rawLines:n}=e;!t.currentCategory||t.learningsInCurrentCategory>0||!t.categoryLineNumber||hasReferenceAfterCategory({lines:n,categoryLineIndex:t.categoryLineNumber-1})||t.issues.push({line:t.categoryLineNumber,severity:"warning",message:`Category '${t.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const o=t.split("\n"),s=preprocessLines(o),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:i,rawLines:o});return checkFinalCategory({state:i,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var wN=__name(e=>"local-global"===e?"global":"project","locationLabel"),SN=__name(({file:e,error:t})=>({success:!1,filesLinted:[],errors:[{file:e,error:t}],totalErrors:0,totalWarnings:0}),"failResult");function resolvePackageFile(e,t){const n=getCategoryTasteFile({target:t,category:e});return O(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${wN(t)}`}}}function collectSpecificFiles(e){const{packages:t,target:n}=e,r=t.map(e=>resolvePackageFile(e,n));return{files:r.filter(e=>"result"in e).map(e=>e.result),errors:r.filter(e=>"error"in e).map(e=>e.error)}}async function collectAllFiles(e){const{tastePath:t,target:n}=e,r=[],o=getRootTasteFile({target:n});O(o)&&r.push({path:o,displayName:"taste.md"});const s=(await C.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>O(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...s),r}async function lintFile(e){let t=await C.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await C.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),o=r.issues.filter(e=>"error"===e.severity).length,s=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:o}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&o.length>0)return{success:!1,filesLinted:[],errors:o,totalErrors:0,totalWarnings:0};if(0===r.length)return SN({file:"all",error:`No taste files found in ${wN(n)}`});const s=await Promise.all(r.map(lintFile)),i=s.reduce((e,t)=>e+t.errors,0),a=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return SN({file:"all",error:`No taste files found in ${wN(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),i=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return O(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):SN({file:"all",error:`No taste directory found in ${wN(n)}`})}function resolveConflictStrategy(e){const t=[e.skip&&"skip",e.merge&&"merge",e.overwrite&&"overwrite"].filter(Boolean);return t.length>1&&exitWithError(`Cannot combine --${t[0]} and --${t[1]}. Choose one conflict strategy.`),t[0]}__name(resolvePackageFile,"resolvePackageFile"),__name(collectSpecificFiles,"collectSpecificFiles"),__name(collectAllFiles,"collectAllFiles"),__name(lintFile,"lintFile"),__name(lintSpecificPackages,"lintSpecificPackages"),__name(lintAllFiles,"lintAllFiles"),__name(lint,"lint"),Bt(),Bs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var bN=ue.bgGreen.black.bold(" TASTE ");function shortenPath(e){const t=process.env.HOME??process.env.USERPROFILE??"";return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function exitWithError(e){console.error(`${ue.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`),process.exit(1)}function formatUsageLine(e){const t=e.match(/^(\s*(?:Usage:|or:)?\s*)(cmd)(\s+.+?)(\s+\(.*\))?$/);return t?`${ue.dim(t[1])}${ue.green(t[2])}${ue.white(t[3]??"")}${t[4]?ue.dim(t[4]):""}`:ue.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ue.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function resolveRemoteDefault(e){return e.global||e.remote?e:{...e,remote:!0}}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(resolveRemoteDefault,"resolveRemoteDefault");var EN=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return Ct(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:EN})}function getProfileLink(e){return Ct(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:EN})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return vt(e,n,{trim:!1})}function formatMergeParts(e){const t=[];return e.added>0&&t.push(`${e.added} ${1===e.added?"learning":"learnings"} added`),e.updated>0&&t.push(`${e.updated} ${1===e.updated?"learning":"learnings"} updated`),e.unchanged>0&&t.push(`${e.unchanged} ${1===e.unchanged?"learning":"learnings"} unchanged`),t}function hasMergeConflictRisk(e){return(e.added>0||e.updated>0)&&e.unchanged>0}function hasMergeConflictRiskInRecord(e){return Object.values(e).some(hasMergeConflictRisk)}function logMergeReviewTip(){console.log(ue.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function parseOwnerPackage(e){if(!e.includes("/"))return;const[t,n]=e.split("/");return t&&n?{owner:t,packageName:n}:void 0}function handleResultErrors(e){for(const t of e){const e=t.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${t.pkg}' `);console.error(`${ue.red("Error:")} ${e}`)}process.exit(1)}function getTimeAgo(e){const t=Date.now()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}async function flushAndExit(e){await Promise.race([shutdownTelemetry(),new Promise(e=>setTimeout(e,500))]).catch(()=>{}),process.exit(e)}function withErrorHandler(e){return async(...t)=>{try{await e(...t),await flushAndExit(0)}catch(e){const t=e instanceof Error?e.message:String(e);console.error(ue.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ne("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${ue.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){e||t.all||exitWithUsage({message:"Specify a taste package name or use --all to validate everything",usage:["cmd taste lint <package> validate a taste package","cmd taste lint --all validate all taste packages"]}),e&&t.all&&exitWithError("Use either a package name or --all, not both")}function logLintResults(e){for(const t of e.filesLinted)console.log(t.formatted);e.filesLinted.length>1&&logLintSummary(e),e.success||process.exit(1)}function logLintSummary({filesLinted:e,totalErrors:t,totalWarnings:n}){if(console.log(""),0===t&&0===n)return void console.log(`${ue.green(Re.tick)} All ${ue.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ue.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ue.yellow(`${n} warning${n>1?"s":""}`)),console.log(`Summary: ${r.join(", ")} across ${e.length} files`)}async function runLint({packageName:e,options:t}){console.log(""),validateLintOptions({packageName:e,options:t});const n=await lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(ue.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),o=r[0].trim(),s=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===s.length?null:{category:normalizeCategory({category:o}),learnings:s,sourcePath:n}}function parsePackages(e){const{content:t,sourcePath:n}=e;return t.split(/^# /gm).filter(e=>e.trim()).filter(e=>!e.includes("See [")).map(e=>parseSection({section:e,sourcePath:n})).filter(e=>null!==e)}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatPackage(e){const{pkg:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}async function readAndMigrateFile(e){const{filePath:t}=e,n=await C.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await C.writeFile(t,r,"utf-8"),r)}function trimTrailingBlanks(e){const{lines:t,until:n}=e;let r=e.from;for(;r>n&&""===t[r].trim();)r--;return r}function findCategoryRange(e){const{lines:t,pattern:n}=e,r=t.findIndex(e=>n.test(e));if(-1===r)return null;const o=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===o)return{start:r,end:t.length-1};const s=trimTrailingBlanks({lines:t,from:o-1,until:r});return{start:r,end:s}}function ensureHeader(e){if(!e)return BC+"\n\n";const t=e.trim();return t.startsWith(jC)||t.startsWith(qC)||t.startsWith(zC)?e:BC+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Bt(),ri(),Bt(),Bt(),Bt(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Bt(),__name(formatPackage,"formatPackage"),Bt(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var vN="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:vN,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await C.stat(e.sourcePath);return{category:e.category,learningCount:e.learnings.length,lastUpdated:t.mtime,filePath:e.sourcePath}}catch{return{category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}}}async function getAllPackages(){const e=getTastePath({target:vN});if(!O(e))return[];const t=await C.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:vN,category:t});return O(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:vN});await C.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:vN,category:n.category}),s=e.dirname(o);await C.mkdir(s,{recursive:!0});const i=formatPackage({pkg:n});await C.writeFile(o,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Bt(),Bt();var CN="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!O(n))return null;const r=migrateHeader({content:await C.readFile(n,"utf-8")}).split("\n"),o=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!o)return null;const s=r.slice(0,o.start),i=o.end<r.length-1?r.slice(o.end+1):[],a={before:s.join("\n").trim(),after:i.join("\n").trim()},l=[...s,...i].join("\n").trim();return""===l&&await C.rm(n,{force:!0}),""!==l&&await C.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:CN}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:CN,category:n}),i=e.dirname(s);return O(i)&&await C.rm(i,{recursive:!0,force:!0}),o}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,o=formatPackage({pkg:t});if(r){let e=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=o.trim()+t,void await C.writeFile(n,e.trim()+"\n","utf-8")}let s="";O(n)&&(s=await C.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await C.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:CN,category:n.category}),i=e.dirname(s);await C.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await C.writeFile(s,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=ensureHeader(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=l.trim()+t,void await C.writeFile(r,e.trim()+"\n","utf-8")}let u="";O(r)&&(u=await C.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await C.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var kN="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:kN,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:kN});if(!O(e))return[];const t=[],n=getRootTasteFile({target:kN});if(O(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await C.readdir(e,{withFileTypes:!0}),o=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...o),t}async function getPackage2(e){const{category:t}=e;return(await getAllPackages2()).find(e=>e.category===t)||null}async function writePackage2(e){const{pkg:t}=e,n=getTastePath({target:kN});await C.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:kN}),o=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:o}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:o})}function exists2(){const e=getTastePath({target:kN});return O(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!O(n))return;const r=await C.readFile(n,"utf-8"),o=new Blob([r],{type:"text/markdown"}),s=new File([o],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,s)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:o,type:s="category",isPublic:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),o&&l.append("description",o),l.append("type",s),l.append("isPublic",String(i)),l.append("overwrite",String(a));const u=formatPackage({pkg:r}),d=new Blob([u],{type:"text/markdown"}),m=new File([d],"taste.md",{type:"text/markdown"});if(l.append("files[taste.md]",m),"category"===s)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!O(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!O(f))return l;const y=await C.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1,overwrite:s=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(o)),i.append("overwrite",String(s));const a=getRootTasteFile({target:"local-project"});if(O(a)){const e=await C.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}const l=t.map(e=>appendCategoryFile(i,e));return await Promise.all(l),i}function parseLearningLine(e){const t=e.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(!t)return null;const n=t[1].trim(),r=parseFloat(t[2]);return!n||isNaN(r)?null:{text:n,confidence:r}}function parseTasteContent(e){return e.split("\n").filter(e=>{const t=e.trim();return t&&!t.startsWith("#")&&t.startsWith("-")}).map(e=>parseLearningLine(e.trim())).filter(e=>null!==e)}async function parseApiError(e){const{response:t,fallback:n}=e;try{const e=await t.json();return e.error?.message||e.message||n}catch{return n}}function throwTrackedError(e){const{message:t,label:n,heading:r,status:o,extra:s}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:Ls.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),o=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(o)return o;const s=await getAuthKey();if(!s)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");return tryAuthenticatedDownload({baseUrl:r,owner:t,packageName:n,apiKey:s})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,o=`${t}${Gt.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let s;try{s=await fetch(o,{method:"GET"})}catch{return null}if(s.ok){const{data:e}=await s.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===s.status)return null;throwTrackedError({message:await parseApiError({response:s,fallback:`Failed to download taste package (${s.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:s.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:o}=e,s=`${t}${Gt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:Ls.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${n.message}`),null}}async function getAllPackages3(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list taste packages",status:n.status});const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const s=[];for(let e=0;e<o.length;e+=5){const t=o.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));s.push(...n.filter(e=>null!==e))}return s}async function getPackage3(e){const{category:t}=e;let n;await requireAuthKey();try{n=await getAuthenticatedEntity()}catch(e){const n=e instanceof Error?e:new Error(String(e));throw dlog(`[Auth] getPackage: entity endpoint unavailable — ${n.message}`),trackError({error:sanitizeErrorForTelemetry({error:n,label:"get_entity_error"}),context:{component:Ls.TASTE_REMOTE_STORAGE,heading:"getAuthenticatedEntity failed in getPackage"}}),new Error(`Could not resolve your account to fetch '${t}'. Check your connection and try again.`)}if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");return downloadRemotePackage({owner:n.user.userName,packageName:t})}async function downloadRemotePackage(e){const{owner:t,packageName:n}=e,r=await downloadPackage({owner:t,packageName:n});if(!r)return null;const o=r.files||[];if(0===o.length)return null;const s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1,overwrite:o=!1}=e,s=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:o}),a=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:l.status}),await l.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o=!1,overwrite:s=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o,overwrite:s}),l=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:a});u.ok||throwTrackedError({message:await parseApiError({response:u,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:u.status,extra:{"package.count":t.length}}),await u.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list packages",status:n.status});const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}async function list(e){const{location:t}=e;if("local-global"===t)return listPackages();if("remote-project"===t||"remote-user"===t)return listPackages2();if("local-project"===t){const e=getRootTasteFile({target:"local-project"}),t=await getAllPackages2();return Promise.all(t.map(async t=>{let n;if(t.sourcePath!==e)try{n=(await C.stat(t.sourcePath)).mtime}catch{}return{category:t.category,learningCount:t.learnings.length,lastUpdated:n,filePath:t.sourcePath}}))}throw new Error(`Invalid location: ${t}`)}function createListCommand(){return new Ne("list").alias("ls").option("-g, --global","List global packages").addOption(new Le("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Le("--staging","Use staging environment").hideHelp()).description(`List available packages ${ue.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Bt(),VS(),Bt(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),_n(),Bt(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),kC(),Bs(),Bt(),cC(),Bs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Bt(),VS(),cC(),_n(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),ir(),__name(fetchSinglePackage,"fetchSinglePackage"),__name(getAllPackages3,"getAllPackages"),__name(getPackage3,"getPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage3,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages2,"listPackages"),__name(list,"list"),__name(createListCommand,"createListCommand");var TN={remote:{location:"remote-project",name:"remote",subtitle:"commandcode.ai account"},global:{location:"local-global",name:"global",subtitle:"~/.commandcode/taste"},project:{location:"local-project",name:"project",subtitle:".commandcode/taste"}};function resolveStorage(e){return e.remote?TN.remote:e.global?TN.global:TN.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Re.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Re.arrowDown}${e.downloadCount}`.length),t}function formatPackageLine({pkg:e,maxLen:t}){const n=" ".repeat(t-getPackageDisplayLength(e)+2),r=e.lastUpdated?getTimeAgo(e.lastUpdated):null,o=r?`, updated ${r}`:"";return` ${ue.white(e.category)}${e.isPublic?ue.green(" [public]"):""}${e.isPublic&&e.starCount?ue.yellow(` ${Re.star}${e.starCount}`):""}${e.downloadCount?ue.gray(` ${Re.arrowDown}${e.downloadCount}`):""}${n}${ue.dim.gray(`(${e.learningCount} learnings${o})`)}`}function validateListOptions(e){e.global&&e.remote&&exitWithError("Error: Cannot specify both --global and --remote flags")}async function fetchPackages({options:e}){const t=resolveStorage(e),n=e.remote?De(`Fetching ${t.name} packages`).start():null,r=await list({location:t.location});return n?.stop(),{packages:r,storage:t}}async function getStorageLabel({options:e,fallback:t}){if(!e.remote)return t;const n=await getUserName();return n?getProfileLink(n):t}function printPackageTable({packages:e,subtitle:t}){console.log(`\n${bN} Packages`),console.log(`${ue.gray("⎿")} ${ue.dim(t)}\n`);const n=Math.max(...e.map(getPackageDisplayLength));let r=0;for(const t of e)r+=t.learningCount,console.log(formatPackageLine({pkg:t,maxLen:n}));console.log(ue.dim(`\nTotal: ${e.length} packages, ${r} learnings\n`))}async function runList({options:e}){console.log(""),validateListOptions(e);const{packages:t,storage:n}=await fetchPackages({options:e});0!==t.length?printPackageTable({packages:t,subtitle:await getStorageLabel({options:e,fallback:n.subtitle})}):console.log(ue.yellow(`No taste packages found in ${n.name}`))}async function fetchAllPackages(e){const{target:t}=e;return"local-project"===t?getAllPackages2():"local-global"===t?getAllPackages():getAllPackages3()}function handleOpenError(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}async function readCategoryLineNumber(t){const{filePath:n,category:r}=t,o=await C.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const s=o.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return s>=0?s+1:1}async function findCategoryLineNumber(e){try{return await readCategoryLineNumber(e)}catch{return 1}}async function openPackage(e){const{packageName:t,target:n}=e,r=(await fetchAllPackages({target:n})).find(e=>e.category===t);if(!r){let e="project";return"local-global"===n&&(e="global"),"remote-project"!==n&&"remote-user"!==n||(e="remote"),{success:!1,error:`Taste package '${t}' not found in ${e}`}}const o=r.sourcePath,s=await findCategoryLineNumber({filePath:o,category:t});return await Et([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Bt(),Bt(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var _N=new Set(["local-project","local-global","remote-project","remote-user"]);async function open11(e){const{package:t,target:n}=e;if(!_N.has(n))return{success:!1,error:`Invalid target: ${n}`};try{return await openPackage({packageName:t,target:n})}catch(e){return handleOpenError(e)}}function getEditorSetupInstructions(){const e=kt.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}function createOpenCommand(){return new Ne("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${ue.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){e||exitWithUsage({message:"Specify a taste package name to open",usage:["cmd taste open <package> open taste package in editor","cmd taste open <package> -g open global taste package in editor","cmd taste open owner/package open package page in browser"]})}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor3({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await he(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ue.green(Re.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open11({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ue.green(Re.tick)} Opened ${ue.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open11,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Bt(),Bt(),Bt(),Bt();var xN=null,AN=!1;function setActiveSpinner(e){xN=e}function stopActiveSpinner(e){xN&&(xN.stop(e),xN=null)}function setPrompted(e){AN=e}function wasPrompted(){return AN}function beginPrompt(e,t){stopActiveSpinner(),Ge.intro(ue.dim(e)),t&&Ge.log.message(ue.dim(t)),setPrompted(!0)}function handleCancel(e){Ge.isCancel(e)&&(Ge.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ge.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ge.spinner();r.start(t),setActiveSpinner({stop:__name(e=>r.stop(e??n),"stop"),cancel:__name(e=>r.cancel(e),"cancel"),error:__name(e=>r.error(e),"error")})}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:o}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from ${n}`,s),Ge.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ue.dim(`(from ${n})`)}`);const i=await Ge.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(i);const a=i;return startStrategySpinner(a),a}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,o="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ue.green(`'${t}'`)} to global`,o),Ge.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Ge.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});handleCancel(s);const i=s;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from global`,o),Ge.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Ge.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});handleCancel(s);const i=s;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),Ge.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Ge.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await Ge.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),Ge.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Ge.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await Ge.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${o} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const o=t.get(e.text);return o?e.confidence>o.confidence?(n.set(e.text,e),void r.updated++):void r.unchanged++:(n.set(e.text,e),void r.added++)}function mergePackages(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},o=new Map(n.map(e=>[e.text,e])),s=new Map(o);for(const e of t)mergeSingleLearning(e,o,s,r);const i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{merged:Array.from(s.values()),details:r}}function validateSinglePackage(e,t){const n=validateTasteFile({content:formatPackage({pkg:e}),filePath:`${e.category}/taste.md`});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:e.category,error:`Validation failed for taste package in ${t}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${e.category}' in ${t} has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validateSingleRemoteFile(e,t){const n=validateTasteFile({content:e.content,filePath:e.file});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:t,error:`Validation failed for ${e.file}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validatePackages(e){const{packages:t,label:n}=e;return t.map(e=>validateSinglePackage(e,n)).filter(e=>null!==e)}function validateRemoteFiles(e){const{files:t,packageName:n}=e;return t.map(e=>validateSingleRemoteFile(e,n)).filter(e=>null!==e)}function mergeOrKeep(e){const{source:t,existing:n}=e;if(!n)return{pkg:t,details:{added:t.learnings.length,updated:0,unchanged:0}};const r=mergePackages({source:t.learnings,target:n.learnings});return{pkg:{...t,learnings:r.merged},details:r.details}}async function resolveRemotePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,tastePkg:o,owner:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:o.category,owner:s,localPkg:r,remoteLearningsCount:o.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void s.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:o,flagStrategy:s,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:o,flagStrategy:s,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:o,flagStrategy:s,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Bt(),Bt(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Bt(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var PN=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),IN=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),MN=__name(e=>"local-global"===e?"global":"remote-project"===e?"remote project":"remote-user"===e?"remote":"source","sourceName");async function resolvePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,source:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPullStrategy({packageName:s.category,localPkg:r,globalLearningsCount:s.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void s.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return PN({pkg:"all",error:`Invalid source: ${n}`});const s=MN(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return PN({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return PN({pkg:"all",error:`No taste packages found in ${s}`});const a=validatePackages({packages:i,label:s});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=IN();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return PN({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:o,result:s};return"project"===a?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=IN();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return PN({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,i=wasPrompted()?"":`${Re.tick} `,a=r?ue.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ue.green(i)}Replaced ${ue.green(`'${t}'`)} taste package in project`+a;if(s){const e=formatMergeParts(s);return`${ue.green(i)}Pulled ${ue.green(`'${t}'`)} taste package from ${n} ${ue.gray(`(${e.join(", ")})`)}`+a}return`${ue.green(i)}Pulled ${ue.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const o=t.packagesPulled[0],s=t.filePaths?.[o],i=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+o.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return s.length>0&&l.push(wrapLine(`${ue.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ue.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${ue.dim("Skipped")} (${o.length}) ${ue.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Ge.log.message(l.join("\n")),Ge.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ue.green(Re.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ue.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ne("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new Le("--local","Use local server").hideHelp()).option("--remote","Pull taste package from commandcode.ai remote").option("--all","Pull all taste packages from global").option("--overwrite","Replace local package without prompting").option("--skip","Keep local package, skip conflicting pull").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Le("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ue.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:o}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?o??"remote":"global",options:n})}))}function validatePullOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one source"),n.remote&&n.all&&exitWithUsage({message:"--all is not supported for remote pull — specify a package instead",usage:["cmd taste pull <owner>/<package> pull a taste package from remote"]}),n.remote&&!t&&exitWithUsage({message:"Specify a taste package to pull from remote",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),n.remote&&t&&!t.includes("/")&&exitWithUsage({message:`Remote pull requires owner/package format — got '${t}'`,usage:["cmd taste pull <owner>/<package> e.g. cmd taste pull ahmadawais/code-style"]}),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to pull everything",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePullOptions({packageName:t,options:r});const o=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:o}):pullGlobal({packageName:t,options:r,strategy:o})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,o=parseOwnerPackage(t);o||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(De("Pulling taste package").start());const s=await pullRemote({owner:o.owner,packageName:o.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s,owner:o.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(De("Pulling taste package").start());const o=n.all||!t?[]:[t],s=await pull({packages:o,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new hS({baseUrl:e}),n=await t.get({endpoint:Gt.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}function logResult2(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function logPushAllSuccess(t){const{result:n,options:r}=t;if(!r.all)return!1;if(0===n.packagesPushed.length){const e=n.skipped?.length??0;if(e>0){const t=wasPrompted()?"":`${Re.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ue.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${Re.tick} `;if(!a)return logResult2(`${ue.green(l)}Pushed ${s} to remote`),!1;if(r.overwrite||Boolean(n.overwritten?.length)){let e=0;if(n.mergeDetails)for(const t of Object.values(n.mergeDetails))e+=t.updated??0;const t=e>0?` ${ue.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ue.green(l)}Replaced ${s} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ue.green(l)}Pushed ${s} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${ue.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${ue.green(l)}Pushed ${s} to ${a}${h}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],o=t.filePaths?.[r],s=n.remote&&o,i=s?o:"global",a=wasPrompted()?"":`${Re.tick} `,l=!s&&o?ue.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ue.green(a)}Replaced ${ue.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ue.green(a)}Pushed ${ue.green(`'${r}'`)} taste package to ${i} ${ue.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ue.green(a)}Pushed ${ue.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",o=wasPrompted()?"":`${Re.tick} `;return logResult2(wrapLine(`${ue.green(o)}Pushed ${ue.green(t.packagesPushed.length)} taste packages ${ue.green(`(${t.packagesPushed.join(", ")})`)} to ${r}`)),!(n.overwrite||!t.mergeDetails)&&hasMergeConflictRiskInRecord(t.mergeDetails)}function logPushUrls(e){const{result:t,options:n}=e;if(!n.remote||!t.filePaths)return;const r=new Set;for(const e of t.packagesPushed){const n=t.filePaths[e];if(!n||!n.includes("/"))continue;const[o,s]=n.split("/");if(!o||!s)continue;const i=getPackageLink({owner:o,packageName:s});r.has(i)||(r.add(i),console.log(ue.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],o=t.packagesPushed.filter(e=>!n.includes(e)),s=t.packagesPushed.length+r.length,i=[];o.length>0&&i.push(wrapLine(`${ue.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ue.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ue.dim("Skipped")} (${r.length}) ${ue.dim(r.join(", "))}`,4)),i.length>0&&Ge.log.message(i.join("\n"));const a=`${s} ${1===s?"package":"packages"}`;Ge.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),o=[];r.length>0&&o.push(wrapLine(`${ue.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ue.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ue.dim("Skipped")} (${n.length}) ${ue.dim(n.join(", "))}`)),o.length>0&&console.log(o.join("\n"))}function logPushSuccess(e){const{result:t,options:n}=e;if(wasPrompted())return setPrompted(!1),logConflictSummary({result:t}),void logPushUrls({result:t,options:n});const r=logPushAllSuccess({result:t,options:n})||logPushSingleSuccess({result:t,options:n})||logPushMultiSuccess({result:t,options:n});n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r&&logMergeReviewTip()}__name(resolvePullStrategy,"resolvePullStrategy"),__name(executePullStrategy,"executePullStrategy"),__name(pullSinglePackage,"pullSinglePackage"),__name(pull,"pull"),__name(executePullRemote,"executePullRemote"),__name(pullRemote,"pullRemote"),Bt(),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSingleSuccess,"logPullSingleSuccess"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),__name(createPullCommand,"createPullCommand"),__name(validatePullOptions,"validatePullOptions"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Bt(),ir(),Bt(),VS(),LS(),_n(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Bt(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Bt(),kC(),Bt();var RN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),NN=__name(e=>e.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0),"countRemoteLearnings");async function resolvePushAllStrategy(e){const{flagStrategy:t,overwrite:n,existingProject:r,packagesToPush:o,projectName:s,owner:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=o.reduce((e,t)=>e+t.learnings.length,0),u=NN(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l}),m=await resolvePushAllStrategy({flagStrategy:a,overwrite:o,existingProject:d,packagesToPush:n,projectName:l,owner:r});if("skip"===m)return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?s:d?.isPublic??!1,overwrite:"overwrite"===m});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return RN({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var LN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),$N=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o,overwrite:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o,overwrite:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var DN=__name(e=>{const{target:t,category:n,owner:r}=e;return"local-global"===t?getCategoryTasteFile({target:"local-global",category:n}):"remote-project"!==t&&"remote-user"!==t||!r?void 0:`${r}/${n}`},"getDestPath");async function getUserOwner(){try{const e=await getAuthenticatedEntity();if(e.success&&e.user?.userName)return e.user.userName}catch{}}async function resolveSinglePushStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,target:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPushStrategy({packageName:s.category,localLearningsCount:s.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:o,userOwner:s,isPublic:i,result:a}=e,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:o,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:s,isPublic:i,overwrite:!0}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:s,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=DN({target:n,category:t.category,owner:s});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e;if(!exists2())return LN({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return LN({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:i}):LN({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return LN({pkg:"all",error:`Invalid target: ${r}`});const m=$N();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:o,userOwner:d,isPublic:s,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return LN({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return LN({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:o,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?s:u?.isPublic??!1,g=$N();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return LN({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return LN({pkg:t,error:e instanceof Error?e.message:String(e)})}}async function promptOwnerSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],o=await Ge.select({message:"Owner",options:r,initialValue:t});return Ge.isCancel(o)&&(Ge.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new Ne("push").description(`Push taste packages to remote ${ue.dim("(commandcode.ai)")} or global ${ue.dim("(~/.commandcode)")}`).argument("[package]","Taste package name to push (omit with --all)").option("--all","Push all taste packages to remote").option("--remote","Push to commandcode.ai remote (default)").option("-g, --global","Push to local global storage (~/.commandcode)").addOption(new Le("--local","Use local server").hideHelp()).option("--public","Make package publicly discoverable on commandcode.ai").option("--private","Make package private (not publicly discoverable)").option("--owner <owner>","Push under a specific owner or organization").option("--overwrite","Replace existing package without prompting").option("--skip","Keep existing package, skip conflicting push").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Le("--staging","Push to staging environment").hideHelp()).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),r=await runPush({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPushSuccess({result:r,options:n})}))}function validatePushOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one destination"),n.public&&n.private&&exitWithError("--public and --private are mutually exclusive — pick one visibility"),n.owner&&n.global&&exitWithError("--owner only applies to remote pushes, not --global"),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to push everything",usage:["cmd taste push <package> push a taste package to remote (default)","cmd taste push --all push all taste packages to remote","cmd taste push <package> -g push a taste package to global (~/.commandcode)"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}__name(getUserOwner,"getUserOwner"),__name(resolveSinglePushStrategy,"resolveSinglePushStrategy"),__name(executePushStrategy,"executePushStrategy"),__name(pushSinglePackage,"pushSinglePackage"),__name(push,"push"),__name(executeRemotePush,"executeRemotePush"),__name(pushRemote,"pushRemote"),Bt(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var ON=__name(e=>!!e.public||!e.private&&void 0,"resolveVisibility");async function validateOwnerAccess(e){let t;try{t=await fetchUserNamespaces()}catch(e){return void dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${e instanceof Error?e.message:String(e)}`)}const n=[t.userName,...t.orgs.map(e=>e.login)];n.includes(e)||exitWithError(`No push access to '${e}'. Available: ${n.join(", ")}`)}async function resolveOwnerForPush(e){const{packageName:t,owner:n}=e,r=parseOwnerPackage(t);if(r)return await validateOwnerAccess(r.owner),r;if(n)return await validateOwnerAccess(n),{owner:n,packageName:t};Ge.intro(ue.dim(`pushing ${t}`)),setPrompted(!0);const o=Ge.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Ge.outro(ue.red(`Taste package '${t}' not found in project`)),process.exit(1));const s=await fetchUserNamespaces();return o.stop(s.orgs.length>0?"Select owner to push to":""),{owner:s.orgs.length>0?await promptOwnerSelection(s):s.userName,packageName:t}}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePushOptions({packageName:t,options:r});const o=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:o}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:o}):pushGlobal({packageName:t,options:r,strategy:o})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const o=(await getAllPackages2()).length,s=`${o} ${1===o?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ue.dim(` Pushing ${s} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(De("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:ON(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:o,packageName:s}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:o,pkgName:s});const i=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:ON(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ge.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(De("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),i=o.length>0?o.length:s.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(ue.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(De("Pushing taste packages").start());const d=await push({packages:o,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new Ne(an.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?de.bold(de.green(t)):de.white(t);return`${de.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${de.bold(de.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(de.dim(`Run ${de.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(de.dim("Try updating manually:")),console.log(de.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(de.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(`${de.green(Re.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${de.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} ${Re.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:Ls.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 ${de.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),Co(),__name(createTasteCommand,"createTasteCommand"),Bt(),_n(),Bs(),__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 FN=new Ne("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Bt(),cC(),kC();var jN=__name((e,t)=>`${Re.info} ${e}: ${de.cyan(t)}`,"formatInfoLine"),UN=__name(e=>de.bold(`${e}:`),"formatSectionHeader"),BN=__name(e=>de.red(e),"formatError"),qN=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),zN=__name(e=>["",UN("User Information"),jN("Name",e.name),jN("Email",e.email),jN("Username",e.userName)],"buildUserOutput"),HN=__name(e=>["",UN("Organization"),jN("Name",e.name),jN("Login",e.login)],"buildOrgOutput"),WN=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),GN=__name((e,t)=>{WN(zN(e)),t&&WN(HN(t)),console.log("")},"displayUserInfo"),VN=__name(e=>null!==e&&e.length>0,"validateApiKey"),KN=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=De("Fetching user information...").start();try{const t=await getAuthKey();VN(t)||(e.fail(BN('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();KN(n)||(e.fail(BN("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),GN(n.user,n.org)}catch(t){e.fail(BN(`Error: ${qN(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var QN=new Ne("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function normalizeGitUrl(e){let t=e.trim();const n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);return n?`https://${n[1]}/${n[2]}`:(t=t.replace(/\.git$/,""),t)}function validateGitRepo(){try{if("true"!==Ce("git rev-parse --is-inside-work-tree",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error("Not inside a git repository.")}catch{throw new Error("Sandbox requires a git repository with a GitHub remote.")}let e;try{e=Ce("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("No GitHub remote found. Add one with: git remote add origin https://github.com/you/repo")}const t=normalizeGitUrl(e);let n;try{n=Ce("git branch --show-current",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("Failed to determine current branch.")}if(!n)throw new Error("Detached HEAD state. Please checkout a branch first.");if(!/^[\w./-]+$/.test(n))throw new Error("Branch name contains invalid characters. Please use a simpler branch name.");try{if(!Ce(`git ls-remote --heads origin ${n}`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}catch(e){if(e instanceof Error&&e.message.includes("not found on remote"))throw e;throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}return{repoUrl:t,branch:n,isClean:""===Ce("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}Bt(),Bt(),_n(),LS(),oi(),VS(),Un(),Ro(),Bt(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Bt(),VS(),cC(),Bt();var YN=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return YN.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var JN={setting_up:"Setting up sandbox...",cloning:"Cloning repository..."};function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusEvent({event:e,state:t}){const n=e.data.status,r=JN[n],o="setup"===t.phase;if(t.isResume&&o&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&o&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=De({stream:process.stderr,text:r}).start()),"running"===n)return t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="running",void(t.workingSpinner||(t.workingSpinner=De({stream:process.stderr}).start()));if("completed"===n){t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="done";const n=e.data.prUrl;return void(n&&console.error(`PR: ${de.cyan(n)}`))}if("failed"===n){const n=e.data.message||"Unknown error";return t.workingSpinner&&(t.workingSpinner.fail(n),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(n),t.currentSpinner=null),void(t.phase="done")}if("timed_out"===n)return t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null),void(t.phase="done");"cancelled"===n&&(stopAllSpinners({state:t}),t.phase="done",console.error(`\n${de.yellow("Cancelled.")}`))}}function renderEvent({event:e,state:t}){if("status"!==e.type){if("pty"===e.type){const n=e.data.content;return void(n&&(t.workingSpinner&&t.workingSpinner.stop(),process.stdout.write(n),t.workingSpinner&&t.workingSpinner.start()))}if("error"===e.type){t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null);const n=e.data.message;console.error(`${Re.cross} ${de.red(n)}`)}}else renderStatusEvent({event:e,state:t})}function setupInputHandling({callbacks:e}){const t=__name(t=>{3===t[0]?e.onCancel():4===t[0]&&e.onDetach()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({ws:e}){const t=__name(()=>{e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({action:"resize",cols:process.stdout.columns,rows:process.stdout.rows}))},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}function sendTerminalSize({ws:e}){e.send(JSON.stringify({action:"resize",cols:process.stdout.columns||120,rows:process.stdout.rows||30}))}async function streamSession({sessionId:e,prompt:t,lastEventId:n=0,isResume:r=!1}){const o=getApiBaseUrl().replace(/^http/,"ws"),s=await getAuthKey();if(!s)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:s,...n>0?{lastEventId:String(n)}:{}}),a=`${o}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,o)=>{const s=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=De({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.close(),console.error(`\n${de.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.readyState===WebSocket.OPEN&&s.send(JSON.stringify({action:"cancel"})),s.close(),console.error(`\n${de.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:s}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");s.addEventListener("open",()=>{sendTerminalSize({ws:s}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${de.yellow("[Ctrl+C]")} ${de.dim("stop")} ${de.yellow("[Ctrl+D]")} ${de.dim("detach")}`),console.error(`${de.dim("Session:")} ${de.gray(e)}`),console.error(""),r&&(i.workingSpinner=De({stream:process.stderr}).start())}),s.addEventListener("message",e=>{try{const n="string"==typeof e.data?e.data:e.data.toString(),r=JSON.parse(n);renderEvent({event:r,state:i}),void 0!==r.id&&(i.lastEventId=r.id),"status"===r.type&&isTerminalStatus(r.data.status)&&(s.close(),g(),t())}catch{}}),s.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),o(new Error("WebSocket connection failed"))}),s.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${de.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=$.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=$.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=dt.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function startSandboxSession({repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}){return new hS({baseUrl:getApiBaseUrl()}).post({endpoint:Gt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateGitRepo();n.isClean||console.error(de.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),s=e||await askQuestion(`${de.bold("What do you want to do?")}\n${de.cyan(">")} `);if(!s.trim())return void console.error(de.yellow("No prompt provided. Aborting."));const i=s.trim().slice(0,ln.MAX_PROMPT_CHARS),a=De({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:i,isInternalTeam:r,configFiles:o});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:i}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=e instanceof Ws,r=t?e.code:void 0;if(401===(t?e.status:void 0)||"UNAUTHORIZED"===r)console.error(de.red("\nAuthentication failed. Try logging in again: cmd login"));else if("GITHUB_APP_NOT_INSTALLED"===r){const e=de.cyan(de.underline(n.repoUrl)),t=de.cyan(de.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${de.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(de.dim(" Then run this command again."))}else{const n=t&&"string"==typeof e.message?e.message:"Something went wrong. Please try again.";console.error(de.red(`\n${n}`))}process.exit(1)}}function createSandboxCommand(){return new Ne("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(de.red(t)),process.exit(1)}})}function validateSafeString(e,t){if(e.includes("..")||e.includes("\\"))throw new Error(`Invalid ${t}: path traversal sequences are not allowed.\nExpected format: owner/repo or owner/repo/path`);if(!/^[a-zA-Z0-9._/-]+$/.test(e))throw new Error(`Invalid ${t}: contains unsupported characters.\nOnly letters, numbers, hyphens, underscores, dots, and slashes are allowed.`)}function parseGitHubRepo(e){let t,n=e.replace(/^https?:\/\/github\.com\//,"");const r=n.lastIndexOf("@");r>0&&r<n.length-1&&(t=n.slice(r+1),n=n.slice(0,r),validateSafeString(t,"branch name"));const o=n.split("/");if(o.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[s,i,...a]=o;validateSafeString(s,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:s,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:o}=e;let s=`gh:${t}/${n}`;return r&&(s+=`/${r}`),o&&(s+=`#${o}`),s}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:o,path:s}=n;let i;if(s){const e=s.split("/").filter(Boolean);i=e[e.length-1]}else i=o;const a=t.join(S.tmpdir(),`commandcode-skill-${N()}`);await k.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:s}=await import("giget");try{await s(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,o),await s(e,{dir:a,force:!0,silent:!0})}const l=t.join(a,"SKILL.md"),u=t.join(a,"skill.md");let d=!1;try{await k.access(l),d=!0}catch{}if(!d)try{await k.access(u),d=!0}catch{}if(!d)throw new Error(`SKILL.md not found in ${e}. Make sure the repository contains a SKILL.md file.`);return{tempDir:a,skillName:i}}catch(e){if(await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,o)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:o,path:s,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(RC(),MC)),u=await l({owner:r,repo:o,path:s,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${o}${s?` at path "${s}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await k.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await k.access(r),r}catch{}throw new Error(`SKILL.md not found in ${e}`)}function validateSkillName(e){const t=e.trim();if(!t||0===t.length)throw new Error("Invalid skill name: name cannot be empty");if(t.includes("/")||t.includes("\\"))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain path separators (/ or \\).`);if(t.includes(".."))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain parent directory references (..).`);if(t.startsWith("."))throw new Error(`Invalid skill name: "${e}". Skill names cannot start with a dot.`);if(!/^[a-z0-9-]+$/.test(t))throw new Error(`Invalid skill name: "${e}". Skill names must contain only lowercase letters, numbers, and hyphens.`);return t}async function validateSkillContent(e){const t=await resolveSkillMdPath(e),n=await k.readFile(t,"utf-8"),{data:r}=qe(n),o=zf.parse(r);return{name:validateSkillName(o.name),description:o.description}}async function skillExists(e){const{skillName:n,location:r}=e,o="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),s=t.join(o,n);try{return await k.access(s),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:o=!1,force:s=!1,skillName:i,discoveredSkill:a,cachedTempDir:l}=r;let u,d,m=n;if(i){let e;if(a)e=a;else{const t=await discoverSkillsInRepo(n);if(0===t.skills.length)throw new Error(`No skills found in repository: ${n}`);const r=t.skills.find(e=>e.name.toLowerCase()===i.toLowerCase());if(!r){const e=t.skills.map(e=>e.name).join(", ");throw new Error(`Skill "${i}" not found in repository. Available skills: ${e}`)}e=r}const t=parseGitHubRepo(n),r=[t.path,e.path&&"."!==e.path?e.path:void 0].filter(Boolean).join("/"),o=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${o}@${t.branch}`:o}if(l&&a){u=a.path&&"."!==a.path?t.join(l,a.path):l,d=!1;try{await resolveSkillMdPath(u)}catch{const e=a.path&&"."!==a.path?`at ${a.path}`:"at root";throw new Error(`SKILL.md not found in cached directory ${e}. Make sure the repository contains a SKILL.md file.`)}}else u=(await fetchSkillFromGitHub(m)).tempDir,d=!0;try{const{name:e,description:n}=await validateSkillContent(u),r=e,i=o?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!s)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await k.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await k.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&s&&await k.rm(d,{recursive:!0,force:!0}),await k.rename(g,d)}catch(e){if(await k.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await k.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),o=n?"global":"project",s="global"===o?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(s,r);if(!await skillExists({skillName:r,location:o}))throw new Error(`Skill "${r}" not found in ${"global"===o?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===o?"":" Use -g/--global to check global skills."}`);await k.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t,warnings:n}=await loadAllSkillSummariesWithWarnings(),r=getBundledSkillsDir(),o=[],s=[];for(const t of e){const e={name:t.name,description:t.description,location:isBundledSkillPath({filePath:t.filePath,bundledDir:r})?"bundled":"global",path:t.filePath};("bundled"===e.location?o:s).push(e)}return{global:s,project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath})),bundled:o,warnings:n}}__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusEvent,"renderStatusEvent"),__name(renderEvent,"renderEvent"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(sendTerminalSize,"sendTerminalSize"),__name(streamSession,"streamSession"),__name(readLocalConfigFiles,"readLocalConfigFiles"),__name(askQuestion,"askQuestion"),__name(startSandboxSession,"startSandboxSession"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),Co(),Bt(),Bt(),Bt(),Bt(),IC(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),QS(),iy(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),_n();var XN=[`${de.dim("Usage:")}`,` ${de.cyan("cmd skills add")} ${de.white("<owner/repo>")}`,"",`${de.dim("Examples:")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/my-skills")} ${de.dim("# single-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/skills/path/to/skill")} ${de.dim("# specific path in repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/multi-skills -s my-skill")} ${de.dim("# pick one from multi-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo@branch")} ${de.dim("# specific branch")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo --global")} ${de.dim("# install to ~/.commandcode/skills/")}`],ZN=__name((e,t)=>`${de.green(Re.tick)} Installed ${de.cyan(e)} ${de.dim(`${Re.arrowRight} ${t}/`)}`,"formatInstalled"),eL=__name(e=>`${de.red(Re.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await x(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(eL("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),XN.forEach(e=>console.log(e)),process.exit(1));const t=e.replace(/^https?:\/\/github\.com\//,""),n=t.lastIndexOf("@");(n>0?t.slice(0,n):t).split("/").filter(Boolean).length<2&&(console.error(eL(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${de.cyan("owner/repo")} or ${de.cyan("owner/repo/path")}`),console.log(""),XN.forEach(e=>console.log(e)),process.exit(1))}async function addAction(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let o;validateRepoFormat(e);const s=De({text:`Fetching ${de.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(o=u,s.stop(),0===l.length&&(console.error(eL(`No skills found in ${de.cyan(e)}`)),console.log(de.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(eL(`Skill "${t.skill}" not found in ${de.cyan(e)}`)),console.log(""),console.log(de.dim("Available skills:")),l.forEach(e=>console.log(` ${de.cyan(e.name)}`)),await cleanupAndExit(o,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await Ve({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(de.dim("Cancelled")),await cleanupAndExit(o,0));const n=t;i=l.filter(e=>n.includes(e.name))}else i=l;let d=0;for(const n of i)try{const s=De({text:`Installing ${de.cyan(n.name)}...`,color:"cyan"});s.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:o}});s.stop(),console.log(ZN(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(eL(`Failed to install "${n.name}"`)),console.log(de.dim(` ${t}`))}await cleanupAndExit(o,d>0?1:0)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(eL(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var tL=new Ne("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${XN.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(eL("No repository specified.")),console.log(""),XN.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Bt(),_n();var nL=__name((e,t)=>`${de.green(Re.tick)} Removed ${de.cyan(e)} from ${t} skills`,"formatRemoved"),rL=__name(e=>`${de.red(Re.cross)} ${e}`,"formatError");function validateSkillNameEarly(e){return e.includes("/")||e.includes("\\")?`"${e}" is not a valid skill name — it cannot contain path separators.`:e.includes("..")?`"${e}" is not a valid skill name — it cannot contain "..".`:e.startsWith(".")?`"${e}" is not a valid skill name — it cannot start with a dot.`:/^[a-z0-9-]+$/.test(e.trim())?null:`"${e}" is not a valid skill name — use only lowercase letters, numbers, and hyphens.`}async function removeAction(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",o=validateSkillNameEarly(e);if(o&&(console.error(rL(o)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Ke({message:`Remove ${de.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(de.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(nL(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(rL(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(de.dim(`Try ${de.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`))):console.error(rL(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var oL=new Ne("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction);Bt(),QS(),Nv(),_n();var sL=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${de.cyan(e)} ${de.dim(`· ${n}`)}`},"formatSkillLine"),iL=__name((e,t)=>`${de.bold(de.white(e))} ${de.dim(`(${t})`)}`,"formatSectionHeader"),aL=__name(e=>{if(0===e.length)return;const t=groupWarnings(e);console.log(""),console.log(`${de.bold(de.yellow("Skipped"))} ${de.dim(`(${e.length})`)}`);for(const e of t){console.log(""),console.log(` ${de.bold(e.category)} ${de.dim(`(${e.items.length})`)}`);for(const t of e.items)console.log(` ${de.bold(skillIdentifier(t.path))}`),console.log(` ${de.dim(t.reason)}`)}},"printWarnings"),lL=__name(()=>{const e=process.cwd(),n=t.join(e,".commandcode","skills"),r=t.join(e,".agents","skills"),o=getProjectSkillsDir(),s=getProjectAgentsCompatSkillsDir(),i=["",de.dim("No skills installed."),"",de.dim("Looking in:"),de.dim(` ${getGlobalSkillsDir()} ${de.white("(global)")}`),de.dim(` ${getGlobalAgentsCompatSkillsDir()} ${de.white("(global, .agents)")}`)];return n!==o&&i.push(de.dim(` ${n} ${de.white("(cwd)")}`)),r!==s&&i.push(de.dim(` ${r} ${de.white("(cwd, .agents)")}`)),i.push(de.dim(` ${o} ${de.white("(project)")}`),de.dim(` ${s} ${de.white("(project, .agents)")}`),"",`Install a skill: ${de.cyan("cmd skills add")} ${de.dim("<owner/repo>")}`,""),i},"formatEmptyHint"),cL=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){const e="true"===process.env.DEBUG;try{const{global:t,project:n,bundled:r,warnings:o}=await listSkills(),s=t.length+n.length,i=__name(()=>{e||0===o.length||(console.log(""),console.log(de.dim(`${o.length} skill${1===o.length?"":"s"} skipped · run with ${de.cyan("--debug")} to see issues`)))},"printDebugHint");0===s&&(cL(lL()),r.length>0&&(console.log(iL("Bundled",r.length)),r.forEach(e=>{console.log(sL(e.name,e.description))}),console.log("")),e&&(aL(o),o.length>0&&console.log("")),e||(i(),console.log("")),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:de.dim(`${s} installed`)})),n.length>0&&(console.log(""),console.log(iL("Project",n.length)),n.forEach(e=>{console.log(sL(e.name,e.description))})),t.length>0&&(console.log(""),console.log(iL("Global",t.length)),t.forEach(e=>{console.log(sL(e.name,e.description))})),r.length>0&&(console.log(""),console.log(iL("Bundled",r.length)),r.forEach(e=>{console.log(sL(e.name,e.description))})),e&&aL(o),e||i(),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${de.red(Re.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var uL=new Ne("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction),dL=new Ne("skills").description("Manage skills from GitHub repositories").addCommand(tL).addCommand(oL).addCommand(uL);handleUnhandledErrors(),setupTelemetry(),await preRun();var mL=createProgram();mL.action(interactiveModeAction),mL.addCommand(HR),mL.addCommand(WR),mL.addCommand(QN),mL.addCommand(FN),mL.addCommand(zR),mL.addCommand(createTasteCommand()),mL.addCommand(createMcpCommand()),mL.addCommand(GR),mL.addCommand(zs),mL.addCommand(Wv),mL.addCommand(eC),mL.addCommand(dL),isExperimentalEnabled()&&mL.addCommand(createSandboxCommand()),setupCommanderHooks(mL),mL.parse();
324
+ `,jP=getMaxLineWidth(FP),UP=$P,BP=__name(e=>{const t=e??getTerminalWidth();return t>=LP?"full":t>=UP?"compact":"minimal"},"getHeaderLayout");Bt(),Vr();var qP=__name(({children:e})=>{const t=[];let n="",r=!0;const o=__name(()=>{0!==n.length&&(t.push({text:n,panel:r}),n="")},"flush");for(const t of e){const e="░"===t;0===n.length?r=e:e!==r&&(o(),r=e),n+=t}return o(),re.createElement(Y,null,t.map((e,t)=>re.createElement(Y,{key:t,backgroundColor:Br.BG,color:e.panel?Br.BG:Br.TEXT},e.panel?e.text.replaceAll("░"," "):e.text)))},"CommandLogoBanner");Bt(),Vr();var zP=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:o=0,titleColor:s=br.GRAY,dividerChar:i="─",dividerColor:a=br.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*o),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return re.createElement(Q,{paddingLeft:o,paddingRight:o,marginBottom:1,...l},(t||n)&&re.createElement(Y,{color:a},d),e&&re.createElement(Y,{color:s},m),re.createElement(Y,{color:a},f),r&&re.createElement(Y,{color:br.DIM},g))},"Divider");hC(),Vr(),Bt(),Vr();var HP=[{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}],WP=__name(({onComplete:e,onExit:t})=>{const[n,r]=se(0),[o,s]=se(!1),i=n>=HP.length;return ae(()=>{if(n>=HP.length)return;if(o)return;const e=HP[n],t=setTimeout(()=>{r(e=>Math.min(e+1,HP.length))},e.duration);return()=>clearTimeout(t)},[n,o]),Z((n,o)=>{""===n||o.ctrl&&"c"===n?t?t():e():o.escape?e():i?(o.return||" "===n)&&e():" "===n?s(e=>!e):o.return&&r(e=>Math.min(e+1,HP.length))}),re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Meet Your Coding Taste")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Command Code learns your coding style as you work.")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Here's how your preferences evolve in real-time:")),re.createElement(Q,{flexDirection:"column",marginY:1},HP.slice(0,n).map((e,t)=>"user"===e.type?re.createElement(Q,{key:t},re.createElement(Y,null,Re.pointer," ",e.text)):re.createElement(Q,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"⎿ "),re.createElement(Y,{color:vr.TEXT},e.text)),e.details&&re.createElement(Q,{marginLeft:3},re.createElement(Y,{color:br.DIM},"Saved(",e.details,")"))))),i?re.createElement(Q,{flexDirection:"column",marginY:1},re.createElement(Q,null,re.createElement(Y,{bold:!0,color:vr.TEXT},"Demo Complete!")),re.createElement(Q,null,re.createElement(Y,null,"Command Code will now use these preferences to generate")),re.createElement(Q,null,re.createElement(Y,null,"better suggestions tailored to your coding style. The")),re.createElement(Q,null,re.createElement(Y,null,"more you code, the smarter it gets.")),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Enter to get started →"))):re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(o?" (paused)":""))))},"TasteDemoComponent"),GP=__name(({onClose:e,onExit:t})=>{const[n,r]=se(FC.getEvents()),[o,s]=se(0);Z((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),ae(()=>{const e=__name(()=>{r(FC.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return FC.on("new-event",e),FC.on("cleared",t),()=>{FC.off("new-event",e),FC.off("cleared",t)}},[]),ae(()=>{const e=__name(()=>{uC(),s(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=le(()=>n.find(e=>"analyzing"===e.type),[n]),l=le(()=>n.find(e=>"analyzed"===e.type),[n]),u=le(()=>n.find(e=>"no_learnings"===e.type),[n]),d=le(()=>n.find(e=>"learned"===e.type||"refactored"===e.type),[n]),m=u?n.indexOf(u):1/0,g=d?n.indexOf(d):1/0,h=!!u&&m<g,f=!!a||!!l||h,y=le(()=>n.filter(e=>"analyzing"!==e.type&&"analyzed"!==e.type&&"no_learnings"!==e.type),[n]),w=le(()=>[...y].reverse(),[y]),S=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`confidence: ${parseFloat(e).toString()}%`}const i={learned:"LEARNED",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),E=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),v=__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"),C=le(()=>(process.stdout.rows??24)-1,[o]);return re.createElement(Q,{flexDirection:"column",width:"100%",height:C,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(qP,null,DP())),re.createElement(zP,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),re.createElement(Q,{flexDirection:"column"},0===n.length?re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Q,null,re.createElement(Y,null,"Start using Command Code and it will begin recording your coding taste.")),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Your preferences, patterns, and style will appear here in real-time."))),re.createElement(ne,{count:2}),re.createElement(zP,{title:"DEMO",titleColor:"white",subPrefix:!0}),re.createElement(WP,{onComplete:()=>{e()},onExit:t})):re.createElement(Q,{flexDirection:"column"},y.length>0&&re.createElement(Q,{flexDirection:"column",gap:1},w.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:o}=S(e.message),s="moved"===t?v(e.details):null,i="upgraded"===t||"downgraded"===t?E(r):null,a=s?.fullPath??e.details;let l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:br.DIM}," ","(",o,")"));return i&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",i.text," ("),re.createElement(Y,{color:br.DIM},"confidence:"," "),re.createElement(Y,{color:br.DIM},i.oldPercent,"%"),re.createElement(Y,null," ",Re.arrowRight," "),re.createElement(Y,{color:i.diff>0?br.GREEN:br.RED},i.newPercent,"%"),re.createElement(Y,null,")"))),s&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",s.category," ","package ("),re.createElement(Y,{color:br.DIM},s.oldPath),re.createElement(Y,null," ",Re.arrowRight," ",s.newPath),re.createElement(Y,null,")"))),re.createElement(Q,{key:e.id},re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:vr.BADGE_BG,color:vr.BADGE_FG,bold:!0},`${Lx}${n}${Lx}`)),a&&re.createElement(Y,{color:br.DIM}," ","(",a,")")),re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM},"⎿"," "),l)))}return re.createElement(Q,{key:e.id},re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",e.message))})),f&&re.createElement(Q,{flexDirection:"column",marginTop:y.length>0?1:0},a&&re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",a.message)),l&&re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",l.message)),h&&u&&re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," ",u.message))))))},"LearningFeedFull");function useListNavigation({items:e,onSelect:t,onCancel:n,validate:r,initialIndex:o=0,searchCursorIndex:s=0,searchQuery:i,onSearchChange:a,isActive:l=!0,disableSearch:u=!1,selectByNumber:d=!1,onReset:m}){const[g,h]=se(o),[f,y]=se(null);ae(()=>{i||h(o)},[o,i]);const w=e.length-1,S=__name(e=>{a(e),h(s)},"updateSearch");return Z((o,s)=>{if(s.escape)return!u&&i?void S(""):void n();if(u||!s.backspace&&!s.delete){if(u&&m&&"r"===o&&!s.ctrl&&!s.meta){const t=e[g];return void(t&&m(t))}if(0!==e.length){if(s.upArrow)return y(null),void h(e=>Math.max(e-1,0));if(s.downArrow)return y(null),void h(e=>Math.min(e+1,w));if(s.return){const n=e[g];if(!n)return;if(r){const e=r(n);if(e)return void y(e)}return void t(n)}if(d&&1===o.length&&o>="1"&&o<="9"&&!s.ctrl&&!s.meta){const n=Number(o)-1,s=e[n];if(!s)return;if(h(n),r){const e=r(s);if(e)return void y(e)}return void t(s)}!u&&!s.ctrl&&!s.meta&&!s.tab&&o&&1===o.length&&o>=" "&&S(i+o)}}else S(i.slice(0,-1))},{isActive:l}),{cursor:g,error:f,setError:y}}Bt(),Bt(),Vr(),Bt(),__name(useListNavigation,"useListNavigation");var VP=[{scope:"project",label:"This project"},{scope:"global",label:"User"}],KP=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=se(!0),[s,i]=se(void 0),[a,l]=se(void 0),[u,d]=se(!0),m="local"===a,g=ce(async()=>{try{const e=await getTasteLearningSettings();o(e.global),i(e.project),l(e.projectSource)}catch{}},[]);ae(()=>{g().finally(()=>d(!1))},[g]);const h=__name(async(e,n,r)=>{e();try{await r(),t?.(),await g()}catch(e){n()}},"persist"),f=__name(e=>{if("global"===e.scope){const e=!r;return h(()=>o(e),()=>o(!e),()=>setTasteLearning({tasteLearning:e,scope:"global"}))}if(m)return;const t=s,n=!(t??r);return h(()=>i(n),()=>i(t),()=>setTasteLearning({tasteLearning:n,scope:"project"}))},"toggleRow"),y=__name(e=>{if("global"===e.scope){if(r)return;return h(()=>o(!0),()=>o(!1),()=>setTasteLearning({tasteLearning:!0,scope:"global"}))}if(m)return;const t=s;return void 0!==t?h(()=>i(void 0),()=>i(t),()=>clearProjectTasteLearning()):void 0},"resetRow"),{cursor:w}=useListNavigation({items:VP,onSelect:__name(e=>{f(e)},"onSelect"),onReset:__name(e=>{y(e)},"onReset"),onCancel:e,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:!u});if(u)return re.createElement(Q,{key:n,borderStyle:"single",borderColor:br.BLUE,padding:1,flexDirection:"column"},re.createElement(Y,{color:br.BLUE,bold:!0},"Taste Settings"),re.createElement(Y,{color:br.DIM},"Loading configuration..."));const S=__name(e=>"project"===e.scope?s??r:r,"valueFor");return re.createElement(Q,{key:n,borderStyle:"single",borderColor:br.GRAY,padding:1,flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Taste Learning"),re.createElement(Y,{color:br.DIM},"Learn from your interactions."),re.createElement(Q,{marginTop:1}),VP.map((e,t)=>{const n=t===w,r=S(e),o="project"===e.scope&&m;return re.createElement(Q,{key:e.scope},re.createElement(Y,{color:n?br.CYAN:br.GRAY},n?`${Re.pointer} `:" "),re.createElement(Y,{color:n?br.CYAN:br.WHITE},e.label.padEnd(16)),re.createElement(Y,{color:r?br.GREEN:br.DIM},r?"enabled":"disabled"),o?re.createElement(Y,{color:br.DIM}," ","(set in settings.local.json)"):null)}),re.createElement(Q,{marginTop:1}),re.createElement(Y,{color:br.DIM},"Taste data stored in .commandcode/taste/taste.md"),m?re.createElement(Y,{color:br.DIM},"This project is pinned by .commandcode/settings.local.json — edit that file to change it."):null,re.createElement(Y,{color:br.DIM},"↑/↓ navigate · enter to toggle · r reset to default · esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,onClose:t,loadTasteStatus:n}){return re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(KP,{onClose:t,onSettingsChange:n,staticKey:e})))}function fuzzyMatch(e,t){let n=0;for(const r of e)if(r===t[n]&&(n++,n===t.length))return!0;return!1}function fuzzyScore(e,t){let n=0;for(const r of e)fuzzyMatch(r.text.toLowerCase(),t)&&(n+=r.weight);return n}function fuzzyFilter(e,t,n){if(!t.trim())return e;const r=t.toLowerCase().split("");return e.map(e=>({item:e,score:fuzzyScore(n(e),r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score).map(({item:e})=>e)}__name(TasteConfigView,"TasteConfigView"),Bt(),Bt(),_n(),Bt(),__name(fuzzyMatch,"fuzzyMatch"),__name(fuzzyScore,"fuzzyScore"),__name(fuzzyFilter,"fuzzyFilter"),Vr(),Bt(),Vr();var QP=__name(({query:e,resultCount:t,placeholder:n="Type to search..."})=>re.createElement(Q,{width:"100%"},re.createElement(Y,{color:br.GRAY},Re.pointerSmall," "),re.createElement(Y,{color:e?br.WHITE:br.GRAY},e||n),e&&void 0!==t&&re.createElement(Y,{dimColor:!0}," (",t," found)")),"SearchInput");function useTerminalHeight(){const{stdout:e}=X(),[t,n]=se(()=>e?.rows??24);return ae(()=>{const t=__name(()=>n(e?.rows??24),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function skillIdentifier(e){const n=t.basename(e);return"skill.md"===n.toLowerCase()?t.basename(t.dirname(e)):n}Bt(),__name(useTerminalHeight,"useTerminalHeight"),Bt(),_n(),Vr(),Bt(),hC(),Vr(),ko(),Bt(),__name(skillIdentifier,"skillIdentifier");var YP=new Set(["Invalid YAML","Missing fields","Missing SKILL.md"]);function categoryColor(e){return YP.has(e)?br.RED:br.YELLOW}function formatWarningsAsMarkdown(e){const t=groupWarnings(e),n=[`# Skipped skills (${e.length})`,""];for(const e of t){n.push(`## ${e.category} (${e.items.length})`,"");for(const t of e.items)n.push(`- \`${skillIdentifier(t.path)}\` — \`${t.path}\``),n.push(` - ${t.reason}`);n.push("")}return n.join("\n").replace(/\n+$/,"")+"\n"}async function copyAllWarnings(e,t){try{const{isClipboardAvailable:n}=await Promise.resolve().then(()=>(so(),ro));if(!n())return void t({text:"Clipboard unavailable — copy the skipped skill paths manually",color:br.YELLOW});const r=await import("@crosscopy/clipboard");await r.default.setText(formatWarningsAsMarkdown(e));const o=e.length;t({text:`Copied ${o} issue${1===o?"":"s"} to clipboard`,color:br.GREEN})}catch{t({text:"Clipboard write failed",color:br.YELLOW})}}__name(categoryColor,"categoryColor"),__name(formatWarningsAsMarkdown,"formatWarningsAsMarkdown"),__name(copyAllWarnings,"copyAllWarnings");var JP=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,i]=se(null),a=ie(null),l=ie(!0);ae(()=>()=>{l.current=!1,a.current&&(clearTimeout(a.current),a.current=null)},[]);const u=__name(e=>{l.current&&(a.current&&clearTimeout(a.current),i(e),a.current=setTimeout(()=>{l.current&&(i(null),a.current=null)},3e3))},"showStatus");return Z((n,r)=>r.escape||" "===n&&o?(uC(),void t()):void("c"===n&&o&&copyAllWarnings(e,u)),{isActive:n}),re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Skills"," "),re.createElement(Y,{color:br.DIM},"› "),re.createElement(Y,{color:Er,bold:!0},"Skipped"," "),re.createElement(Y,{color:br.WHITE},e.length)),o&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Press c to copy all issues")),o?re.createElement(Q,{flexDirection:"column"},r.map(e=>re.createElement(Q,{key:e.category,flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:categoryColor(e.category)},e.category)),e.items.map(e=>re.createElement(Q,{key:e.path,flexDirection:"column",marginBottom:1},re.createElement(Q,{paddingLeft:2},re.createElement(Eo,{url:m(e.path).href,text:skillIdentifier(e.path),color:br.WHITE})),re.createElement(Q,{paddingLeft:4},re.createElement(Y,{color:br.WHITE},e.reason))))))):re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"No issues — every skill loaded.")),s&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:s.color},s.text)),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),XP=__name(({warnings:e=[],onClose:t})=>{const[n,r]=se("list");return Z((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?re.createElement(JP,{warnings:e,onClose:()=>r("list"),isActive:!0}):re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Skills"),e.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.YELLOW},e.length," skipped"))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"No skills found")),re.createElement(Y,{color:br.DIM},"Create skills in:"),re.createElement(Y,{color:br.DIM}," ","~/",".commandcode","/","skills","/ (user)"),re.createElement(Y,{color:br.DIM}," ","~/.agents/","skills","/ (user, .agents)"),re.createElement(Y,{color:br.DIM}," ",".commandcode","/","skills","/ (project)"),re.createElement(Y,{color:br.DIM}," ",".agents/","skills","/ (project, .agents)"),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},e.length>0&&"space to view issues · ","Press ",re.createElement(Y,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");function clampScrollOffset(e){const{cursor:t,total:n,maxVisible:r,currentOffset:o}=e;if(n<=r)return 0;let s=o;t<s?s=t:t>=s+r&&(s=t-r+1);const i=Math.max(0,n-r);return Math.min(Math.max(0,s),i)}function sliceSectionForWindow(e){const{section:t,sectionBase:n,windowStart:r,windowEnd:o}=e,s=Math.min(Math.max(r-n,0),t.length),i=Math.min(Math.max(o-n,0),t.length);return{rows:t.slice(s,i),baseIndex:n+s}}Bt(),__name(clampScrollOffset,"clampScrollOffset"),__name(sliceSectionForWindow,"sliceSectionForWindow"),Bt();var ZP=__name(e=>Math.ceil(e.length/4),"estimateTokens"),eI=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),tI={user:"user settings",projectShared:"project shared",projectLocal:"project local"},nI=__name(()=>"win32"===process.platform?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===process.platform?"~/.zshrc":"~/.bashrc"),"getEditorSetupMessage");Bt(),Vr();var rI=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Q,null,re.createElement(Y,{color:Mr,bold:!0},e," "),re.createElement(Y,{color:Mr},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=eI(e.filePath),l=n?zr:void 0;return re.createElement(Q,{key:e.filePath},re.createElement(Y,{color:i?br.DIM:br.GREEN,backgroundColor:l},i?"[off] ":"[on] "),re.createElement(Y,{color:i?br.DIM:br.WHITE,backgroundColor:l},e.label),a&&re.createElement(Y,{color:br.DIM,backgroundColor:l}," [.agents]"),re.createElement(Y,{color:br.DIM,backgroundColor:l}," · ~",ZP(e.description)," tokens "))})),"SkillSection");Bt();var oI=__name(e=>[{text:e.label,weight:100}],"SKILL_SEARCH_FIELDS"),sI=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se([]),[s,i]=se(!0),[a,l]=se(null),[u,d]=se(""),[m,g]=se(new Set),[h,f]=se(new Map),[y,w]=se(!1),[S,E]=se(null),[v,C]=se("list"),[k,T]=se(0),_=useTerminalHeight(),x=ie(!1);ae(()=>{__name(async()=>{try{const e=findGitRoot(),t=getBundledSkillsDir(),[{global:r,project:s,warnings:i},a]=await Promise.all([loadAllSkillSummariesWithWarnings(),loadDisabledSkills({projectRoot:e})]),l=__name(e=>isBundledSkillPath({filePath:e,bundledDir:t}),"isBundled"),u=[...s.map(e=>({label:e.name,location:"project",description:e.description,filePath:e.filePath})),...r.filter(e=>!l(e.filePath)).map(e=>({label:e.name,location:"user",description:e.description,filePath:e.filePath})),...r.filter(e=>l(e.filePath)).map(e=>({label:e.name,location:"bundled",description:e.description,filePath:e.filePath}))];u.sort((e,t)=>{if(e.location!==t.location){const n={project:0,user:1,bundled:2};return n[e.location]-n[t.location]}return e.label.localeCompare(t.label)}),n(u),o(i),g(new Set(a.names)),f(new Map(a.bySkill)),w(a.noProjectRoot)}catch(e){l(e instanceof Error?e.message:"Failed to load skills")}finally{i(!1)}},"load")()},[]);const A=le(()=>fuzzyFilter(t.filter(e=>"project"===e.location),u,oI),[t,u]),P=le(()=>fuzzyFilter(t.filter(e=>"user"===e.location),u,oI),[t,u]),I=le(()=>fuzzyFilter(t.filter(e=>"bundled"===e.location),u,oI),[t,u]),M=le(()=>[...A,...P,...I],[A,P,I]),R=_-1,N=(A.length>0?1:0)+(P.length>0?1:0)+(I.length>0?1:0),L=Math.max(4,R-12-2*N),$=__name(async e=>{if(x.current)return;const t=m.has(e.label),n=h.get(e.label);if(t&&void 0!==n&&"projectLocal"!==n&&!y)return void E(`Cannot enable: "${e.label}" is disabled in ${tI[n]}. Edit that file to override.`);x.current=!0;const r=new Set(m);t&&r.delete(e.label),t||r.add(e.label),g(r),E(null);try{const n=findGitRoot(),r=await setSkillEnabled(e.label,t,{projectRoot:n}),o=new Map(h);t&&o.delete(e.label),t||o.set(e.label,r),f(o),"user"===r&&E("Saved to user settings — no project found.")}catch(e){g(m),E(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{x.current=!1}},"toggleSkill");ae(()=>{"issues"===v&&d("")},[v]);const D="list"===v&&t.length>0,{cursor:O}=useListNavigation({items:M,onSelect:$,onCancel:e,searchQuery:u,onSearchChange:d,initialIndex:0,isActive:D});if(ae(()=>{T(e=>clampScrollOffset({cursor:O,total:M.length,maxVisible:L,currentOffset:e}))},[O,M.length,L]),Z((t,n)=>{if(!n.tab)return;const r=M[O];r&&(async()=>{try{await Et([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(nI());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),Z((e,n)=>{"list"===v&&0!==t.length&&" "===e&&!n.ctrl&&!n.meta&&r.length>0&&0===u.length&&C("issues")},{isActive:"list"===v&&t.length>0}),s)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:Er,bold:!0},"Skills"),re.createElement(Y,{color:br.DIM},"Loading skills..."));if(a)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:br.RED,bold:!0},"Skills"),re.createElement(Y,{color:br.DIM},a),re.createElement(Q,{marginTop:1}),re.createElement(Y,{color:br.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close"));if(0===t.length)return re.createElement(XP,{warnings:r,onClose:e});if("issues"===v)return re.createElement(JP,{warnings:r,onClose:()=>C("list"),isActive:!0});const F=t.filter(e=>m.has(e.label)).length,j=k,U=k+L,B=sliceSectionForWindow({section:A,sectionBase:0,windowStart:j,windowEnd:U}),q=sliceSectionForWindow({section:P,sectionBase:A.length,windowStart:j,windowEnd:U}),z=sliceSectionForWindow({section:I,sectionBase:A.length+P.length,windowStart:j,windowEnd:U}),H=M.length>L;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Skills"," "),re.createElement(Y,{color:br.DIM},t.length," skill",1===t.length?"":"s"),F>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.YELLOW},F," off")),r.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.YELLOW},r.length," skipped"))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{dimColor:!0},y?"No project found — toggles will be saved to user settings.":"Toggle skills on or off for this project.")),re.createElement(Q,{marginBottom:1,flexDirection:"column",width:"100%"},re.createElement(QP,{query:u,resultCount:u?M.length:void 0,placeholder:"Type to search skills..."})),0===M.length?re.createElement(Q,{marginY:1},re.createElement(Y,{color:br.GRAY},'No skills match "',u,'"')):re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},B.rows.length>0&&re.createElement(rI,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:B.rows,baseIndex:B.baseIndex,cursor:O,disabled:m}),q.rows.length>0&&re.createElement(rI,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:q.rows,baseIndex:q.baseIndex,cursor:O,disabled:m}),z.rows.length>0&&re.createElement(rI,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:z.rows,baseIndex:z.baseIndex,cursor:O,disabled:m})),H&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",j+1,"–",Math.min(U,M.length)," of"," ",M.length,j>0?" · ↑ more":"",U<M.length?" · ↓ more":""))),S&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.YELLOW},S)),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},"type to search · ↑/↓ navigate · enter to toggle · tab to edit",r.length>0&&!u&&re.createElement(re.Fragment,null," · space to view issues"),u?" · esc to clear":" · esc to close"),re.createElement(Y,{color:br.DIM},"add skills:"," ",re.createElement(Y,{color:br.CYAN},"cmd skills add ","<owner/repo>"))))},"SkillsConfig");function SkillsConfigView({staticKey:e,onClose:t}){return re.useEffect(()=>{hardResetForResize()},[]),re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(sI,{onClose:t,staticKey:e})))}function getUsageColor(e){return e>=80?br.RED:e>=50?br.YELLOW:br.GREEN}function buildBlockBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e));let r=Math.round(n/100*t);n>.5&&0===r&&(r=1),n<99.5&&r===t&&(r=t-1);const o=t-r;return{filled:"█".repeat(r),empty:"░".repeat(o)}}function getStudioUsageUrl(e){const t=e?.org?.login??e?.user?.userName;return t?`https://commandcode.ai/${t}/settings/usage`:null}__name(SkillsConfigView,"SkillsConfigView"),Bt(),Bt(),Vr(),Bt(),Vr(),__name(getUsageColor,"getUsageColor"),__name(buildBlockBar,"buildBlockBar"),ko(),__name(getStudioUsageUrl,"getStudioUsageUrl");var iI=__name(e=>e.replace(/^https?:\/\//,""),"stripScheme");function getProgressBarWidth({terminalWidth:e}){return e<50?Math.max(10,e-10):e<70?Math.max(15,e-15):Math.min(30,e-15)}function getDaysColor(e){if(null!==e)return e<3?br.RED:e<7?br.YELLOW:void 0}__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var aI=__name(({plan:e,status:t})=>re.createElement(Q,{marginBottom:0},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:br.BLUE,color:"#f4f4f4",bold:!0},`${Lx}USAGE${Lx}`)),e&&re.createElement(re.Fragment,null,re.createElement(Y,null," "),re.createElement(Y,{color:br.GRAY},`${e.name} Plan`)),t&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:"active"===t?br.GREEN:br.YELLOW},t))),"UsageBadge"),lI=__name(({showRetry:e})=>re.createElement(Q,{marginTop:1},e&&re.createElement(Y,{color:br.DIM},re.createElement(Y,{bold:!0},"r")," to retry · "),re.createElement(Y,{color:br.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close")),"UsageFooter"),cI=__name(({onClose:e})=>{const[t,n]=se("loading"),[r,o]=se(null),[s,i]=se(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ce(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return i(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),u=re.useRef(null);Z((r,o)=>{if(o.escape&&e(),"r"===r&&"error"===t){n("loading"),u.current?.abort();const e=new AbortController;u.current=e,l(e.signal)}}),ae(()=>{const e=new AbortController;return u.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?.subscription?.data??null,m=d?getPlanInfo({planId:d.planId??""}):null;if("loading"===t)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(aI,{plan:m,status:d?.status??null}),re.createElement(Y,{color:br.DIM},"Loading…"),re.createElement(lI,null));if("error"===t)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(aI,{plan:m,status:d?.status??null}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),re.createElement(lI,{showRetry:!s}));if(!r)return null;const g=r.credits||r.subscription,h=getStudioUsageUrl(r.whoami);if(!g)return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(aI,{plan:m,status:d?.status??null}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"No billing data found."),h&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," Visit "),re.createElement(Eo,{url:h,text:"Studio",color:br.CYAN}),re.createElement(Y,{color:br.DIM}," for usage details."))),re.createElement(lI,null));const f=r.credits?.credits,y=r.summary,w=Math.max(0,f?.monthlyCredits??0)+Math.max(0,f?.purchasedCredits??0)+Math.max(0,f?.freeCredits??0),S=Math.max(0,y?.totalCost??0),E=getUsagePercent({used:S,total:S+w}),v=w>0||S>0,C=d?.currentPeriodEnd?getDaysRemaining(d.currentPeriodEnd):null,k=getDaysColor(C),T=getUsageColor(E),_=buildBlockBar({percentage:E,width:a});return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,{marginBottom:1},re.createElement(aI,{plan:m,status:d?.status??null})),v?re.createElement(Q,null,re.createElement(Y,{color:T},_.filled),re.createElement(Y,{color:Mr},_.empty),re.createElement(Y,{bold:!0,color:T},` ${Math.round(E)}% used`)):re.createElement(Y,{color:br.DIM},"Plan details unavailable"),v&&re.createElement(Q,null,d?.currentPeriodEnd&&re.createElement(Y,{color:br.DIM},"Cycle: "),re.createElement(Y,null,formatCredits(w)),re.createElement(Y,{color:br.DIM}," left"),y&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,null,y.totalCount.toLocaleString()),re.createElement(Y,{color:br.DIM}," requests")),null!==C&&re.createElement(re.Fragment,null,re.createElement(Y,{color:br.DIM}," · "),0===C?re.createElement(Y,{color:k},"renewal today"):re.createElement(re.Fragment,null,re.createElement(Y,{color:k},`${C} day${1===C?"":"s"}`),re.createElement(Y,{color:br.DIM}," to renewal")))),h&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Full breakdown at "),re.createElement(Eo,{url:h,text:iI(h),color:br.CYAN})),re.createElement(lI,null))},"UsageOverlay");function UsageView({staticKey:e,onClose:t}){return re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(cI,{onClose:t})))}__name(UsageView,"UsageView"),Bt(),Bt(),_n(),SE(),QS(),Gb(),Co();var uI="System prompt",dI="Messages";function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&!isHiddenTranscriptMessage({message:r})&&t++,"assistant"===r.message.role&&n++;return{user:t,assistant:n}}function countToolCalls({messages:e}){let t=0,n=0;for(const r of e){if(isHiddenTranscriptMessage({message:r}))continue;const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)isHiddenTranscriptMessage({message:n})||(t+=estimateTokens(n.message));return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:Cn.TIER_1_THRESHOLD,description:`Prune to last ${Cn.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:Cn.TIER_2_THRESHOLD,description:`Prune to last ${Cn.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:Cn.TIER_3_THRESHOLD,description:"Full summarization"}];let o=0;const s=r.map(r=>{const s=Math.round(r.threshold*t),i=Math.max(0,s-e);let a="upcoming";return n>=r.threshold&&(a="passed",o=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:s,description:r.description,status:a,tokensAway:i}}),i=s.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?s.map((e,t)=>t===i?{...e,status:"current"}:e):s,currentTier:o,keepRecentTokens:Cn.KEEP_RECENT_TOKENS}}function getPrimaryTip({percentage:e,conversationPct:t}){return e>=90?"Tier 3 auto-compact imminent — /compact now to control what gets summarized":e>=80?"Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in":t>60&&e>40?`${t}% is conversation — /compact to reclaim tokens`:e>=50?"/compact to free space · /model to switch models":null}function getSecondaryTip({mcpToolCount:e,imageCount:t,messageCount:n,percentage:r}){return e>0&&r>30?`${e} MCP tools loaded — disconnect unused servers to save tokens`:t>0&&r>30?`${t} image${t>1?"s":""} in context — images use ~1.5k tokens each`:n>50&&r>40?`${n} messages — consider starting a new session for a fresh context`:null}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:o,imageCount:s}){if(0===n)return[];const i=getPrimaryTip({percentage:e,conversationPct:Math.min(100,Math.round(t/n*100))}),a=getSecondaryTip({mcpToolCount:r,imageCount:s,messageCount:o,percentage:e}),l=[];return i&&l.push(i),a&&l.push(a),0===l.length&&l.push("/compact to summarize and free context · /model to switch models"),l}async function collectMemoryItems(){const e=(await discoverMemoryFiles(process.cwd())).filter(e=>e.exists),t=[];for(const n of e){const e=await loadMemoryFile(n.path),r=e?estimateTokens(e):0,o=process.env.HOME??"",s=o&&n.path.startsWith(o)?`~${n.path.slice(o.length)}`:n.path;t.push({name:n.description,tokens:r,source:s})}return t}function collectBuiltInTools(){const e=[];for(const t of T_){const n=JSON.stringify(t.input_schema??{}),r=estimateTokens(`${t.name} ${t.description??""} ${n}`);e.push({name:t.name,tokens:r})}for(const t of __){const n=estimateTokens(`${t.name} ${t.type}`);e.push({name:t.name,tokens:n})}return e}function collectMcpTools(){const e=getMcpConnectionManager().getConnectedServers(),t=[];for(const n of e)if("connected"===n.status)for(const e of n.tools){const r=JSON.stringify(e.inputSchema??{}),o=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:o,source:n.name})}return t}async function collectSkillItems(){const[e,{names:t}]=await Promise.all([loadAllSkillSummaries(),loadDisabledSkills()]);return deduplicateSkills({project:e.project.filter(e=>!t.has(e.name)),global:e.global.filter(e=>!t.has(e.name))}).map(e=>({name:e.name,tokens:estimateTokens(`${e.name} ${e.description}`)}))}async function collectAgentItems(){const e=await loadAllAgents(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.personal){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"user"})}return t}function sumTokens(e){let t=0;for(const n of e)t+=n.tokens;return t}async function analyzeContext({contextEngine:e}){const t=e.getContextTokensUsed(),n=e.getSystemPromptBreakdown(),r=getConfiguredModel(),o=getContextLimit(r),s=e.getHistory(),i=countMessagesByRole({messages:s}),a=countToolCalls({messages:s}),l=countImages({messages:s}),u=estimateConversationTokens({messages:s}),d=collectBuiltInTools(),m=collectMcpTools(),[g,h,f]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),y=sumTokens(d),w=sumTokens(m),S=sumTokens(g),E=sumTokens(h),v=sumTokens(f),C=t>0,k=n?n.memory:v,T=null!==n&&Math.abs(v-n.memory)>50,_=n?n.taste:0,x=y+w+S+E,A=C?t:u+x+k+_,P=!C&&s.length>0,I=Math.min(A/o*100,100),M=Math.max(0,o-A),R=[];if(A>0){const e=n?n.systemPrompt:Math.max(0,A-u-x-k-_);if(e>0&&R.push({name:uI,tokens:e,detail:n?"identity":"identity + taste"}),k>0&&R.push({name:"Memory",tokens:k,detail:T?"memory files (modified, refreshes next request)":"memory files"}),_>0&&R.push({name:"Taste",tokens:_,detail:"taste.md"}),y>0&&R.push({name:"System tools",tokens:y,detail:`${d.length} built-in`}),w>0){const e=Array.from(new Set(m.map(e=>e.source).filter(e=>"string"==typeof e)));let t=`${m.length} tools`;e.length>3&&(t=`${e.length} servers`),e.length>=1&&e.length<=3&&(t=e.join(", ")),R.push({name:"MCP",tokens:w,detail:t})}S>0&&R.push({name:"Skills",tokens:S,detail:`${g.length} loaded`}),E>0&&R.push({name:"Subagents",tokens:E,detail:`${h.length} loaded`});const r=e+k+_+x,o=C?Math.max(0,t-r):u;o>0&&R.push({name:dI,tokens:o,detail:`${i.user} user · ${i.assistant} assistant`})}R.sort((e,t)=>e.name===uI?-1:t.name===uI||e.name===dI?1:t.name===dI?-1:t.tokens-e.tokens);const N=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:A,tokenLimit:o,percentage:I,tokensRemaining:M,isEstimated:P,model:r,breakdown:R,autoCompact:buildAutoCompactStatus({tokensUsed:A,tokenLimit:o}),stats:{messageCount:s.length,userMessages:i.user,assistantMessages:i.assistant,toolCalls:a.calls,toolResults:a.results,imageCount:l,sessionStartTime:N},tips:generateTips({percentage:I,conversationTokens:u,totalTokens:A,mcpToolCount:m.length,messageCount:s.length,imageCount:l})}}function formatK(e){if(e<1e3)return String(e);if(e>=1e6){const t=Math.round(e/1e5)/10;return Number.isInteger(t)?`${t}M`:`${t.toFixed(1)}M`}const t=e/1e3;return Number.isInteger(t)?`${t}k`:`${t.toFixed(1)}k`}function formatBreakdownValue(e){return e<1e3?String(e):`${(e/1e3).toFixed(1)}k`}function getLayoutSizes({terminalWidth:e}){const t=Math.max(20,e),n=Math.min(50,Math.max(30,Math.floor(.5*t)));return{labelWidth:16,progressBarWidth:Math.max(10,Math.min(n,t-10)),showBreakdownDetail:t>=70}}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildBlockBar({percentage:e.percentage,width:t});return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:br.BLUE,color:"#f4f4f4",bold:!0},`${Lx}CONTEXT${Lx}`)),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:br.GRAY},getModelDisplayName(e.model))),re.createElement(Q,null,re.createElement(Y,{color:n},r.filled),re.createElement(Y,{color:Mr},r.empty),re.createElement(Y,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),re.createElement(Q,null,re.createElement(Y,null,formatK(e.tokensUsed)),re.createElement(Y,{color:br.GRAY},` / ${formatK(e.tokenLimit)}`),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:n},formatK(e.tokensRemaining)),re.createElement(Y,{color:br.GRAY}," remaining"),e.isEstimated&&re.createElement(Y,{color:br.DIM}," (estimated)")))}function CompactionDistance({analysis:e}){if(e.percentage<40)return null;const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const{tokensAway:n}=t;let r=br.GRAY;return n<=5e4&&(r=br.YELLOW),n<=2e4&&(r=br.RED),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:r},`~${formatK(n)}`),re.createElement(Y,{color:br.DIM}," until auto-compact"))}function BreakdownRow({item:e,labelWidth:t,numWidth:n,showDetail:r}){return re.createElement(Q,null,re.createElement(Y,null,e.name.padEnd(t)),re.createElement(Y,{bold:!0},formatBreakdownValue(e.tokens).padStart(n)),re.createElement(Y,{color:br.GRAY}," tokens"),r&&e.detail&&re.createElement(Y,{color:br.DIM},` · ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,showBreakdownDetail:n}){const r=e.breakdown.filter(e=>e.tokens>0);if(0===r.length)return null;const o=Math.max(4,...r.map(e=>formatBreakdownValue(e.tokens).length));return re.createElement(Q,{flexDirection:"column",marginTop:1},r.map(e=>re.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t,numWidth:o,showDetail:n})))}function ContextTips({tips:e}){return 0===e.length?null:re.createElement(Q,{flexDirection:"column",marginTop:1},e.map(e=>re.createElement(Q,{key:e},re.createElement(Y,{color:br.CYAN},Re.pointer),re.createElement(Y,{color:br.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return re.createElement(Q,{flexDirection:"column",paddingTop:1},re.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),re.createElement(CompactionDistance,{analysis:e}),re.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,showBreakdownDetail:t.showBreakdownDetail}),re.createElement(ContextTips,{tips:e.tips}))}function ContextConfigView({staticKey:e,contextEngineRef:t,onClose:n,setInput:r}){const[o,s]=se(null),[i,a]=se(null);return ae(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&s(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),Z((e,t)=>{t.escape&&(r(""),n())}),re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},i?re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Context"),re.createElement(Y,{color:br.DIM},i)):o?re.createElement(ContextMessage,{analysis:o}):re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Context"),re.createElement(Y,{color:br.DIM},"Loading context analysis...")),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Esc to return to conversation"))))}__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(getPrimaryTip,"getPrimaryTip"),__name(getSecondaryTip,"getSecondaryTip"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),Bt(),bo(),Vr(),__name(formatK,"formatK"),__name(formatBreakdownValue,"formatBreakdownValue"),__name(getLayoutSizes,"getLayoutSizes"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),Vr(),__name(ContextConfigView,"ContextConfigView"),Bt(),Bt(),_n(),ri(),QS(),Go(),Ro(),Co();var mI="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson().version,updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkAuthStatus(),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(){try{const e=await getSelectedModel(),t=getProviderDisplayName((await loadUserConfig()).provider||null);return{id:e,displayName:getModelDisplayName(e),provider:t}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}async function getSkillsAgentsStatus(){let e=0,t=0,n=0,r=0,o=0;try{const r=await loadAllSkillSummaries();e=r.global.length,t=r.project.length;const{names:o}=await loadDisabledSkills();n=[...r.global,...r.project].filter(e=>o.has(e.name)).length}catch{}try{const e=await loadAllAgents();r=e.personal.length,o=e.project.length}catch{}return{personalSkills:e,projectSkills:t,disabledSkills:n,personalAgents:r,projectAgents:o}}function execGitAsync(e){return new Promise(t=>{Te("git",e,{encoding:"utf8",cwd:process.cwd(),timeout:3e3},(e,n)=>{t(e?null:n.trim()||null)})})}async function getGitStatus2(){const e=await execGitAsync(["rev-parse","--abbrev-ref","HEAD"]);if(!e)return{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null};const[t,n]=await Promise.all([execGitAsync(["rev-parse","--show-toplevel"]),execGitAsync(["remote","get-url","origin"])]);return{branch:e,worktreePath:t,remoteUrl:n?formatRemoteUrl(n):null,remoteHttpUrl:n?buildHttpUrl(n):null}}function parseSSHUrl(e){const t=e.match(/@([^:]+):(.+?)(?:\.git)?$/);return t?.[1]&&t[2]?{host:t[1],path:t[2]}:null}function formatRemoteUrl(e){const t=parseSSHUrl(e);if(t)return t.path;const n=e.match(/\/\/[^/]+\/(.+?)(?:\.git)?$/);return n?.[1]?n[1]:e}function buildHttpUrl(e){const t=parseSSHUrl(e);if(t)return`https://${t.host}/${t.path}`;const n=e.match(/^ssh:\/\/[^@]+@([^/]+)\/(.+?)(?:\.git)?$/);return n?.[1]&&n[2]?`https://${n[1]}/${n[2]}`:/^https?:\/\//.test(e)?e.replace(/\.git$/,""):e}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}async function hasTasteMdFiles(e){if(!O(e))return!1;try{return(await I(e,{recursive:!0,encoding:"utf-8"})).some(e=>e.endsWith(".md"))}catch{return!1}}async function getTasteStatus(){const e=t.join(process.cwd(),".commandcode","taste"),n=t.join(e,"taste.md"),r=O(n),o=r||await hasTasteMdFiles(e);let s=!0;try{s=await isTasteLearningEnabled()}catch{}return{fileExists:o,filePath:r?n:e,learningEnabled:s}}function detectProxy(){const e=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy;return e?sanitizeProxyUrl(e):null}function sanitizeProxyUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString().replace(/\/$/,"")}catch{return"[malformed proxy URL]"}}function getSystemStatus(){let e,t,n,r;try{e=nA(S.platform()),t=wA(),n=SA(),r=bA()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:S.arch(),shell:n,terminal:t,nodeVersion:process.version,ide:"N/A"!==r?r:null,proxy:detectProxy()}}async function gatherStatusData(){const e=safeSync(getVersionStatus,{current:"Unknown",updateAvailable:null}),t=safeSync(getSystemStatus,{cwd:process.cwd(),os:"Unknown",arch:S.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,o,s,i]=await Promise.all([safeAsync(getAuthStatus,{authenticated:!1,username:null}),safeAsync(getModelStatus,{id:"Unknown",displayName:"Unknown",provider:"Unknown"}),safeAsync(getTasteStatus,{fileExists:!1,filePath:"",learningEnabled:!1}),safeAsync(getSkillsAgentsStatus,{personalSkills:0,projectSkills:0,disabledSkills:0,personalAgents:0,projectAgents:0}),safeAsync(getGitStatus2,{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null})]),a=safeSync(()=>getPrStatus(i.branch),null);return{version:e,auth:n,model:r,git:i,pr:a,taste:o,skillsAgents:s,system:t}}function safeSync(e,t){try{return e()}catch{return t}}async function safeAsync(e,t){try{return await e()}catch{return t}}function formatCountValue(e,t){const n=e+t;return 0===n?"None":`${n} (${e} user, ${t} project)`}function formatSkillsValue(e){const{personal:t,project:n,disabled:r}=e,o=t+n;return 0===o?"None":0===r?formatCountValue(t,n):`${o-r} active · ${r} off · (${t} user, ${n} project installed)`}function formatSystemValue({system:e}){const t=[`${e.os} ${e.arch}`];return e.ide&&t.push(e.ide),!e.terminal||e.ide&&e.ide.toLowerCase().startsWith(e.terminal.toLowerCase())||t.push(e.terminal),t.push(e.shell),t.push(`Node ${e.nodeVersion}`),t.join(" · ")}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getSkillsAgentsStatus,"getSkillsAgentsStatus"),__name(execGitAsync,"execGitAsync"),__name(getGitStatus2,"getGitStatus"),__name(parseSSHUrl,"parseSSHUrl"),__name(formatRemoteUrl,"formatRemoteUrl"),__name(buildHttpUrl,"buildHttpUrl"),__name(getPrStatus,"getPrStatus"),__name(hasTasteMdFiles,"hasTasteMdFiles"),__name(getTasteStatus,"getTasteStatus"),__name(detectProxy,"detectProxy"),__name(sanitizeProxyUrl,"sanitizeProxyUrl"),__name(getSystemStatus,"getSystemStatus"),__name(gatherStatusData,"gatherStatusData"),__name(safeSync,"safeSync"),__name(safeAsync,"safeAsync"),Bt(),_n(),dv(),Vr(),ko(),__name(formatCountValue,"formatCountValue"),__name(formatSkillsValue,"formatSkillsValue"),__name(formatSystemValue,"formatSystemValue");var pI=__name(({label:e,value:t,valueColor:n,dimValue:r})=>re.createElement(Q,null,re.createElement(Y,{dimColor:!0},`${e}:`.padEnd(14)),r?re.createElement(Y,{dimColor:!0},t):re.createElement(Y,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=e,n=t.version.updateAvailable?`v${t.version.current} → v${t.version.updateAvailable} available`:`v${t.version.current}`,r=`${t.model.provider} · ${t.model.displayName}`,o=t.git.branch||"N/A",s=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?Re.tick:Re.cross,a=t.auth.authenticated?br.WHITE:Pr.ERROR,l=t.skillsAgents.personalSkills+t.skillsAgents.projectSkills,u=t.skillsAgents.personalAgents+t.skillsAgents.projectAgents,d=t.taste.fileExists?"Active · "+(t.taste.learningEnabled?"Learning on":"Learning off"):"No taste.md";return re.createElement(Q,{flexDirection:"column",paddingX:0},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Command Code"," "),re.createElement(Y,{dimColor:!0},n)),re.createElement(Q,null,re.createElement(Y,{dimColor:!0},"Visit "),re.createElement(Eo,{url:mI,text:mI,color:br.CYAN}),re.createElement(Y,{dimColor:!0}," for usage and billing")),re.createElement(Q,{marginTop:1},re.createElement(Y,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?re.createElement(re.Fragment,null,re.createElement(Eo,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:br.CYAN}),re.createElement(Y,{color:a}," ",i)):t.auth.authenticated?re.createElement(re.Fragment,null,re.createElement(Y,null,"Authenticated"),re.createElement(Y,{color:a}," ",i)):re.createElement(re.Fragment,null,re.createElement(Y,{color:Pr.WARNING},"Not signed in"),re.createElement(Y,{color:a}," ",i),re.createElement(Y,{dimColor:!0}," — run "),re.createElement(Y,{bold:!0},"/login"))),re.createElement(pI,{label:"Model",value:r}),re.createElement(pI,{label:"Branch",value:o,dimValue:!t.git.branch}),s?re.createElement(pI,{label:"Worktree",value:s}):null,t.git.remoteUrl?re.createElement(Q,null,re.createElement(Y,{dimColor:!0},"Repository:".padEnd(14)),re.createElement(Eo,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:br.CYAN}),t.pr?re.createElement(re.Fragment,null,re.createElement(Y,{dimColor:!0}," · "),re.createElement(Eo,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?br.CYAN:br.GRAY}),re.createElement(Y,{dimColor:!0}," ","(",t.pr.state.toLowerCase(),")")):null):t.pr?re.createElement(Q,null,re.createElement(Y,{dimColor:!0},"Pull Request:".padEnd(14)),re.createElement(Eo,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?br.CYAN:br.GRAY}),re.createElement(Y,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,re.createElement(pI,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),re.createElement(pI,{label:"Directory",value:toRelativePath(t.system.cwd)}),re.createElement(pI,{label:"Skills",value:formatSkillsValue({personal:t.skillsAgents.personalSkills,project:t.skillsAgents.projectSkills,disabled:t.skillsAgents.disabledSkills}),dimValue:0===l}),re.createElement(pI,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),re.createElement(pI,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?re.createElement(pI,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,onClose:t,setInput:n}){const[r,o]=se({phase:"loading"});return ae(()=>{let e=!1;return gatherStatusData().then(t=>{e||o({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";o({phase:"error",message:n})}),()=>{e=!0}},[]),Z((e,r)=>{r.escape&&(n(""),t())}),re.createElement(re.Fragment,null,re.createElement(cP,{staticKey:e}),re.createElement(Q,{flexDirection:"column",width:"100%"},"ready"===r.phase?re.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?re.createElement(Y,{dimColor:!0},"Could not load status: ",r.message):re.createElement(Y,{dimColor:!0},"Gathering status…"),re.createElement(Q,{marginTop:1},re.createElement(Y,{dimColor:!0},"Press Esc to return to conversation"))))}function moveFocusDown(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?n>0?{...e,zone:"suggestions",suggestionIndex:0}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:e:"suggestions"===e.zone?e.suggestionIndex<n-1?{...e,suggestionIndex:e.suggestionIndex+1}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:{...e,zone:"input"}:e.activeDirIndex<r-1?{...e,activeDirIndex:e.activeDirIndex+1}:{...e,zone:"input"}}function moveFocusUp(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?r>0?{...e,zone:"active-dir",activeDirIndex:r-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:e:"suggestions"===e.zone?e.suggestionIndex>0?{...e,suggestionIndex:e.suggestionIndex-1}:{...e,zone:"input"}:e.activeDirIndex>0?{...e,activeDirIndex:e.activeDirIndex-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:{...e,zone:"input"}}function getAdjustedSuggestionOffset(e){const{selectedIndex:t,currentOffset:n,maxVisible:r,totalSuggestions:o}=e;return o<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),o=e.replace(/\\/g,"/");if(o.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${o.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:o};const s=o.lastIndexOf("/");return-1===s?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:o.slice(0,s+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),o=n.startsWith(".")||r.includes("/.");return D.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!o||!e.name.startsWith(".")).filter(e=>!n||e.name.toLowerCase().startsWith(n.toLowerCase())).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>`${r}${e.name}/`)}catch(e){const t=e.code;return"ENOENT"!==t&&"ENOTDIR"!==t&&console.error(`Warning: Could not list directory suggestions: ${t}`),[]}}function getFooterText(e){return"active-dir"===e.focusZone?"[Del] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}__name(StatusMessage,"StatusMessage"),__name(StatusConfigView,"StatusConfigView"),Bt(),Bt(),Xo(),Bt(),Xo(),__name(function createInitialFocusState(){return{zone:"input",suggestionIndex:0,activeDirIndex:0}},"createInitialFocusState"),__name(moveFocusDown,"moveFocusDown"),__name(moveFocusUp,"moveFocusUp"),__name(getAdjustedSuggestionOffset,"getAdjustedSuggestionOffset"),__name(getSuggestionBase,"getSuggestionBase"),__name(getDirectorySuggestions,"getDirectorySuggestions"),__name(getFooterText,"getFooterText"),Vr(),Xr();var gI=__name(({onClose:e})=>{const[t,n]=se(""),[r,o]=se(null),[s,i]=se([]),[a,l]=se(getAdditionalDirectories()),[u,d]=se({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=se(0);ae(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),ae(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),f=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());o({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");Z((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&s[u.suggestionIndex]?void h(s[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[u.activeDirIndex]);else{if(r.tab&&s.length>0){const e=s[u.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),ae(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,s.length]),ae(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=s.length?{...e,zone:"input",suggestionIndex:Math.max(0,s.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[s.length,a.length]);const y=s.slice(m,m+8),w=getFooterText({focusZone:u.zone});return re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:br.CYAN,paddingX:1,paddingY:0},re.createElement(Y,{bold:!0,color:br.CYAN},"Add directory to workspace"),re.createElement(Y,{color:br.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.GRAY},"Added directories"),0===a.length?re.createElement(Y,{color:br.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return re.createElement(Y,{key:e,color:n?br.YELLOW:br.GREEN,bold:n&&isLightTheme()},n?` ${Re.pointer} `:" ",formatDirectoryForDisplay(e))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0,color:br.WHITE},"Path")),re.createElement(Q,null,re.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?Re.pointer:" "} `,prefixColor:"input"===u.zone?br.CYAN:br.GRAY,onChange:e=>{n(e),o(null)},onSubmit:h})),!t&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:{error:br.RED,warning:br.YELLOW,success:br.GREEN}[r.tone]},r.text)),s.length>0&&re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:br.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return re.createElement(Y,{key:e,color:r?br.CYAN:br.GRAY,bold:r&&isLightTheme()},r?` ${Re.pointer} `:" ",e)})),re.createElement(Q,{marginTop:1},re.createElement(BracketedText,{text:w,color:br.DIM})))},"AddDirModal");Bt(),Bt(),_n(),Bt(),Bt(),_n(),Vr();var hI=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),fI=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),yI=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=se("idle"),[i,a]=se(""),l=[...T_.map(e=>e.name),...__.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void a("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?hI():fI();await k.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),i=Array.from(e.selectedTools).map(e=>P_[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await k.writeFile(s,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>P_[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Name:"),re.createElement(Y,{color:br.GRAY},e.agentType)),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Location:"),re.createElement(Y,{color:br.GRAY},m)),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Tools:"),re.createElement(Y,{color:br.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Description"),re.createElement(Y,{color:br.GRAY},"(Tells ","Command Code"," when to use this agent):")),re.createElement(Y,{color:br.GRAY},e.ccToolDefinition),re.createElement(Q,{gap:1},re.createElement(Y,{color:br.WHITE,bold:!0},"System Prompt:")),re.createElement(Y,{color:br.GRAY},e.sysPrompt),!r&&re.createElement(Q,{marginTop:1},"idle"===o&&re.createElement(Q,{gap:1},re.createElement(Y,{color:br.GREEN,dimColor:!0},"Press"),re.createElement(Y,{color:br.GREEN,bold:!0},"Enter"),re.createElement(Y,{color:br.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===o&&re.createElement(Y,{color:br.YELLOW},"Saving agent..."),"saved"===o&&re.createElement(Y,{color:br.GREEN},Re.tick," ",i),"error"===o&&re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.RED},Re.cross," Error: ",i),re.createElement(Y,{color:br.GRAY},"Press Enter to retry"))))},"AgentSummary");Vr();var wI=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=se("menu"),i=[...T_.map(e=>e.name),...__.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>I_[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect"),m=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],g=__name(async r=>{if("confirm-delete"===r.value)try{await k.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return Z((e,n)=>{if(n.escape)"menu"===o?t():s("menu");else if(n.return&&"view"===o)s("menu");else if(1===e.length&&e>="1"&&e<="9"){const t=Number(e)-1;if("menu"===o){const e=u[t];e&&d(e)}else if("delete"===o){const e=m[t];e&&g(e)}}}),"view"===o?re.createElement(Q,{flexDirection:"column"},re.createElement(yI,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},"Press Enter to go back"))):"edit"===o?re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.YELLOW},"Edit functionality coming soon..."),re.createElement(Y,{color:br.GRAY},"Press Esc to go back")):"delete"===o?re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.RED},"Delete agent"),re.createElement(Y,{color:br.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),re.createElement(Q,null,re.createElement(ft,{items:m,onSelect:g,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e},` ${t} `)}))):re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE,bold:!0},e.name),re.createElement(Q,{marginTop:1},re.createElement(ft,{items:u,onSelect:d,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e},` ${t} `)})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");Vr();var SI=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=se([]),[s,i]=se([]),[a,l]=se([]),[u,d]=se(!0),[m,g]=se(!1),[h,f]=se(null),[y,w]=se(!1),[E,v]=se(0),[C,T]=se(0),_=useTerminalHeight(),x=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),A=__name(async(e,n)=>{try{g(!1);const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=qe(s);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");ae(()=>{__name(async()=>{d(!0);const[e,...t]=await Promise.all([A(x(),"personal"),...getProjectAgentDirs().map(e=>A(e,"project"))]),n=new Set,r=[];for(const e of t.flat())n.has(e.name)||(n.add(e.name),r.push(e));const s=ZT.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));o(e),i(r),l(s),d(!1)},"loadAgents")()},[m]);const P=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{P.push({label:e.name,value:e.filePath})}),s.forEach(e=>{P.push({label:e.name,value:e.filePath})});const I=r.length+s.length,M=(r.length>0?1:0)+(s.length>0?1:0),R=__name(e=>0===e?"action":e<=r.length?"user":"project","sectionOf"),N=_-1,L=Math.max(4,N-11-a.length-2*M),$=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(f(e),w(!0))}},"handleAgentSelect");if(Z((e,t)=>{if(t.upArrow)v(e=>Math.max(0,e-1));else if(t.downArrow)v(e=>Math.min(P.length-1,e+1));else if(t.return){const e=P[E];e&&$(e)}},{isActive:!u&&!y}),ae(()=>{v(e=>Math.min(e,Math.max(0,P.length-1)))},[P.length]),ae(()=>{T(e=>clampScrollOffset({cursor:E,total:P.length,maxVisible:L,currentOffset:e}))},[E,P.length,L]),u)return re.createElement(Y,{color:br.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return re.createElement(wI,{agent:h,onBack:()=>{w(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const D=C,O=C+L,F=P.slice(D,O),j=P.length>L;let U=null;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.WHITE,bold:!0},"Agents"),I>0?re.createElement(Y,{color:br.GRAY}," ","(",I," agent",I>1?"s":"",")"):re.createElement(Y,{color:br.GRAY}," (No custom agents)")),n&&re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{color:br.GREEN,dimColor:!0},"Created agent: ",n)),re.createElement(Q,{flexDirection:"column"},F.map((e,t)=>{const n=D+t,r=R(n),o="action"!==r&&r!==U;U=r;const s=n===E,i="user"===r?"User agents":"Project agents";return re.createElement(re.Fragment,{key:e.value},o&&re.createElement(Q,{marginTop:0===t?0:1},re.createElement(Y,{color:Mr,bold:!0},i)),re.createElement(Q,null,re.createElement(Y,{color:s?br.WHITE:br.GRAY,backgroundColor:s?zr:void 0,bold:s},e.label," ")))})),j&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",D+1,"–",Math.min(O,P.length)," of ",P.length,D>0?" · ↑ more":"",O<P.length?" · ↓ more":"")),a.length>0&&re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:Mr,bold:!0},"Default agents"),a.map(e=>re.createElement(Y,{key:e.filePath,color:br.DIM},e.name.charAt(0).toUpperCase()+e.name.slice(1)))),re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:br.DIM},"Create specialized subagents that Command Code can delegate to."),re.createElement(Y,{color:br.DIM},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Bt(),_n(),li(),Vr(),Bt(),Bt(),_n(),Vr();var bI=__name(({onSelect:e})=>re.createElement(ft,{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})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},` ${t}`)}),"LocationSelector");Bt(),Xr(),_n(),so(),Qr(),Vr();var EI=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=se(!1),[g,h]=se(!1),f=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),y=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(P_).some(e=>ze(e)===ze(t))||Object.keys(P_).some(e=>ze(e)===ze(t)))&&re.createElement(Y,{color:br.RED},Re.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(ze(t))&&re.createElement(Y,{color:br.RED},Re.warning," This name is reserved. Reserved names: ",XT.join(", "))),re.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=ze(t);Object.values(P_).some(t=>ze(t)===e)||Object.keys(P_).some(t=>ze(t)===e)||isReservedAgentName(e)||a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE},"Enter the system prompt for your agent:"),re.createElement(Y,{color:br.GRAY},"Be comprehensive for best results.")),re.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?re.createElement(re.Fragment,null,re.createElement(Y,{color:br.WHITE},"When should ","Command Code"," use this agent?"),re.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Bt(),Vr();var vI=__name(({onSelect:e})=>re.createElement(ft,{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})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,bold:e&&isLightTheme()},` ${t}`)}),"MethodSelector");Bt(),Xr(),Bt(),gC(),Vr();var CI=["·","○","◇","☆","✧","☆","◇","○","⌘"],kI=[12,5,4,4,4,4,4,5,16],TI=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<kI.length;e++)if(n+=kI[e],t<n)return CI[e];const r=t-58;n=0;for(let e=0;e<TI.length;e++)if(n+=TI[e],r<n)return CI[7-e];return CI[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=le(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<jr.length?jr[n]:Ur},"getCharColor");return re.createElement(Y,null,r.map((e,t)=>re.createElement(Y,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return re.createElement(Y,{color:t??Er,bold:!0},`${getWaveSymbol(e)} `)}function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var _I=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=se(0),[s,i]=se(0),a=ie(n);a.current=n;const l=getTerminalWidth(),[u,d]=se(()=>l>=72?"all":l>=42?"medium":"none");ae(()=>{d(e=>"all"===e?l<68?l>=42?"medium":"none":"all":"medium"===e?l>=72?"all":l<38?"none":"medium":l>=72?"all":l>=42?"medium":"none")},[l]),ae(()=>{const e=setInterval(()=>{o(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const m=r%(e.length+10),g="all"===u,h="medium"===u;return aC.statusRender({width:l,layoutMode:u,status:e,frame:r}),re.createElement(Q,{width:l,height:1,paddingLeft:0,marginLeft:0},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:xr.BG,color:xr.FG}," "),re.createElement(Y,{backgroundColor:xr.BG},re.createElement(CMDIcon,{frame:4*r,color:xr.FG})),re.createElement(ShimmerText,{text:e,offset:m,bg:xr.BG}),re.createElement(Y,{backgroundColor:xr.BG,color:xr.FG}," ")),g&&re.createElement(Q,{columnGap:1,marginLeft:1},re.createElement(Y,{bold:!0,color:br.GRAY},"esc"),re.createElement(Y,{color:br.DIM},"to interrupt"),re.createElement(Y,{color:br.DIM},"•"),re.createElement(Y,{color:br.DIM},formatTime3(t)),re.createElement(Y,{color:br.DIM},"•"),re.createElement(Y,{color:br.GRAY},Re.arrowDown),re.createElement(Y,{color:br.DIM},formatToken(Math.round(s)))),h&&re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM},formatToken(Math.round(s)))))},"Status");Qr(),so(),Vr();var xI=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=se(!1),[a,l]=se(0),[u,d]=se(0);ae(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=ce(()=>{0!==e.trim().length&&n()},[e,n]),g=ce(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[s,t]);return re.createElement(Q,{flexDirection:"column"},r?re.createElement(Q,null,re.createElement(CMDIcon,{frame:u}),re.createElement(Y,{color:br.WHITE},"Generating agent from description...")):re.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),o&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.RED},`${Re.warning} ${o}`)))},"RecommendedFlow");Bt(),Vr();var AI=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=se(!1),[i,a]=se(0),[l,u]=se(0),d=useTerminalHeight(),m=le(()=>[...T_.map(e=>e.name),...__.map(e=>e.name)],[]),g=le(()=>[{name:"All tools",tools:m},{name:"Read-only tools",tools:m.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:m.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:m.filter(e=>"shell_command"===e)},{name:"Search tools",tools:m.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:m.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),[m]),h=le(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(g.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:"}),m.forEach(t=>{e.push({type:"tool",value:t})})):(g.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,g,e,m]),f=h.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=g.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]":"[ ]"} ${P_[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),y=f.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type),w=Math.max(5,d-1-10),S=y[i]?.value??0;ae(()=>{u(e=>clampScrollOffset({cursor:S,total:f.length,maxVisible:w,currentOffset:e}))},[S,f.length,w]);const E=l,v=l+w,C=f.slice(E,v),k=f.length>w;return Z((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?y.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=y.length?0:t});else if(l.return||" "===e){const e=y[i];if(e){const i=h[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(s(!o),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),re.createElement(Q,{flexDirection:"column"},C.map(e=>{const t=y.findIndex(t=>t.value===e.value),n=-1!==t&&t===i;if("divider"===e.type)return re.createElement(Q,{key:`divider-${e.value}`},re.createElement(Y,{color:br.GRAY}," ",e.label));if("spacer"===e.type)return re.createElement(Q,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return re.createElement(Q,{key:`label-${e.value}`},re.createElement(Y,{color:br.GRAY}," ",e.label));const r="continue"===e.type;return re.createElement(Q,{key:`item-${e.value}`},re.createElement(Y,{color:n?br.WHITE:br.GRAY,bold:r&&n},n?">":" "," ",e.label))}),k&&re.createElement(Q,null,re.createElement(Y,{color:br.GRAY}," ","Showing ",E+1,"–",Math.min(v,f.length)," of"," ",f.length,E>0?" · ↑ more":"",v<f.length?" · ↓ more":"")),re.createElement(Q,{marginTop:1},e.size===m.length&&re.createElement(Y,{color:br.GRAY},"All tools selected"),e.size>0&&e.size<m.length&&re.createElement(Y,{color:br.GRAY},e.size," tools selected"),0===e.size&&re.createElement(Y,{color:br.GRAY},"No tools selected")))},"ToolsSelector");No(),VS(),LS(),oi(),xC(),Co();var PI=__name(({onComplete:e})=>{const[t,n]=se("location"),[r,o]=se(!1),[s,i]=se(null),[a,l]=se("agentType"),u=le(()=>[...T_.map(e=>e.name),...__.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=se(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[Wt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[Wt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(a[Wt.OAUTH_PROVIDER]=s));const l=getApiBaseUrl(),u=new hS({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:Gt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:ze(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof Vs&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:ze(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),v=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),C=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.WHITE,bold:!0},"Create new agent"),re.createElement(Y,{color:br.GRAY},f())),re.createElement(Q,null,"location"===t&&re.createElement(bI,{onSelect:y}),"method"===t&&re.createElement(vI,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&re.createElement(xI,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:S}),"configuration"===t&&"manual"===m.method&&re.createElement(Q,{flexDirection:"column",gap:1},re.createElement(EI,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:v,onCCToolDefinitionSubmit:C})),"tools"===t&&re.createElement(AI,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&re.createElement(yI,{config:m,onSaveComplete:h})))},"AgentNew"),II=__name(({onCancel:e})=>{const[t,n]=se(null),[r,o]=se(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),re.createElement(Q,{width:"100%",flexDirection:"column"},null===t&&re.createElement(SI,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&re.createElement(PI,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");Vr(),Bt(),Co(),Vr();var MI=[{label:"Compact Normal (default)",value:"default",description:"Summarize session when context limit reached."},{label:"Compact Fast",value:"fast",description:"Fast tiered compaction. Higher quality, uses more tokens."}],RI=__name(({onSelect:e,onCancel:t})=>{const[n,r]=se(null);ae(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(Z((e,n)=>{n.escape&&t()}),null===n)return null;const s=MI.findIndex(e=>e.value===n);return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Select a compact mode to compact sessions")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Choose how Command Code handles automatic context compaction.")),re.createElement(ft,{items:MI,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>{const r=MI.find(e=>e.label===t),o=r?.value===n,s=MI.findIndex(e=>e.label===t),i=e?zr:void 0;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:e||!o?br.WHITE:br.GREEN,backgroundColor:i,bold:e||o},` ${s+1}. ${r?.label??t} `),o&&re.createElement(Y,{color:br.GREEN}," ",Re.tick)),re.createElement(Y,{color:e?br.WHITE:br.DIM,backgroundColor:i},` ${r?.description??""} `))}}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to cancel")))},"CompactModeSelector");Bt(),_n(),bo(),Ro(),Co(),Po(),Bt(),_n(),Vr();var NI=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0})=>{const i=Sn[t],a=o??i?.showProviderLabelInSelector??!1,l=e.vendorLabel??yn[e.provider],u=s&&e.id===fn,d="free"===e.badge,m=u?`${e.label} (default)`:e.label,g=d?" (FREE)":"",h=" ".repeat(Math.max(0,32-m.length-g.length)),f=n?zr:void 0,y=e.description?`${a?`${l} · `:""}${e.description}`:"",w=useTerminalWidth()>=70&&y;return re.createElement(Q,null,re.createElement(Y,{backgroundColor:f,color:r?br.GREEN:br.WHITE,bold:r},m),d&&re.createElement(Y,{backgroundColor:f,color:br.GREEN,bold:!0},g),w&&re.createElement(re.Fragment,null,re.createElement(Y,{backgroundColor:f},h),re.createElement(Y,{backgroundColor:f,color:br.DIM},y)),re.createElement(Y,{backgroundColor:f,color:br.GREEN},r?` ${Re.tick} `:" "))},"ModelRow");Vr();var LI=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,LI);e.length>0&&n.push({...r,models:e})}return n}function groupByModelProvider(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups,"searchGroups"),__name(groupByModelProvider,"groupByModelProvider");var $I=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,onPick:r,onBack:o})=>{const[s,i]=se(""),a=le(()=>isInternalTeamFlagEnforced(),[]),[l,u]=se(()=>getCachedBillingContext());ae(()=>{if(l)return;let e=!0;return getBillingContext().then(t=>{e&&u(t)}),()=>{e=!1}},[l]);const d=null!==l,m=le(()=>a?bn:groupByModelProvider(En.flatMap(e=>e.models),Sn["command-code"].id),[a]),g=le(()=>l?m.map(e=>({...e,models:e.models.filter(e=>checkModelAccess({model:{id:e.id,provider:e.provider,name:e.name},planId:l.planId,purchasedCredits:l.purchasedCredits,freeCredits:l.freeCredits}).allowed)})).filter(e=>e.models.length>0):[],[m,l]),h=le(()=>searchGroups(g,s),[g,s]),f=le(()=>{const e=[];for(const t of h)for(const n of t.models)e.push({kind:"model",providerId:t.providerId,model:n});return[{kind:"reset"},...e]},[h]),y=le(()=>{if(!n)return 0;const e=f.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[f,n]),{cursor:w}=useListNavigation({items:f,initialIndex:y,searchCursorIndex:1,searchQuery:s,onSearchChange:i,onSelect:__name(e=>{d&&r("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:o}),[S,E]=se(0),v=useTerminalHeight()-1,C=Math.max(4,v-11-2*h.length);ae(()=>{E(e=>clampScrollOffset({cursor:w,total:f.length,maxVisible:C,currentOffset:e}))},[w,f.length,C]);const k=S,T=S+C,_=0===k;let x=1;const A=h.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:x,windowStart:k,windowEnd:T});return x+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),P=f.length>C;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},e," › select model")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{dimColor:!0},"Pick a model for this task, or reset it to the default.")),isCmdZdrEnabled()&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.YELLOW},"Your pick is saved but stays paused until CMD_ZDR is unset.")),re.createElement(Q,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(QP,{query:s,resultCount:s?f.length-1:void 0,placeholder:"Type to search models..."})),d?re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column"},_&&re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{bold:!0,dimColor:!0},"Default"),re.createElement(Q,null,re.createElement(Y,{backgroundColor:0===w?zr:void 0,color:n?br.WHITE:br.GREEN},t," "),!n&&re.createElement(Y,{color:br.GREEN},Re.tick))),A.map(({group:e,groupWindow:t},r)=>re.createElement(Q,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||_?1:0},re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(NI,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===w,isCurrent:r.id===n,showProviderLabel:!!a&&void 0,showDefaultBadge:!1}))))),P&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",k+1,"–",Math.min(T,f.length)," of"," ",f.length,k>0?" · ↑ more":"",T<f.length?" · ↓ more":""))):re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"Loading available models…")),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"type to search · ↑/↓ navigate · enter select"),s?re.createElement(Y,{color:br.DIM}," · esc to clear"):re.createElement(Y,{color:br.DIM}," · esc back")))},"FeatureModelPicker");function sanitizeFeatureOverrides(e){const t={};for(const{key:n}of a_){const r=e?.[n];"string"==typeof r&&r&&(t[n]=r)}return t}__name(sanitizeFeatureOverrides,"sanitizeFeatureOverrides");var DI=__name(({onClose:e})=>{const[t,n]=se(null),[r,o]=se(null),[s,i]=se(null);ae(()=>{loadUserConfig().then(e=>{n(sanitizeFeatureOverrides(e.featureModels))})},[]);const a=r?"picker":"list",{cursor:l}=useListNavigation({items:a_,initialIndex:0,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:"list"===a&&null!==t,onSelect:__name(e=>{i(null),o(e.key)},"onSelect"),onCancel:e,onReset:__name(async e=>{try{await setFeatureModel({feature:e.key,model:void 0}),n(t=>{const n={...t??{}};return delete n[e.key],n}),i({text:`${e.label} reset to default`})}catch{i({text:`Couldn't reset ${e.label} — try again`,error:!0})}},"onReset")});if(null===t)return null;const u=a_.find(e=>e.key===r)??null;if("picker"===a&&u)return re.createElement($I,{featureLabel:u.label,defaultLabel:getFeatureDefaultLabel(u),currentModelId:t[u.key],onBack:()=>o(null),onPick:async e=>{try{await setFeatureModel({feature:u.key,model:e}),n(t=>{const n={...t??{}};return void 0===e?delete n[u.key]:n[u.key]=e,n}),i({text:void 0===e?`${u.label} reset to default`:`${u.label} → ${getModelDisplayName(e)}`})}catch{i({text:`Couldn't save ${u.label} — try again`,error:!0})}o(null)}});const d=isCmdZdrEnabled();return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Configure models")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Pick a model for each task. Applies to all sessions."," ",createOSC8Link("https://commandcode.ai/docs/troubleshooting/faqs#why-do-i-see-small-background-requests","Why background requests?",!1))),d&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.YELLOW},"Model overrides were reverted to ZDR safe defaults. Your overrides will be restored when CMD_ZDR is unset.")),a_.map((e,n)=>{const r=t[e.key],o=e.defaultLabel?`Default (${getFeatureDefaultLabel(e)})`:`Uses current model (${getFeatureDefaultLabel(e)})`,s=r?getModelDisplayName(r):null,i=!!r&&!d,a=i&&s?s:o,u=n===l;return re.createElement(Q,{key:e.key},re.createElement(Y,{backgroundColor:u?zr:void 0,color:br.WHITE},e.label.padEnd(20)),re.createElement(Y,{backgroundColor:u?zr:void 0},re.createElement(Y,{color:i?br.GREEN:br.DIM},a),s&&d&&re.createElement(Y,{color:br.DIM},` · ${s} paused`)))}),s&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:s.error?br.RED:br.GREEN},s.text)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑/↓ navigate · enter to change · r to reset · esc to close")))},"ConfigureModelsSelector");function settingsFilePaths(e){return[getProjectLocalPath(e),getProjectSharedPath(e),getUserSettingsPath()]}function readInputSettings(e){try{const t=$.readFileSync(e,"utf-8");return parseJSON(t)?.input}catch{return}}function shouldCollapsePastedText(e=process.cwd()){for(const t of settingsFilePaths(e)){const e=readInputSettings(t)?.collapsePastedText;if("boolean"==typeof e)return e}return!0}Bt(),Vr(),Bt(),Xr(),_n(),so(),Bt(),No(),__name(settingsFilePaths,"settingsFilePaths"),__name(readInputSettings,"readInputSettings"),__name(shouldCollapsePastedText,"shouldCollapsePastedText"),Yn(),Bt();var OI=n(E(),"commandcode-images"),FI={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{O(OI)||B(OI,{recursive:!0});const r=FI[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(OI,o),i=Buffer.from(e.data,"base64");return q(s,i),s}catch{return null}}function stripInputAfterSuffix(e,t){return t&&e.endsWith(t)?e.slice(0,e.length-t.length):e}function extractAppendedChunk(e,t,n){const r=t+n;return e.length>=r.length&&e.startsWith(r)?e.slice(r.length):null}function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedContent:n,setInput:r,setDetectedImages:o,setDetectedContent:s,incrementInputKey:i,setInitialCursor:a,collapsePastedText:l=!0}=e,u=ce((e,t,n="")=>{o(t=>[...t,e]),r(t+n),a(t.length),i()},[o,r,a,i]),d=ie(!1),m=ie(""),g=ie(null),h=ie(""),f=ie(""),y=ce(async(e,t,n)=>{let o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const d=await detectDroppedImageFile(o);if(d)return void u(d,t,n);const m=await detectClipboardImage();if(m)return void u(m,t,n);let g=o;if(0===g.length){const e=await detectClipboardText();g=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(!g&&!n)return;if(!g)return r(t+n),a(t.length),void i();if(l&&g.length>300){const e=t+pastedTextToken(g);return s(e=>[...e,g]),r(e+n),a(e.length),void i()}const h=t+g;r(h+n),a(h.length),i()},[u,n.length,s,r,a,i,l]),w=ce(()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(async()=>{if(d.current){const e=m.current,t=h.current,n=f.current;m.current="",h.current="",f.current="",d.current=!1,g.current=null,e?await y(e,t,n):n&&await y("",t,n)}},500)},[y]);return{handlePaste:ce(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return d.current&&(d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)),await y(n.pastedContent??n.cleanedContent,n.textBeforePaste??"",n.textAfterPaste??""),!0;if(n.isPasteStart&&!d.current){d.current=!0;const e=n.textBeforePaste??t,r=t.slice(e.length);h.current=e,f.current=r;const o=n.pastedContent??n.cleanedContent;return m.current=stripInputAfterSuffix(o,r),w(),!0}if(d.current&&!n.isPasteEnd){const e=h.current,t=f.current;if(void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(n.cleanedContent){const r=extractAppendedChunk(n.cleanedContent,e,t);m.current=null!==r?m.current+r:accumulateDelta(n.cleanedContent,m.current,e)}return w(),!0}if(d.current&&n.isPasteEnd){g.current&&(clearTimeout(g.current),g.current=null);const e=h.current,t=f.current,r=n.textAfterPaste??"";let o=n.cleanedContent??"";if(r&&o.endsWith(r)&&(o=o.slice(0,o.length-r.length)),void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(o){const n=extractAppendedChunk(o,e,t);m.current=null!==n?m.current+n:accumulateDelta(o,m.current,e)}const s=m.current,i=e,a=r||t;return m.current="",h.current="",f.current="",d.current=!1,await y(s,i,a),!0}if(n.isPasteEnd&&!n.isPasteStart&&!d.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return u(e,t),!0}return!1},[t,y,w,u]),resetPasteState:ce(()=>{d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)},[]),isPasting:ce(()=>d.current,[])}}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=se(!1),[l,u]=se(null),d=ce(async()=>{if(!i){a(!0),u(null);try{let i=e.replace(/\n+$/,"");r.forEach(e=>{const t=pastedTextToken(e);i.includes(t)&&(i=i.replace(t,e))});const a=await openInEditor2(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){u(e instanceof Gx?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{a(!1)}}},[e,t,n,r,o,s,i]),m=ce(()=>{u(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:m}}__name(saveTempImage,"saveTempImage"),gr(),No(),Bt(),Qr(),so(),__name(stripInputAfterSuffix,"stripInputAfterSuffix"),__name(extractAppendedChunk,"extractAppendedChunk"),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),Qr(),Bt(),Qr(),__name(useExternalEditor,"useExternalEditor"),Bt();var jI=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=se(null),o=ie(!1);return ae(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,zx().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");Vr(),Bt(),Bt();var UI=1e5,BI=null,qI=new Map;function memoKey(e,t){return`${e}\0${t}`}function memoize(e,t){if(qI.size>=128){const e=qI.keys().next().value;void 0!==e&&qI.delete(e)}return qI.set(e,t),t}function loadGitignore(e){const t=it(),r=n(e,".gitignore");if(O(r))try{t.add(j(r,"utf8"))}catch{}return t.add(".git"),t}function isIgnored(e,t,n){return!!e.ignores(t)||n&&e.ignores(`${t}/`)}function listDirectory(e,t){const r=loadGitignore(t),o=[],i=H(e,{withFileTypes:!0});for(const a of i){const i=n(e,a.name),l=a.isDirectory();isIgnored(r,s(t,i),l)||o.push({name:a.name,path:i,isDirectory:l})}return sortDirectoriesFirst(o)}function sortDirectoriesFirst(e){return e.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name))}function buildFileIndex(e){const t=loadGitignore(e),r=[],o=[{dirPath:e,depth:0}];for(let i=0;i<o.length;i++){const{dirPath:a,depth:l}=o[i];if(r.length>=UI)break;let u;try{u=H(a,{withFileTypes:!0})}catch{continue}for(const i of u){if(r.length>=UI)break;const u=n(a,i.name),d=s(e,u),m=i.isDirectory();isIgnored(t,d,m)||(r.push({name:d,path:u,isDirectory:m,nameLower:d.toLowerCase(),filenameLower:i.name.toLowerCase(),depth:l+1}),m&&"node_modules"!==i.name&&l<8&&o.push({dirPath:u,depth:l+1}))}}return r}function getFileIndex(e){if(BI&&BI.basePath===e&&Date.now()-BI.builtAt<3e4)return BI.entries;const t=buildFileIndex(e);return BI={basePath:e,entries:t,builtAt:Date.now()},qI.clear(),t}function invalidateFileIndex(){BI=null,qI.clear()}function compareByRelevance(e,t,n){const r=e.nameLower===n,o=t.nameLower===n;if(r&&!o)return-1;if(!r&&o)return 1;const s=e.filenameLower.includes(n),i=t.filenameLower.includes(n);return s&&!i?-1:!s&&i?1:e.depth!==t.depth?e.depth-t.depth:e.name.localeCompare(t.name)}function searchIndex(e,t){const n=e.toLowerCase(),r=[];for(const e of getFileIndex(t)){if(!e.nameLower.includes(n))continue;if(50===r.length&&compareByRelevance(e,r[r.length-1],n)>=0)continue;let t=0,o=r.length;for(;t<o;){const s=t+o>>1;compareByRelevance(e,r[s],n)<0?o=s:t=s+1}r.splice(t,0,e),r.length>50&&r.pop()}return r.map(({name:e,path:t,isDirectory:n})=>({name:e,path:t,isDirectory:n}))}function searchFiles(e,t=process.cwd()){if(!e.trim())return[];const r=memoKey(t,e),o=qI.get(r);if(o)return o;if(/[/\\]$/.test(e))try{return memoize(r,listDirectory(n(t,e),t).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}if(/[/\\]/.test(e)){const o=e.split(/[/\\]/),i=(o.pop()||"").toLowerCase();try{return memoize(r,listDirectory(n(t,...o),t).filter(e=>!i||e.name.toLowerCase().includes(i)).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}}return memoize(r,searchIndex(e,t))}__name(memoKey,"memoKey"),__name(memoize,"memoize"),__name(loadGitignore,"loadGitignore"),__name(isIgnored,"isIgnored"),__name(listDirectory,"listDirectory"),__name(sortDirectoriesFirst,"sortDirectoriesFirst"),__name(buildFileIndex,"buildFileIndex"),__name(getFileIndex,"getFileIndex"),__name(invalidateFileIndex,"invalidateFileIndex"),__name(compareByRelevance,"compareByRelevance"),__name(searchIndex,"searchIndex"),__name(searchFiles,"searchFiles"),Vr();var zI=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[o,s]=se(process.cwd()),[i,l]=se([]),[u,d]=se(0),[m,g]=se(0),h=n.trim()?15:10;ae(()=>{invalidateFileIndex()},[]);const f=ce(e=>{try{const t=[];"/"!==e&&t.push({name:"..",path:r(e),isDirectory:!0}),t.push(...listDirectory(e,process.cwd())),l(t),d(0),g(0)}catch{}},[]);ae(()=>{if(n.trim()){const e=searchFiles(n);l(e),d(0),g(0)}else f(o)},[o,f,n]),Z((r,o)=>{if(o.escape)t();else if(o.upArrow)d(e=>{const t=Math.max(0,e-1);return t<m&&g(t),t});else if(o.downArrow)d(e=>{const t=Math.min(i.length-1,e+1);return t>=m+h&&g(t-h+1),t});else{if(o.rightArrow){const e=i[u];if(!e)return;return void(e.isDirectory&&!n.trim()&&s(a(e.path)))}if(o.return){const t=i[u];if(!t)return;return void e(t.path)}}});const y=i.slice(m,m+h);return re.createElement(Q,{flexDirection:"column",paddingLeft:1},re.createElement(Q,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${o}`),re.createElement(Y,{color:br.DIM},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===y.length?re.createElement(Y,{color:br.DIM},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):y.map((e,t)=>{const n=m+t,r=e.name,o=n===u;return re.createElement(Y,{key:e.path,color:o?br.GREEN:br.DIM,bold:o&&isLightTheme()},e.isDirectory?`${r}/`:r)}))},"FileList");Bt(),_n(),Ro(),Vr(),Bt(),Vr();var HI=__name(e=>{if(e>=1e6){const t=e/1e6;return`${t%1==0?t.toFixed(0):t.toFixed(1)}M`}return`${Math.round(e/1e3)}k`},"formatTokens"),WI=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20&&e.current>=18e4)return re.createElement(Q,{paddingRight:3},re.createElement(Y,{color:br.DIM},"~",HI(e.current)," tokens in context · try"," "),re.createElement(Y,{color:br.DIM,bold:!0},"/compact"));if(n>20)return null;const r=__name(e=>e>=90?br.RED:e>=70?br.YELLOW:br.DIM,"getColor"),o=t>=90?6:Math.round(t/100*6),s=6-o,i=Re.square.repeat(o),a=Re.squareLightShade.repeat(s),l=r(t);return re.createElement(Q,{paddingRight:3},re.createElement(Y,{color:l},`Context left before auto-compact ${n}% `),re.createElement(Y,{color:l},i),s>0&&re.createElement(Y,{color:br.DIM},a))},"ContextUsage");Bt(),Rs(),Vr();var GI=__name(()=>{const[e,t]=se("continuous learning"),[n,r]=se(!1),[o,s]=se(!1),i=ie([]),a=ie(0),l=ie(null),u=ie(!1);ae(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),s(!1),i.current=[],a.current=0,l.current&&(clearTimeout(l.current),l.current=null),void t(e.message)):u.current&&"analyzed"!==e.type?void i.current.push(e):"analyzed"===e.type?(u.current=!1,void(i.current.length>0?(a.current=0,n()):(r(!1),s(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),s(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const o="learned"===e.type||"refactored"===e.type;s(o);const u="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;l.current=setTimeout(()=>{a.current++,n()},u)},"cycleThroughNextEvent");return FC.on("new-event",e),()=>{FC.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?Re.squareSmallFilled:Re.squareSmall} TASTE`,m=9+e.length+d.length>Cs;let g=e;g=truncateString(m?{text:e,maxChars:Cs}:{text:e,maxChars:Cs-d.length-9-10});const h=o?void 0:br.DIM;return re.createElement(Q,{paddingRight:2},!m&&re.createElement(re.Fragment,null,re.createElement(BracketWrap,{color:br.DIM},"ctrl+t"),re.createElement(Y,{color:br.DIM}," ")),re.createElement(Y,{color:h},g),!m&&re.createElement(Y,{color:vr.TEXT},d))},"LearningFeedMini");Bt(),Vr();var VI=__name(({mode:e,pendingExitKey:t})=>t?re.createElement(Y,{color:br.DIM},"Press Ctrl+C again to exit"):"bypass"===e?re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:br.RED},"» permission bypass on "),re.createElement(BracketWrap,{color:br.DIM},"shift+tab")):"auto-accept"===e?re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:$r},"» accept edits on "),re.createElement(BracketWrap,{color:br.DIM},"shift+tab")):"plan"===e?re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:Lr},"plan mode "),re.createElement(BracketWrap,{color:br.DIM},"shift+tab")):re.createElement(Y,{color:br.DIM},"? for shortcuts"),"ModeIndicator");Bt(),Vr(),ko();var KI=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?br.DIM:Dr.MERGED;return re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:n},"PR "),re.createElement(Eo,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),QI=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{color:"connected"===e.type?br.GREEN:br.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),YI=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const v=e>=60;return re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r||l?re.createElement(Q,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(Q,{flexDirection:"row",columnGap:0},n&&!l?re.createElement(Y,{color:Ir},t):re.createElement(VI,{mode:r,pendingExitKey:l}),!l&&re.createElement(KI,{prInfo:o}),!l&&re.createElement(QI,{indicator:a})),v&&re.createElement(Q,{flexDirection:"column",alignItems:"flex-end"},s&&re.createElement(GI,null),i&&re.createElement(WI,{usage:i}))):re.createElement(re.Fragment,null,re.createElement(Q,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(VI,{mode:r}),v&&s&&re.createElement(GI,null)),re.createElement(Q,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(Q,{flexDirection:"row",columnGap:0},re.createElement(Y,{color:n?Ir:br.DIM},t),re.createElement(KI,{prInfo:o}),re.createElement(QI,{indicator:a})),v&&i&&re.createElement(WI,{usage:i}))),(u||d||g&&m)&&re.createElement(Q,{flexDirection:"row",columnGap:1},u&&re.createElement(Y,null,Re.tick," ","Command Code"," updated:"," ",re.createElement(Y,{color:br.DIM},"v",u.updatedFrom),re.createElement(Y,{color:br.DIM}," ",Re.arrowRight," "),re.createElement(Y,null,"v",u.updatedTo)),!u&&d&&re.createElement(Y,{color:br.YELLOW,dimColor:!0},Re.info," Update available:"," ",d.currentVersion," ",Re.arrowRight," ",d.latestVersion),g&&m&&re.createElement(Y,{color:br.GREEN,dimColor:!0},Re.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:br.GREEN},"! for bash mode")),y&&f&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:Er},"SHARED: ",f.url," (copied to clipboard)")),w&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:w.includes("NOT SHARED")?br.RED:Er},w)),S&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:Er},S)),E&&re.createElement(Q,{paddingLeft:2},re.createElement(Y,{color:br.YELLOW},Re.warning," ",E)))},"BottomIndicator");Bt(),Sv(),Rs(),Vr();var JI=__name((e,t)=>e.padEnd(t),"padCell"),XI=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getDeleteErrorMessage"),ZI=__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"),eM=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),tM=__name(e=>truncateString({text:eM(e),maxChars:Es}),"truncateMessage"),nM=__name(e=>e.title?eM(e.title):tM(e.firstMessage),"getSessionSummary"),rM=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=se([]),[o,s]=se(0),[i,a]=se(0),[l,u]=se(!0),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w]=se(()=>getCurrentGitBranch()),S=useTerminalHeight(),E=Math.max(6,S-14),v=ce(async()=>{u(!0);const e=await fv.listSessions();r(e),u(!1)},[]);ae(()=>{v()},[v]);const C=ce(async e=>{try{await fv.deleteSession(e),h(!1),y(null),s(0),a(0),await v()}catch(e){h(!1),y(`Failed to delete session: ${XI(e)}`)}},[v]),k=d&&w?n.filter(e=>e.gitBranch===w):n;if(Z((n,r)=>{if(g)if(r.return){if(k.length>0&&o<k.length){const e=k[o];C(e.id)}}else h(!1);else if(r.delete||r.ctrl&&"d"===n)k.length>0&&(y(null),h(!0));else{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),s(0),void a(0)):void(r.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?s(e=>{const t=Math.min(k.length-1,e+1);return t>=i+E&&a(t-E+1),t}):r.return&&k.length>0&&o<k.length&&e(k[o].id));t()}}),l)return re.createElement(Q,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:br.GRAY},"Loading sessions..."));if(0===k.length)return re.createElement(Q,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:br.GRAY},d&&w?`No sessions found for branch "${w}"`:"No previous sessions found"),re.createElement(Y,{color:br.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const T=k.slice(i,i+E),_=o<k.length?k[o]:null,x=g&&_?`Delete "${nM(_)}"? Press Enter to confirm, any other key to cancel.`:null;return re.createElement(Q,{flexDirection:"column",paddingLeft:1,width:"100%"},re.createElement(Y,{color:br.CYAN,bold:!0},"Resume Session"),re.createElement(Q,{marginTop:1}),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Mr,bold:!0},JI("#",6),JI("Modified",12),JI("Git Branch",22),JI("Messages",12),"Summary")),re.createElement(Q,{flexDirection:"column"},T.map((e,t)=>{const n=i+t,r=o===n,s=truncateString({text:e.gitBranch||"-",maxChars:20});return re.createElement(Y,{key:e.id,color:r?br.WHITE:br.GRAY,backgroundColor:r?zr:void 0,bold:r,wrap:"truncate-end"},JI(`${n+1}.`,6),JI(ZI(e.lastModified),12),JI(s,22),JI(String(e.messageCount),12),nM(e)," ")})),re.createElement(Q,{marginTop:1}),x&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},x)),f&&re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.RED},f)),k.length>E&&re.createElement(Y,{color:br.DIM},"Showing ",i+1,"–",Math.min(i+E,k.length)," ","of ",k.length,i>0?" · ↑ more":"",i+E<k.length?" · ↓ more":""),re.createElement(Y,{color:br.DIM},"↑↓ navigate · Enter select · Del delete · ctrl+b ",d?`[branch: ${w??"unknown"}]`:"branch filter"," · ESC cancel"))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],o=0;for(let s=0;s<e;s++){const e=`[Image #${s+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&o+i>t?(n.push(r),r=[s],o=e):(r.push(s),o+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return re.createElement(Y,null,r?" ":"",t?re.createElement(Y,{inverse:!0},o):s)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:o}){if(0===e.length)return null;const s=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:o}),i=Math.max(1,r-(s.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return re.createElement(Q,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>re.createElement(Q,{key:r,flexDirection:"row"},re.createElement(Q,{flexShrink:0,marginRight:1},0===r&&re.createElement(Y,{color:br.DIM},s)),re.createElement(Q,{flexDirection:"row"},e.map((e,r)=>re.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Bt(),Vr(),Bt(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),Po(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Bt();var oM=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=se(null),[s,i]=se(!1),a=ie(!1),l=ie(null),u=ie(n),[d,m]=se(!1),[g,h]=se("connected"),f=ie(null),y=ie(null),w=ce((e,t)=>{y.current&&(clearTimeout(y.current),y.current=null),h(e),m(!0),void 0!==t&&(y.current=setTimeout(()=>{m(!1)},t))},[]),S=ce(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),E=ce(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new OT,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=f.current;if(null===r?n&&w("connected",3e3):r!==n&&(n?w("connected",2e3):w("disconnected",5e3)),f.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),o(r)}else o(null)}catch{!0===f.current&&w("disconnected",5e3),f.current=!1,i(!1),o(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[w]);ae(()=>{const e=u.current;u.current=n,e&&!n&&t&&null!==xT()&&E(!1)},[n,t,E]),ae(()=>{if(!t)return;if(null===xT())return;let e=null,n=!1,r=0;function schedule(t){n||(e=setTimeout(()=>{tick(!1)},t))}async function tick(e){if(u.current)return void schedule(500);if(await E(e),n)return;if(l.current?.isConnected)return r=0,void schedule(500);r+=1;const t=Math.min(r,6);schedule(Math.min(3e4,500*2**t)+250*Math.random())}return __name(schedule,"schedule"),__name(tick,"tick"),tick(!0),()=>{n=!0,e&&clearTimeout(e),S(),l.current?.disconnect(),l.current=null}},[t,E,S]);const v=xT(),C={visible:d,message:"connected"===g?`${v?Zx[v]??"IDE":"IDE"} ${Re.tick}`:"run /ide",type:g};return{context:r,connected:s,refresh:E,connectionIndicator:C}},"useVSCodeContext");Bt();var sM=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language??"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;").replace(/[\u202A-\u202E\u2066-\u2069\u200B-\u200D\uFEFF]/g,"");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");function basename5(e){return t.win32.basename(e)}function resolvePastedTextTokens({input:e,detectedContent:t}){return t.reduce((e,t)=>{const n=pastedTextToken(t);return e.includes(n)?e.replace(n,()=>t):e},e)}Bt(),Qr(),__name(basename5,"basename"),__name(resolvePastedTextTokens,"resolvePastedTextTokens");var iM=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),aM=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const o=e?t?.activeFile:null;if(o?.relativePath){const e=basename5(o.relativePath),t=n<80?15:n<120?25:40;return`In ${e.length>t?e.slice(0,t-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText");function getModelShortName(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getModelHintLayout(e){const{currentModel:t,terminalWidth:n}=e,r=getCommandMenuDescriptionWidth(n),o=modelSupportsReasoningEffort(t)?getReasoningEffort(t):null,s=o?` with ${o} effort`:"";return{descriptionWidth:r,text:truncateString({text:`${getModelShortName(t)}${s} (current)`,maxChars:r})}}Bt(),bo(),Co(),Rs(),__name(getModelShortName,"getModelShortName"),__name(getModelHintLayout,"getModelHintLayout");var lM=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}function getCommandMenuStateFromQuery(e){return isDesignSubmenu(e)?{showMenu:!0,query:e}:e.includes(" ")?{showMenu:!1,query:""}:{showMenu:!0,query:e}}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace"),__name(getCommandMenuStateFromQuery,"getCommandMenuStateFromQuery");var cM=__name(()=>re.createElement(Q,{flexDirection:"column",paddingLeft:1},re.createElement(Y,{color:br.DIM,bold:!0},"Available Shortcuts:"),re.createElement(Q,{columnGap:4},re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.DIM},"! for bash mode"),re.createElement(Y,{color:br.DIM},"/ for commands"),re.createElement(Y,{color:br.DIM},"@ for file paths"),re.createElement(Y,{color:br.DIM},"shift + tab to toggle auto-accept")),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.DIM},"double tap esc to clear input"),re.createElement(Y,{color:br.DIM},"ctrl + j / shift + ⏎ for newline"),re.createElement(Y,{color:br.DIM},"ctrl + g to open in editor"),re.createElement(Y,{color:br.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),uM=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,currentModel:T,showProviderInfo:_,permissionMode:x="standard",onToggleAutoAccept:A,hintMessage:P,historyManager:I,pendingExitKey:M=null,onOverlayVisibilityChange:R,onDoubleEscapeEmpty:N,onAltP:L,isProcessing:$=!1,ideContextEnabled:D=!0})=>{const[O,F]=se(0),[j,U]=se(!1),[B,q]=se(!1),[z,H]=se(!1),[W,G]=se(!1),[V,K]=se(""),[J,ee]=se(null),[te,ne]=se(!1),oe=ie(0),ue=ie(0),[de,me]=se([]),[pe,ge]=se([]),[he,fe]=se(-1),[ye,we]=se(""),Se=ie(!1),be=ie(!1),Ee=ie(void 0),[ve,Ce]=se(-1),[ke,Te]=se(""),_e=ie(0),{isEditorOpen:xe,editorError:Ae,handleOpenInEditor:Pe,clearEditorError:Ie}=useExternalEditor({input:e,setInput:n,setInputKey:F,detectedContent:de,setDetectedContent:me,onEditorClose:__name(()=>{Se.current=!1},"onEditorClose")}),Me=le(()=>shouldCollapsePastedText(),[]),{handlePaste:Ne,resetPasteState:Le,isPasting:$e}=useBracketedPaste({input:e,detectedContent:de,setInput:n,setDetectedImages:ge,setDetectedContent:me,incrementInputKey:__name(()=>F(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Ee.current=e},"setInitialCursor"),collapsePastedText:Me}),{context:De,connected:Oe,refresh:Fe,connectionIndicator:je}=oM({enabled:D,paused:$}),{stdout:Ue}=X(),Be=Ue?.columns??80,{pr:qe}=jI();ae(()=>{const e=i||W||te;R?.(e)},[i,W,te,R]);const ze=ce(()=>{ge([]),fe(-1)},[]),He=ce(()=>{G(!1),ee(null)},[]),We=ce(()=>{n(""),q(!1),He(),K(""),ne(!1),me([]),ze(),we(""),Le(),Ce(-1),Te(""),F(e=>e+1)},[n,Le,ze,He]),Ge=ce(()=>{Se.current=!0;const{text:t,cursor:r}=insertTextAt(e,_e.current,"\n");n(t),Ee.current=r,F(e=>e+1),setTimeout(()=>{Se.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==he&&r.leftArrow)return void fe(prevImageIndex({currentIndex:he,imageCount:pe.length}));if(-1!==he&&r.rightArrow)return void fe(nextImageIndex({currentIndex:he,imageCount:pe.length}));if(r.upArrow){if(i||W||te)return;const t=e.indexOf("\n"),r=-1===t||_e.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:pe.length,selectedImageIndex:he,historyIndex:ve}))return void fe(pe.length-1);if(-1!==he&&fe(-1),0!==e.length&&-1===ve&&!r)return;const o=I?.count()??0;if(0===o)return;-1===ve&&Te(e);const s=Math.min(ve+1,o-1);return void(s!==ve&&(Ce(s),n(I?.getAt(s)||""),F(e=>e+1)))}if(r.downArrow){if(i||W||te)return;if(-1===ve)return;const t=e.lastIndexOf("\n");if(!(-1===t||_e.current>t))return;const r=ve-1;return Ce(r),n(-1===r?ke:I?.getAt(r)||""),void F(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void ze();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return Se.current=!0,void Pe();if(getIsExpandToolShortcut(r,t))return Se.current=!0,n(e),F(e=>e+1),void setTimeout(()=>{Se.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:$e()}))return be.current=!0,Ge(),void setTimeout(()=>{be.current=!1},0);if(r.meta&&r.backspace)return void We();if(r.meta&&"w"===t)return Se.current=!0,void We();const o=r.ctrl&&"v"===t||lM.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e;Se.current=!0;const r=await detectClipboardImage();return r&&(ge(e=>[...e,r]),n(t),F(e=>e+1)),void(Se.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return H(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==he&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:pe,index:he});return ge([...e]),void fe(t)}if(r.escape){if(-1!==he)return void fe(-1);if(W)return;if(te)return ne(!1),n(ye),void F(e=>e+1);const t=Date.now();return t-oe.current<500?(e.length>0?We():N?.(),oe.current=0,ue.current=0):(oe.current=t,j||B||(ue.current=t)),U(!1),void q(!1)}j&&(r.backspace||r.delete)&&0===e.length&&U(!1)}});const Ve=ce(async t=>{if(xe)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void L?.();const o=processBracketedPaste(t);if((o.isPasteStart||o.isPasteEnd||$e())&&await Ne(t))return;if(Se.current)return void(Se.current=!1);-1!==ve&&Ce(-1);const s=1===t.length,l=t.slice(-1);if(s){if("?"===l&&!j)return U(!0),n(""),void F(e=>e+1);if("!"===l&&!B)return U(!1),q(!0),n(""),void F(e=>e+1)}if("/"!==l||W||"/"!==t||(G(!0),K("")),W)if(t.startsWith("/")){const e=t.substring(1),{showMenu:n,query:r}=getCommandMenuStateFromQuery(e);n?G(!0):He(),K(r)}else He(),K("");"@"!==l||i||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(a(!0),u(""));const d=t.lastIndexOf("@");if(t.length<e.length&&-1!==d&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(d+1),n=!e.includes(" "),r=d>0?t[d-1]:"";n&&isPrecededByWhitespace(r)&&(a(!0),u(e))}if(i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!1),u("");else{const n=t.substring(e+1);u(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);u(e),a(!1)}else u(n)}}j&&(t!==e||t.length<e.length)&&U(!1),Ae&&Ie(),0===t.length&&(q(!1),He(),K(""),ne(!1),me([]),u(""),we(""),Le()),n(t)},[j,e,n,i,a,W,B,pe,ve,Ne,Le,L,Ae,Ie,xe,He]),Ke=ce(async()=>{if(Fe(),ue.current=0,j)return void U(!1);const r=e.trim(),o=!B&&r.startsWith("/");let s=r;!B&&de.length>0&&(s=resolvePastedTextTokens({input:s,detectedContent:de}));const i=!B&&pe.length>0?[...pe]:[],a=De?sM(De):void 0;if(o&&d&&(n(""),"handled"===(await d(s,i,a)).status))return I?.add(s),q(!1),He(),K(""),ze(),me([]),Ce(-1),void Te("");Ce(-1),Te(""),s.length>0&&I?.add(s);const l=De?.selection?{lines:De.selection.lineCount,file:basename5(De.activeFile?.relativePath??De.activeFile?.path??"")||"unknown",ide:Zx[xT()??""]??"IDE"}:void 0;t({input:s,role:B?"bash":"user",images:i,ideContext:a,ideHint:l}),q(!1),He(),K(""),ze(),me([])},[t,d,j,e,B,pe,de,I,Fe,ze,He,n]),Qe=ce(t=>{const r=s(process.cwd(),t);let o;if(i&&""!==l){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),a(!1),u(""),F(e=>e+1)},[n,a,e,i,l,u]),Ye=ce(()=>{a(!1),u("")},[a,u]),Je=ce(e=>{const t=YA.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();n(t+" "),K(t.substring(1)+" ")}else He(),K(""),n(e+" ");F(e=>e+1)},[n,He]),Xe=ce(t=>{if("/resume"===t||"/sessions"===t)return I?.add(t),Ce(-1),Te(""),we(e),He(),K(""),ne(!0),n(""),void F(e=>e+1);if("/design help"===t)return He(),K(""),n(""),F(e=>e+1),I?.add(t),void d?.("/design help");if(QA.has(t))return He(),K(""),I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),void d?.(t);const r=YA.has(t),o=JA.has(t);r?Je(t):(He(),K(""),o?(I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),d?.(t)):(n(t+" "),F(e=>e+1)))},[d,n,e,I,Je,He]),Ze=ce(()=>{He(),K(""),n(""),Ce(-1),Te(""),F(e=>e+1)},[n,He]),et=ce(e=>{ne(!1),n(""),we(""),Ce(-1),Te(""),F(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),tt=ce(()=>{ne(!1),n(ye),Ce(-1),Te(""),F(e=>e+1)},[ye,n]),nt=ce(e=>{_e.current=e,Ee.current=void 0},[]),rt=le(()=>{const t=qe&&("OPEN"===qe.state||"MERGED"===qe.state);return"auto-accept"===x||"plan"===x||"bypass"===x||Oe||t?!j&&!te:!j&&0===e.length&&!B&&!te},[j,e,B,te,x,Oe,qe]),ot=ie(new Map),st=le(()=>pe.map((e,t)=>{if(ot.current.has(e))return ot.current.get(e)??null;const n=saveTempImage(e,t+1);return ot.current.set(e,n),n}),[pe]),it=__name(()=>j||i||W||te||z?0:rt||M||B?3:4,"getBottomMargin");return re.createElement(Q,{width:"100%",flexDirection:"column",marginBottom:it()},!te&&re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(ImageRowsDisplay,{detectedImages:pe,selectedImageIndex:he,imageTempPaths:st,termWidth:Be,inHistory:-1!==ve}),re.createElement(Y,{color:B?br.GREEN:br.GRAY},Re.line.repeat(Be)),(()=>{const t=__name(()=>{if(!be.current)return Date.now()-ue.current<100?(ue.current=0,void Ge()):void(i||W||te||xe||Ke());be.current=!1},"handleTextInputSubmit"),n=__name(n=>re.createElement(TextInput,{key:O,value:e,placeholder:xe?"Save and close the editor to continue...":o,onChange:Ve,onSubmit:t,showCursor:!xe&&r&&-1===he,onCursorChange:nt,initialCursor:Ee.current,prefix:`${B?"!":Re.pointer} `,prefixColor:B?br.GREEN:br.WHITE,singleLine:n?.singleLine,maxWidth:n?.maxWidth}),"renderTextInput");if(W&&T&&"/model"===J){const e=getModelHintLayout({currentModel:T,terminalWidth:Be});return re.createElement(Q,{flexDirection:"row",width:"100%"},re.createElement(Q,{width:25},n({singleLine:!0,maxWidth:25})),re.createElement(Q,{width:e.descriptionWidth},re.createElement(Y,{color:br.DIM,wrap:"truncate"},e.text)))}return n()})(),re.createElement(Y,{color:B?br.GREEN:br.GRAY},Re.line.repeat(Be))),j&&re.createElement(cM,null),z&&re.createElement(Q,{paddingTop:1},re.createElement(Y,{color:br.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&re.createElement(zI,{onSelectFile:Qe,onClose:Ye,searchQuery:l}),W&&re.createElement(eP,{onSelectCommand:Xe,onInsertCommand:Je,onClose:Ze,searchQuery:V,onSelectedCommandChange:ee}),te&&re.createElement(rM,{onSelectSession:et,onClose:tt}),!W&&(rt||M)&&re.createElement(YI,{termWidth:Be,indicatorText:aM(Oe,De,Be),isIDEIndicator:iM(Oe,De),permissionMode:x,prInfo:qe,tasteLearning:g,contextUsage:m,connectionIndicator:je,pendingExitKey:M,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:_,isBashMode:B,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),Ae&&re.createElement(Q,{paddingLeft:1,flexDirection:"column"},re.createElement(Y,{color:br.YELLOW},Ae)))},"InputBox");Bt(),Rs(),Vr();var dM=__name(({messages:e})=>0===e.length?null:re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Q,{marginBottom:0},re.createElement(Y,{color:kr,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>re.createElement(Q,{key:t},re.createElement(Y,{color:br.DIM},Re.pointerSmall," "),re.createElement(Y,{color:br.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),mM=re.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:R,pendingExitKey:N,onResetPendingExitKey:L,onDoubleEscapeEmpty:$,retryAttempt:D,onAltP:O})=>{const[F,j]=se(0),U=ie(o);return ae(()=>{N&&o!==U.current&&o.length>0&&L?.(),U.current=o},[o,N,L]),ae(()=>{if(!t)return void j(0);const e=setInterval(()=>{j(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),re.createElement(Q,{flexDirection:"column"},re.createElement(dM,{messages:e}),re.createElement(Q,{flexDirection:"row",justifyContent:"space-between"},re.createElement(Q,{flexDirection:"column"},(t||n.isExecuting)&&null===D&&re.createElement(_I,{tokens:g,timeElapsed:F,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),M&&re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM}," ","⎿"," ","Tip: ",M)))),re.createElement(uM,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:R,pendingExitKey:!N||t||n.isExecuting?null:N,onDoubleEscapeEmpty:$,onAltP:O,isProcessing:t}))});Bt(),_v(),Mv(),To(),Ro();var pM=__name(({onComplete:e,onCancel:t})=>{const[n,r]=se(!1),[o,s]=se(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");g()}}),n?re.createElement(vo,{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}`)}}):re.createElement(Av,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");function buildOAuthMetadataUrl(e){const t=new g(e),n="/"===t.pathname?"":t.pathname.replace(/\/+$/,"");return t.pathname=`/.well-known/oauth-authorization-server${n}`,t.search="",t.hash="",t.toString()}function buildOidcMetadataUrl(e){const t=new g(e),n=t.pathname.replace(/\/+$/,"");return t.pathname=`${n}/.well-known/openid-configuration`,t.search="",t.hash="",t.toString()}async function tryFetchAsMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.authorization_endpoint&&n.token_endpoint?{authorizationEndpoint:n.authorization_endpoint,tokenEndpoint:n.token_endpoint,registrationEndpoint:n.registration_endpoint,scopes:n.scopes_supported}:null}catch(t){return dlog(`[MCP] OAuth metadata fetch failed for ${e}`,t),null}}async function discoverOAuthMetadataFromIssuer(e){return await tryFetchAsMetadata(buildOAuthMetadataUrl(e))||await tryFetchAsMetadata(buildOidcMetadataUrl(e))}async function discoverOAuthMetadata(e){const t=new g(e),n=`${t.protocol}//${t.host}`;return await tryFetchAsMetadata(`${n}/.well-known/oauth-authorization-server`)||await tryFetchAsMetadata(`${n}/.well-known/openid-configuration`)}function parseResourceMetadataUrl(e){if(!e)return null;const t=e.match(/resource_metadata\s*=\s*"([^"]+)"|resource_metadata\s*=\s*([^\s,]+)/i);return t?t[1]??t[2]??null:null}async function fetchProtectedResourceMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{authorizationServers:n.authorization_servers,scopesSupported:n.scopes_supported}}catch(e){return dlog("[MCP] Protected resource metadata fetch failed",e),null}}async function checkServerAuthRequirements(e){try{const t=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"initialize",id:0,params:{protocolVersion:zb,capabilities:{},clientInfo:Hb}})});if(401===t.status||403===t.status){const n=parseResourceMetadataUrl(t.headers?.get?.("www-authenticate")??null);if(n){const e=await fetchProtectedResourceMetadata(n),t=e?.authorizationServers?.[0];if(t){const n=await discoverOAuthMetadataFromIssuer(t);if(n)return e?.scopesSupported&&(n.scopes=e.scopesSupported),{requiresAuth:!0,metadata:n}}}return{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}}return{requiresAuth:!1}}catch(e){return{requiresAuth:!1,error:`Server unreachable: ${e instanceof Error?e.message:String(e)}`}}}async function registerOAuthClient({registrationEndpoint:e,clientName:t,redirectUris:n}){try{const r=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:t,redirect_uris:n,token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]})});if(r.ok){const e=await r.json();return{clientId:e.client_id,clientSecret:e.client_secret}}}catch(e){dlog("[MCP] OAuth client registration failed",e)}return null}async function discoverAndAuthenticate({serverName:e,serverUrl:t,onStatus:n}){const r=n??(()=>{});r("Probing server for OAuth requirements...");const o=await checkServerAuthRequirements(t);if(o.error)return{success:!1,error:o.error};if(!o.requiresAuth)return{success:!1,error:"Server does not require authentication"};if(!o.metadata)return{success:!1,error:"Server returned 401 but did not advertise OAuth metadata. Add `oauth` config manually via `mcp add-json`."};const{authorizationEndpoint:s,tokenEndpoint:i,registrationEndpoint:a,scopes:l}=o.metadata;if(!a)return{success:!1,error:"Server requires pre-registered OAuth credentials (no Dynamic Client Registration endpoint advertised). Register an OAuth client with the server, then add it via `mcp add-json` with an `oauth.clientId` field."};const u=`http://${cE}:${lE}/callback`;r("Registering OAuth client...");const d=await registerOAuthClient({registrationEndpoint:a,clientName:Hb.name,redirectUris:[u]});if(!d)return{success:!1,error:"Dynamic client registration failed at "+a};const m={authorizationUrl:s,tokenUrl:i,clientId:d.clientId,clientSecret:d.clientSecret,scopes:l},g=await performOAuthFlow(e,t,m,{onStatus:n});return g.success&&(await storeDiscoveredClient(e,{authorizationUrl:s,tokenUrl:i,clientId:d.clientId,scopes:l}),d.clientSecret?await storeClientSecret(e,d.clientSecret):await deleteClientSecret(e)),g}Bt(),Bt(),eE(),Vb(),rE(),tE(),sE(),hE(),SE(),vE(),Bt(),SE(),vE(),Jb(),gE(),Bt(),aE(),Vb(),ir(),__name(buildOAuthMetadataUrl,"buildOAuthMetadataUrl"),__name(buildOidcMetadataUrl,"buildOidcMetadataUrl"),__name(tryFetchAsMetadata,"tryFetchAsMetadata"),__name(discoverOAuthMetadataFromIssuer,"discoverOAuthMetadataFromIssuer"),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(parseResourceMetadataUrl,"parseResourceMetadataUrl"),__name(fetchProtectedResourceMetadata,"fetchProtectedResourceMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),Bt(),Vb(),gE(),Jb(),__name(discoverAndAuthenticate,"discoverAndAuthenticate"),Vr(),ko();var gM=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(!0),[s,i]=se(0),[a,l]=se("list"),[u,d]=se(null),[m,g]=se(0),h=useTerminalHeight(),f=ce(async()=>{o(!0);try{const e=await listMcpServers(),t=getMcpConnectionManager().getConnectedServers(),r=await Promise.all(e.map(async e=>{const n=t.find(t=>t.name===e.name);let r,o,s="disconnected";return!1===e.config.enabled?s="disabled":n&&"connected"===n.status?(s="connected",r=n.tools.length):n&&"error"===n.status?(s="error",o=n.error):(e.config.oauth||"http"===e.config.transport)&&(await hasTokens(e.name)?s="authenticated":e.config.oauth&&(s="requires_auth")),{name:e.name,config:e.config,scope:e.scope,status:s,toolCount:r,error:o}}));n(r)}catch{}finally{o(!1)}},[]);ae(()=>{f()},[f]);const y=le(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),w=y[s]??null,S=h-1,E=le(()=>new Set(y.map(e=>e.scope)).size,[y]),v=Math.max(4,S-8-2*E);ae(()=>{g(e=>clampScrollOffset({cursor:s,total:y.length,maxVisible:v,currentOffset:e}))},[s,y.length,v]),Z((t,n)=>{if(n.ctrl&&"c"===t)e();else if(n.escape)"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e();else if("list"===a){if(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow){if(0===y.length)return;const e=Math.max(0,y.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&w&&(l("actions"),d(null))}});const C=__name((e,t)=>{const n=__name((e,n)=>re.createElement(Y,{color:e,backgroundColor:t},n),"icon");switch(e){case"connected":return n(br.GREEN,Re.tick);case"authenticated":return n(br.CYAN,Re.tick);case"requires_auth":return n(br.YELLOW,Re.warning);case"error":return n(br.RED,Re.cross);default:return n(br.GRAY,Re.circle)}},"getStatusIcon"),k=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";case"disabled":return"disabled";default:return"not connected"}},"getStatusText"),T=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),_=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),x=__name(async e=>{if(w)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)if("remove"!==e.value)if("disable"!==e.value)if("enable"!==e.value);else{d({text:`Enabling ${w.name}...`,color:br.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:w.name,enabled:!0,scope:w.scope}))return void d({text:`${Re.cross} Failed to enable ${w.name}, server may no longer exist in ${w.scope} scope`,color:br.YELLOW});await f(),d({text:`${Re.tick} Enabled ${w.name}`,color:br.GREEN})}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else{d({text:`Disabling ${w.name}...`,color:br.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:w.name,enabled:!1,scope:w.scope}))return void d({text:`${Re.cross} Failed to disable ${w.name}, server may no longer exist in ${w.scope} scope`,color:br.YELLOW});await e.disconnectServer(w.name),await f(),d({text:`${Re.tick} Disabled ${w.name}`,color:br.GREEN})}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else l("confirm-remove");else{if(!(w.config.oauth||"http"===w.config.transport&&w.config.url))return void d({text:"Authentication requires an http server with a url",color:br.YELLOW});d({text:`Authenticating ${w.name}...`,color:br.CYAN,loading:!0});try{let e;if(w.config.oauth){const t={authorizationUrl:w.config.oauth.authorizationUrl,tokenUrl:w.config.oauth.tokenUrl,clientId:w.config.oauth.clientId,clientSecret:w.config.oauth.clientSecret,scopes:w.config.oauth.scopes};e=await performOAuthFlow(w.name,w.config.url??"",t,{onStatus:__name(()=>{},"onStatus")})}else e=await discoverAndAuthenticate({serverName:w.name,serverUrl:w.config.url});if(e.success){d({text:`${Re.tick} Authenticated with ${w.name}`,color:br.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name)}catch{}await f()}else d({text:`${Re.cross} Auth failed: ${e.error}`,color:br.RED})}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else{d({text:`Connecting ${w.name}...`,color:br.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name),d({text:`${Re.tick} Connected to ${w.name}`,color:br.GREEN}),await f()}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED})}}else d({text:"Already authenticated",color:br.GREEN});else d({text:"Already connected",color:br.GREEN});else l("list")},"handleActionSelect"),A=__name(async e=>{if(w)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===w.status&&await e.disconnectServer(w.name),await removeMcpServer({name:w.name,scope:w.scope}),l("list"),await f(),i(e=>Math.min(e,Math.max(0,y.length-2)))}catch(e){d({text:`${Re.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:br.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:br.DIM},"Loading..."));if("confirm-remove"===a&&w)return re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:br.RED,bold:!0},"Remove ",w.name,"?"),re.createElement(Y,{color:br.DIM},"This will remove the server from ",w.scope," ","config."),re.createElement(Q,{marginTop:1},re.createElement(ft,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:A,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e}," ",t," ")})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&w){const e=[],t="disabled"===w.status,n="connected"===w.status,r="authenticated"===w.status||n;t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"});const o=!t&&(w.config.oauth||"http"===w.config.transport);return o&&r&&e.push({label:"Authenticated",value:"authenticated"}),o&&!r&&e.push({label:"Authenticate",value:"auth"}),t||e.push({label:"Disable",value:"disable"}),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},w.name),re.createElement(Q,null,C(w.status),re.createElement(Y,{color:br.DIM}," ",k(w))),re.createElement(Q,{marginTop:1},re.createElement(ft,{items:e,onSelect:x,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.WHITE:br.GRAY,backgroundColor:e?zr:void 0,bold:e}," ",t," ")})),u&&re.createElement(Q,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(We,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let P=null;const I=m,M=m+v,R=y.slice(I,M),N=y.length>v;return re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:Er,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:br.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:br.DIM},"No MCP servers configured."),re.createElement(Y,{color:br.DIM},'Use "cmd mcp add" to add a server.'),re.createElement(Eo,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:br.CYAN,dimColor:!0})):re.createElement(Q,{marginTop:1,flexDirection:"column"},R.map((e,t)=>{const n=I+t,r=e.scope!==P;P=e.scope;const o=n===s;return re.createElement(re.Fragment,{key:e.name},r&&re.createElement(Q,{marginTop:0===t?0:1},re.createElement(Y,{bold:!0},T(e.scope)),re.createElement(Y,{color:br.DIM}," ","(",_(e.scope),")")),re.createElement(Q,null,re.createElement(Y,{color:o?br.WHITE:void 0,backgroundColor:o?zr:void 0,bold:o},e.name),re.createElement(Y,{color:br.DIM,backgroundColor:o?zr:void 0}," · "),C(e.status,o?zr:void 0),re.createElement(Y,{color:"connected"===e.status?br.GREEN:"authenticated"===e.status?br.CYAN:"requires_auth"===e.status?br.YELLOW:br.GRAY,backgroundColor:o?zr:void 0}," ",k(e)," ")))})),N&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",I+1,"–",Math.min(M,y.length)," of"," ",y.length,I>0?" · ↑ more":"",M<y.length?" · ↓ more":"")),u&&re.createElement(Q,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(We,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},0===t.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Bt(),_n(),Xn(),Vr();var hM=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(0),[s,i]=se(!0),[a,l]=se(null);ae(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(Z((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),s)return re.createElement(Q,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:br.DIM},"Loading memory files..."));if(a)return re.createElement(Q,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:br.RED},Re.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return re.createElement(Q,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:br.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},re.createElement(Q,null,re.createElement(Y,{color:br.WHITE,bold:!0},"Select memory to edit:")),re.createElement(Q,{columnGap:4,marginTop:1},re.createElement(Q,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?br.WHITE:br.DIM},r===t?`${Hn} `:" ",e.label))),re.createElement(Q,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?br.WHITE:br.DIM},e.description)))))},"MemorySelector");Bt(),Vr(),Bt(),Xn(),Po(),Vr();var fM={"Interrupted by user":"Interrupted by user","Insufficient credits":qn};function UserMessage({content:e,images:t,imageCount:n=0,ideHint:r}){const o="Interrupted by user"===e,s="Insufficient credits"===e,i=e.startsWith("Error:"),a=o||s||i,l=a&&fM[e]||e,u=null!=t?t.length:n,d=ie(null);null===d.current&&t&&t.length>0&&(d.current=t.map((e,t)=>saveTempImage(e,t+1)));const m=d.current??[];return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{backgroundColor:a?void 0:Rr.BG,paddingRight:1},re.createElement(Y,{color:a?br.RED:Rr.POINTER,bold:!a},Re.pointer),re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:a?br.RED:Rr.FG,wrap:"wrap"},l))),u>0&&re.createElement(Q,{marginLeft:1},re.createElement(Y,{color:br.DIM},"⎿"," ",Array.from({length:u},(e,t)=>{const n=m[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))),r&&!a&&re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:qr},Rx),re.createElement(Y,{color:br.DIM}," ","Selected ",r.lines," ",1===r.lines?"line":"lines"," from"," ",r.file," in ",r.ide)))}function AutoCompactMessage({content:e}){return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},Re.bullet," ",e))}function ZdrPausedMessage(){return re.createElement(Q,{marginTop:1,marginBottom:1},re.createElement(Y,null,re.createElement(Y,{color:br.DIM},Re.bullet," "),re.createElement(Y,{color:br.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),re.createElement(Y,{color:Fr.CODE},"/configure-models"),re.createElement(Y,{color:br.DIM}," to review · esc to dismiss")))}function TasteSkipMessage(){return re.createElement(Q,{marginTop:1,marginBottom:1},re.createElement(Q,{flexShrink:0},re.createElement(Y,{backgroundColor:vr.BADGE_BG,color:vr.BADGE_FG,bold:!0},$x)),re.createElement(Y,{color:br.DIM}," Skipped. Run "),re.createElement(Y,{color:Fr.CODE},"/learn-taste"),re.createElement(Y,{color:br.DIM}," or "),re.createElement(Y,{color:Fr.CODE},"cmd learn-taste"),re.createElement(Y,{color:br.DIM}," anytime."))}function HookWarningMessage({content:e}){return re.createElement(Q,null,re.createElement(Y,{color:br.YELLOW},Re.warning),re.createElement(Q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.YELLOW},e)))}function HookLineMessage({content:e}){return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return re.createElement(Q,{flexDirection:"column"},void 0!==t&&re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},` ${t}`)),e.map((e,t)=>re.createElement(Q,{key:t,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function GoalLineMessage({content:e,subline:t}){return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:qr},Rx),re.createElement(Y,{color:br.DIM,wrap:"wrap"}," ",e)),t?re.createElement(Q,{marginLeft:4,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},t)):null)}function GoalAcceptMessage({command:e,acceptLine:t,hint:n}){return re.createElement(Q,{flexDirection:"column"},re.createElement(UserMessage,{content:e}),re.createElement(GoalLineMessage,{content:t,subline:n}))}function GoalCompleteMessage({elapsed:e,turns:t,goal:n}){const r=`${t} ${1===t?"turn":"turns"}`;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,null,re.createElement(Y,{color:br.GREEN},Re.tick," Goal achieved"),re.createElement(Y,{color:br.DIM},` (${e} · ${r})`))),re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},"Goal: ",n)))}function GoalStatusMessage({state:e,headline:t,goal:n,detail:r,hint:o}){const s="completed"===e?Re.tick:"paused"===e?"⏸":"idle"===e?Re.circle:Re.bullet,i="completed"===e?br.GREEN:"paused"===e?br.YELLOW:br.DIM;return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:i},s," ",t)),re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},n)),r?re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM,wrap:"wrap"},r)):null,o?re.createElement(Q,{marginLeft:2,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},o)):null)}function InfoMessage({content:e,metadata:t}){if(t?.isTasteSkip)return re.createElement(TasteSkipMessage,null);if(t?.isAutoCompact)return re.createElement(AutoCompactMessage,{content:e});if(t?.hookFrame&&t.hookFrame.length>0)return re.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader});if(t?.isHookLine)return re.createElement(HookLineMessage,{content:e});if(t?.isHookLineContinuation)return re.createElement(HookLineContinuationMessage,{content:e});if(t?.isHookWarning)return re.createElement(HookWarningMessage,{content:e});if(t?.isSuccess)return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.GREEN},Re.tick," ",e));if(t?.isGoalAccept)return re.createElement(GoalAcceptMessage,{command:e,acceptLine:t.goalAcceptLine??"",hint:t.goalSubline});if(t?.isGoalComplete)return re.createElement(GoalCompleteMessage,{elapsed:t.goalElapsed??"",turns:t.goalTurns??1,goal:t.goalText??""});if(t?.isGoalStatus)return re.createElement(GoalStatusMessage,{state:t.goalState??"running",headline:t.goalHeadline??"",goal:t.goalText??"",detail:t.goalDetail,hint:t.goalSubline});if(t?.isGoalNotice){const n="cleared"===t.goalNoticeKind?Re.tick:"none"===t.goalNoticeKind?Re.circle:"paused"===t.goalNoticeKind?"⏸":Re.bullet;return re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},n," ",e))}return t?.isGoalLine?re.createElement(GoalLineMessage,{content:e,subline:t.goalSubline}):re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:br.DIM},Re.bullet," ",e))}__name(UserMessage,"UserMessage"),__name(AutoCompactMessage,"AutoCompactMessage"),__name(ZdrPausedMessage,"ZdrPausedMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(HookLineMessage,"HookLineMessage"),__name(HookLineContinuationMessage,"HookLineContinuationMessage"),__name(HookFrameMessage,"HookFrameMessage"),__name(GoalLineMessage,"GoalLineMessage"),__name(GoalAcceptMessage,"GoalAcceptMessage"),__name(GoalCompleteMessage,"GoalCompleteMessage"),__name(GoalStatusMessage,"GoalStatusMessage"),__name(InfoMessage,"InfoMessage"),Bt(),_n(),bo(),mv(),Go(),Ro(),Co(),Vr(),Bt(),Vr();var yM=bt()?"⠶":"#";function AssistantMessage({content:e}){return re.createElement(Q,null,re.createElement(Y,{color:Nr},yM),re.createElement(Q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=br.GREEN,s=Re.tick,i="default",a=t||"(No output)";n&&(o=br.YELLOW,s=Re.arrowRight,i=br.YELLOW,a="Executing…"),r&&(o=br.RED,s=Re.cross,i=br.RED);const l=le(()=>buildTreeConnectors(a),[a]);return re.createElement(Q,null,re.createElement(Y,{color:o},s),re.createElement(Q,{flexDirection:"column",marginLeft:1},re.createElement(Q,null,re.createElement(Y,{color:br.GRAY},"$ "),re.createElement(Y,{color:o,bold:!0},e)),re.createElement(Q,{columnGap:1,marginLeft:1},re.createElement(Y,{color:qr},l),re.createElement(Y,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?br.YELLOW:void 0,o=le(()=>buildTreeConnectors(e),[e]);return re.createElement(Q,{flexDirection:"column",marginBottom:0,marginTop:-1},re.createElement(Q,{columnGap:1},re.createElement(Y,{color:qr},o),re.createElement(Q,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:r},e))),t&&re.createElement(Q,{marginLeft:3},re.createElement(Y,{color:br.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return re.createElement(Q,null,re.createElement(Y,{color:br.RED},t?Re.pointer:Re.warning),re.createElement(Q,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?re.createElement(Y,{color:br.RED,wrap:"wrap"},e):re.createElement(Markdown,{color:br.RED},e)))}__name(AssistantMessage,"AssistantMessage"),Bt(),Vr(),__name(BashMessage,"BashMessage"),Bt(),Vr(),__name(CommandResultMessage,"CommandResultMessage"),Bt(),Vr(),__name(ErrorMessage,"ErrorMessage"),Bt(),Vr();var wM={connected:{char:Re.tick,color:br.GREEN},installed:{char:Re.tick,color:br.GREEN},up_to_date:{char:Re.tick,color:br.GREEN},needs_reload:{char:Re.circle,color:br.YELLOW},failed:{char:Re.cross,color:br.RED},not_in_ide:{char:Re.circle,color:br.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getStatusHeadline(e,t),i=wM[e];return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,null,re.createElement(Y,{color:i.color},i.char),re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:br.CYAN},o),s&&re.createElement(Y,null,s))),n?.map((e,t)=>re.createElement(Y,{key:t,color:br.DIM}," ",e)))}function ReasoningMessage({content:e,expandedOutput:t,expandKey:n,isStreaming:r=!1}){const o=e?Math.max(1,Math.round(e.length/500)):1,s=Boolean(e),i=(s?e.split("\n"):[]).length,a=`${r?"Thinking…":`Thought for ${o} second${1!==o?"s":""}`}${r&&!t&&i>0?` (${i} line${1!==i?"s":""})`:""}`,l=t&&s,u=!t&&s,d=r&&t&&e.length>560,m=d?e.length-560:0,g=80*Math.floor(m/80),h=d?(e.slice(0,g).match(/\n/g)??[]).length:0,f=d?e.slice(g):e;return re.createElement(Q,{flexDirection:"column",width:"90%"},re.createElement(Q,null,re.createElement(Y,{color:Cr},"✻"," "),re.createElement(Y,{color:Cr},u?`${a} `:a),u&&re.createElement(BracketWrap,{color:br.DIM},`${n}+o to expand`)),l&&d&&re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:br.DIM},h>0?`… (${h} more line${1!==h?"s":""})`:"…")),l&&re.createElement(Q,{marginLeft:2,flexDirection:"column"},re.createElement(Y,{color:Cr,wrap:"wrap",italic:!0},f)))}__name(IDEStatusMessage,"IDEStatusMessage"),Bt(),Vr(),__name(ReasoningMessage,"ReasoningMessage"),Bt(),Bt(),_n();function HelpMessage(){const e=getInvokedCommandName(),t=le(()=>GT.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return re.createElement(Q,{flexDirection:"column",paddingY:1},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:br.GRAY}," v","0.39.0")),re.createElement(Y,{color:br.GRAY},BT)),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Usage"),re.createElement(Q,{paddingLeft:2},re.createElement(Y,null,e," <command> [options]"))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Options"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},WT.map(t=>re.createElement(Q,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(qT)),re.createElement(Y,{color:br.GRAY},t.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Commands"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},VT.map(t=>re.createElement(Q,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(qT)),re.createElement(Y,{color:br.GRAY},t.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Slash Commands"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},t.map(e=>re.createElement(Q,{key:e.key},re.createElement(Y,null,e.key.padEnd(qT)),re.createElement(Y,{color:br.GRAY},e.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Keyboard Shortcuts"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},HT.map(e=>re.createElement(Q,{key:e.key},re.createElement(Y,null,e.key.padEnd(qT)),re.createElement(Y,{color:br.GRAY},e.description))))),re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Examples"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},QT.map(t=>re.createElement(Q,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(qT)),re.createElement(Y,{color:br.GRAY},t.description))))),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.CYAN},Re.pointer),re.createElement(Y,{color:br.GRAY}," ",YT.replace(/cmd/,e))),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{bold:!0},"Links"),re.createElement(Q,{flexDirection:"column",paddingLeft:2},KT.map(e=>re.createElement(Q,{key:e.key},re.createElement(Y,null,e.key.padEnd(qT)),re.createElement(Y,{color:br.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?re.createElement(HelpMessage,null):re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{wrap:"wrap"},re.createElement(Markdown,null,e)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0,n=e.metadata?.ideHint;return re.createElement(UserMessage,{content:e.input,images:t,ideHint:n})}return"assistant"===e.role?re.createElement(AssistantMessage,{content:e.input}):"reasoning"===e.role?re.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?re.createElement(ToolMessage,{name:av(e.name||""),input:e.input,output:e.output||"",isPending:ov(e),hasError:rv(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?re.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:ov(e),hasError:rv(e)}):"system"===e.role?re.createElement(SystemMessage,{content:e.input}):"info"===e.role?re.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?re.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?re.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?re.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName2(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getProviderShortName(e){return e?Sn[e]?.shortLabel??e.slice(0,4):""}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [ctrl+e to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),o="─".repeat(r);return re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Mr},o),re.createElement(BracketedText,{text:n,color:Mr}),re.createElement(Y,{color:Mr},o))}Vr(),uE(),Ro(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName2,"getModelShortName"),__name(getProviderShortName,"getProviderShortName"),__name(TranscriptDivider,"TranscriptDivider");var SM=re.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentProvider:s,hiddenCount:i=0})=>{const a=i>0?{role:"transcript-divider",count:i}:null,l=[...t?["header"]:[],...a?[a]:[],...e],u=useTerminalWidth(),d=le(()=>DP(u),[u]),m=le(()=>BP(u),[u]),g=le(()=>getPackageJson().version||"0.0.0",[]),h=le(()=>getGitHeaderInfo(),[]),f=le(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?getModelShortName2(o):"sonnet-4.6",w="taste-1",S=le(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=getReasoningEffort(o);return e?` with ${e} effort`:""},[o,n]),E=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO,v=E?" · co":"",C=E&&s?` · ${getProviderShortName(s)}`:"";return re.createElement(J,{items:l,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return re.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:u});if("header"===e)return"compact"===m?re.createElement(Q,{key:"header",marginBottom:1,flexDirection:"row"},re.createElement(Q,{width:jP,flexShrink:0},re.createElement(qP,null,FP)),re.createElement(Q,{flexDirection:"column",marginLeft:2},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Mr}," ","v",g)),re.createElement(Y,{color:Mr},"models: ",y,S," ·"," ",w,v),re.createElement(Y,{color:Mr},f,h&&h.isLocal&&h.branch&&` (${h.branch})`))):re.createElement(Q,{key:"header",marginBottom:1,flexDirection:"column"},re.createElement(qP,null,d.trimEnd()),re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Q,null,re.createElement(Y,{color:Mr},"# "),re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Mr}," v",g)),re.createElement(Y,{color:Mr},"# models: ",y,S," · ",w,C,v),re.createElement(Q,null,re.createElement(Y,{color:Mr},"# ",f,h&&h.isLocal&&h.branch&&re.createElement(Y,{color:Mr}," ","(branch:"," ",h.branch,")")))));const t=e,n=renderFeedEntry(t,r);return re.createElement(Q,{key:t.id,paddingBottom:1,width:"90%"},n)})});Bt(),mv(),No(),Vr();var bM=oe(__name(function LiveAgentStatusInner2({entry:e}){const t=av(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=se(".");return ae(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),re.createElement(Q,{flexDirection:"column",marginBottom:1,width:"90%"},re.createElement(Q,null,re.createElement(Y,{backgroundColor:Ar.BG,color:Ar.FG,bold:!0},` ${t} `),o&&re.createElement(Y,null," (",o,")")),re.createElement(Q,{columnGap:1,marginLeft:1},re.createElement(Y,null,"⎿"," "),re.createElement(Y,{color:br.GRAY},"Running (",formatTime2(i)," |"," ",formatTokens(s),")",l)),a.length>0&&re.createElement(Q,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=av(e.name);return re.createElement(Q,{key:t,columnGap:1},re.createElement(Y,{color:br.GRAY},"⎿"),re.createElement(Y,{color:br.GRAY}," ",n),e.input&&re.createElement(Y,{color:br.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),EM=oe(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:re.createElement(bM,{entry:e})},"LiveAgentStatus"));Bt(),_n(),bo(),Co(),No(),Ro(),Vr(),Bt(),Vr();var vM={low:"Fast responses with lighter reasoning",medium:"Balances speed and reasoning depth for everyday tasks",high:"Greater reasoning depth for complex problems",xhigh:"Extra reasoning depth for complex problems",max:"Maximum reasoning budget for the hardest problems"},CM={value:void 0,label:"Default",description:"Use the provider default reasoning level"},kM=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=le(()=>[CM,...t.map(e=>({value:e,label:e,description:vM[e]}))],[t]),i=le(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),a=__name((e,t)=>`${e+1}. ${t}`,"labelText"),l=le(()=>Math.max(...s.map((e,t)=>a(t,e.label).length))+4,[s]),{cursor:u}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:i,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Er,bold:!0},`Select reasoning effort for ${e}`)),re.createElement(Q,{flexDirection:"column"},s.map((e,t)=>{const r=t===u,o=e.value===n;return re.createElement(Q,{key:e.label},re.createElement(Y,{color:r||!o?br.WHITE:br.GREEN,backgroundColor:r?zr:void 0,bold:r||o},a(t,e.label).padEnd(l)),re.createElement(Y,{color:r?br.WHITE:br.DIM,backgroundColor:r?zr:void 0},e.description," "),o&&re.createElement(Y,{color:br.GREEN}," ",Re.tick))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑/↓ navigate · enter to select · esc to go back")))},"ReasoningEffortSelector");ir();var TM="Loading plan info…",_M=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups2(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,_M);e.length>0&&n.push({...r,models:e})}return n}function flattenGroups(e){const t=[];for(const n of e)for(const e of n.models)t.push({providerId:n.providerId,model:e});return t}function groupByModelProvider2(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups2,"searchGroups"),__name(flattenGroups,"flattenGroups"),__name(groupByModelProvider2,"groupByModelProvider");var xM=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0,refreshBanner:a})=>{const[l,u]=se(""),[d,m]=se(null),[g,h]=se(()=>new Set),f=le(()=>isInternalTeamFlagEnforced(),[]),y=le(()=>f?bn:groupByModelProvider2(En.flatMap(e=>e.models),Sn["command-code"].id),[f]),w=le(()=>searchGroups2(y,l),[y,l]),S=le(()=>flattenGroups(w),[w]),[E,v]=se(0),C=useTerminalHeight()-1,k=Math.max(4,C-14-2*w.length),T=void 0!==o,_=le(()=>T?null:getCachedBillingContext(),[T]),[x,A]=se(_),[P,I]=se(!T&&!_);ae(()=>{if(T)return;if(x)return;let e=!0;return getBillingContext().then(t=>{e&&(A(t),I(!1))}),()=>{e=!1}},[T,x]);const M=!T&&!0===x?.fetchFailed,R=T?o:x?.planId??null,N=T?s:x?.purchasedCredits??0,L=T?i:x?.freeCredits??0,$=f?Sn.anthropic.id:Sn["command-code"].id,D=r??$,O=n?Math.max(0,S.findIndex(e=>e.model.id===n&&e.providerId===D)):0,[F,j]=se("model"),[U,B]=se(null),{cursor:q,error:z,setError:H}=useListNavigation({items:S,onSelect:__name(t=>{const n=getSupportedEfforts(t.model.id);if(n&&n.length>0)return B(t),void j("effort");e(t.model.id,t.providerId)},"onSelect"),onCancel:t,initialIndex:O,searchQuery:l,onSearchChange:u,isActive:"model"===F,validate:__name(e=>{if(g.has(e.providerId))return`Run /provider to authenticate with ${getProviderConfig(e.providerId)?.displayName??e.providerId} first`;if(d&&!f){const t=Sn[d]?.supportedModelProviders;if(t&&!t.includes(e.model.provider))return`${Sn[d]?.label??d} does not support ${e.model.provider} models. Switch provider via /provider.`}if(P)return TM;const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:R,purchasedCredits:N,freeCredits:L});return t.allowed?null:t.errorMessage??"Model not available for your plan"},"validate")});ae(()=>{v(e=>clampScrollOffset({cursor:q,total:S.length,maxVisible:k,currentOffset:e}))},[q,S.length,k]);const W=ie(!1),G=__name(t=>{if(!U||W.current)return;W.current=!0;const{model:r,providerId:o}=U,s=getReasoningEffort(r.id),i=t!==s,l=r.id===n;(async()=>{try{i&&(await setReasoningEffort({modelId:r.id,effort:t}),l&&a?.())}catch(e){dlog(`[Model] Failed to persist reasoning effort: ${e}`)}finally{e(r.id,o)}})()},"handleEffortSelect"),V=__name(()=>{W.current||(B(null),j("model"))},"handleEffortCancel");if(ae(()=>{if(P)return;if(z!==TM)return;const e=S[q];if(!e||M)return void H(null);const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:R,purchasedCredits:N,freeCredits:L});H(t.allowed?null:t.errorMessage??"Model not available for your plan")},[P,M,z,H,S,q,R,N,L]),ae(()=>{(async()=>{await isOAuthEnforced()&&m(await getConfiguredProvider())})()},[]),ae(()=>{(async()=>{const e=new Set(y.map(e=>e.providerId)),t=new Set;for(const n of e){const e=getProviderConfig(n);e?.requiresAuth&&e.checkAuth&&(await e.checkAuth()||t.add(n))}h(t)})()},[y]),"effort"===F&&U){const e=getSupportedEfforts(U.model.id)??[];return re.createElement(kM,{modelLabel:U.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(U.model.id),onSelect:G,onCancel:V})}const K=E,J=E+k;let X=0;const Z=w.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:X,windowStart:K,windowEnd:J});return X+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),ee=S.length>k;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Select model")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{dimColor:!0},f?"Select a model and provider. Sets the default for new sessions; other open sessions are unaffected. Provider is saved.":"Switch between Command Code models. Sets the default for new sessions; other open sessions are unaffected.")),re.createElement(Q,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(QP,{query:l,resultCount:l?S.length:void 0,placeholder:"Type to search models..."})),0===S.length?re.createElement(Q,{marginY:1},re.createElement(Y,{color:br.GRAY},'No models match "',l,'"')):re.createElement(Q,{flexDirection:"column"},Z.map(({group:e,groupWindow:t},r)=>re.createElement(Q,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},f?re.createElement(Y,{bold:!0,color:Er},e.label):re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(NI,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===q,isCurrent:r.id===n&&e.providerId===D,showProviderLabel:!!f&&void 0}))))),ee&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",K+1,"–",Math.min(J,S.length)," of ",S.length,K>0?" · ↑ more":"",J<S.length?" · ↓ more":"")),z&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.GRAY},z)),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"type to search · ↑/↓ navigate · enter to select"),l?re.createElement(Y,{color:br.DIM}," · esc to clear"):re.createElement(Y,{color:br.DIM}," · esc to cancel")))},"ModelSelector");Bt(),bo(),Co(),ir();var AM=__name(({currentModel:e,onClose:t,refreshBanner:n})=>{const r=getSupportedEfforts(e)??[],o=findModelById(e)?.label??getModelDisplayName(e),s=ie(!1),i=__name(r=>{if(s.current)return;s.current=!0;const o=r!==getReasoningEffort(e);(async()=>{try{o&&(await setReasoningEffort({modelId:e,effort:r}),n())}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),a=__name(()=>{s.current||t()},"handleCancel");return re.createElement(kM,{modelLabel:o,supportedEfforts:r,currentEffort:getReasoningEffort(e),onSelect:i,onCancel:a})},"EffortSelector");Bt(),Ro(),Vr();var PM=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,i=n&&-1===s;return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},re.createElement(Q,null,re.createElement(Y,{bold:!0},"Select AI Provider")),n&&re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:br.DIM},"Current: "),re.createElement(Y,{color:br.GREEN},getProviderDisplayName(n)),i&&re.createElement(Y,{color:br.YELLOW}," ","[OAuth enforced]"))),re.createElement(Q,{marginBottom:0},re.createElement(Y,{color:br.DIM},"Available Providers:")),re.createElement(ft,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>re.createElement(Y,{color:e?br.CYAN:br.GRAY,bold:e&&isLightTheme()},e?Re.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?br.CYAN:br.DIM,bold:e&&isLightTheme()},` ${t}`)}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=se(0);if(ae(()=>{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 re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:Or,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Bt(),Vr(),__name(RetryMessage,"RetryMessage"),Bt(),Rs(),Xn(),Vr();var IM=[{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"}],MM=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=le(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=se(Math.max(0,r.length-1)),[i,a]=se(Math.max(0,r.length-8)),[l,u]=se("checkpoint"),[d,m]=se(null),[g,h]=se(0),f=le(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),y=le(()=>f?IM:IM.filter(e=>"conversation"===e.mode),[f]);if(ae(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),Z((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[o]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:Er,bold:!0},"Rewind"),re.createElement(Y,{color:br.DIM},"No checkpoints available. Start a conversation to create checkpoints."),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to close")));if("mode"===l&&d)return re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:Er,bold:!0},"Rewind"),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Restore to: "),re.createElement(Y,{color:br.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),re.createElement(Q,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return re.createElement(Q,{key:e.mode,flexDirection:"column"},re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:n?Er:void 0},n?`${Hn} `:" "),re.createElement(Q,{flexDirection:"column"},re.createElement(Y,{color:n?Er:br.WHITE},e.label),re.createElement(Y,{color:br.DIM},e.description))),!r&&re.createElement(Y,null," "))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Enter"),re.createElement(Y,{color:br.DIM}," to confirm, "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to go back")));const w=r.slice(i,i+8);return re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:Er,bold:!0},"Rewind"),re.createElement(Y,{color:br.DIM},"Select a checkpoint to restore your session"),r.length>8&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),re.createElement(Q,{marginTop:1}),re.createElement(Q,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return re.createElement(Q,{key:e.messageId,flexDirection:"column"},re.createElement(Q,{flexDirection:"row"},re.createElement(Y,{color:s?Er:void 0},s?`${Hn} `:" "),re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:s?Er:br.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),re.createElement(Y,{color:br.DIM}," • "),re.createElement(Y,{color:br.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),re.createElement(Y,{color:br.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&re.createElement(Y,null," "))})),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Enter"),re.createElement(Y,{color:br.DIM}," to select, "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to cancel")))},"RewindSelector");Bt(),Vr();var RM=[{label:"Complete brief",desc:"If the target, goal, audience, or artifact is clear, act without asking."},{label:"Composition",desc:"Choose layout from the work pattern: monitor, operate, compare, configure, learn, decide, or explore."},{label:"Scope",desc:"Broad prompts get the full mode pass. Narrow prompts stay narrow."},{label:"Truth",desc:"Only claim changes that exist in files and are visible or verifiable."},{label:"Templates",desc:"design-html and report-html are documentation templates, not UI inspiration."},{label:"Reports",desc:"Follow-up modes read markdown reports, apply relevant findings, then still run their own full mode pass."}],NM=['/design redesign "Make this dashboard feel like an operator console"','/design motion "Animate the whole page and add missing interactions"','/design checkup "Audit this UI and generate the design report"','/design "Build a landing page for a privacy-first contract review tool"'],LM=__name(({onCancel:e})=>(Z((t,n)=>{n.escape&&e()}),re.createElement(Q,{flexDirection:"column",paddingLeft:2,paddingRight:2},re.createElement(Q,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Use"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},re.createElement(Y,{color:br.DIM},'/design <mode> "target or request"'),re.createElement(Y,{color:br.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),re.createElement(Q,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Modes"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},WA.map(e=>re.createElement(Q,{key:e.name,columnGap:2},re.createElement(Q,{width:18,flexShrink:0},re.createElement(Y,{color:br.CYAN},"/design ",e.name)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},e.description)))))),re.createElement(Q,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Working rules"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},RM.map(e=>re.createElement(Q,{key:e.label,columnGap:2},re.createElement(Q,{width:16,flexShrink:0},re.createElement(Y,{color:br.CYAN},e.label)),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},e.desc)))))),re.createElement(Q,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:Er},"Quick examples:"),re.createElement(Q,{paddingLeft:2,flexDirection:"column"},NM.map(e=>re.createElement(Y,{key:e,color:br.DIM},e)))),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Bt(),ir(),Bt(),Bt();var $M=__name(e=>{const[t,n]=se(e),[r,o]=se(null);return ae(()=>{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 FC.on("reset",t),FC.on("new-event",r),()=>{FC.off("reset",t),FC.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new hS({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o,s;try{const e=await getOAuthCredentials({provider:n});o=e.token,s=e.oauthProvider,validateOAuthToken({token:o,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[Wt.PROJECT_SLUG]:fv.getCurrentProjectDirName(),[Wt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(i[Wt.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[Wt.OAUTH_PROVIDER]=s)),{request:t,headers:i}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}function buildObserverPrompt(e,t){return`Produce ${t} varied observations for these prompts:\n\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),FC.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()}`),FC.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){const r=getTasteObserverModel({sessionModel:getConfiguredModel()});dlog(`[ObserverAPI] calling ${Gt.ALPHA.GENERATE} with model: ${r}`);const o={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:r,system:"You scan prompts and produce casual observations like a dev friend glancing at someone's work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words per observation\n- one observation per line\n- sound human, not robotic\n- output only the observations, no preamble",max_tokens:200,temperature:.7,stream:!0},threadId:Me()},s=await e.post({endpoint:Gt.ALPHA.GENERATE,body:o,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const i=createInsightEmitter();await consumeSSEStream(s,{onText:__name(e=>{i.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${i.getChunkCount()} chunks received`),i.emitRemaining(),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(FC.observerHasRun)return;FC.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r={...n,[Wt.SESSION_ID]:`observer-${Me()}`},o=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${o.length} batches`);const s=Math.min(o.length,6);for(let t=0;t<s;t++){if(FC.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const n=o[t];try{await processBatch(e,r,n,t+1,o.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),FC.addEvent({type:"progress",message:"Continuing without live observations..."})}}Bt(),Bt(),LS(),VS(),ir(),Bt(),_n(),ir(),Bt(),Bt(),_n(),LS(),VS(),Sv(),ir(),Co(),No(),__name(createRequestClient,"createRequestClient"),Bt(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Bt(),Bt(),ir(),os(),Bt(),_n(),Co(),AE(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var DM=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(w.homedir(),".claude","projects");await C.access(r);const o=getProjectDirName2(process.cwd());dlog(`[Import] scanning project: ${o}`);const s=(await C.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await C.stat(s)).isDirectory())continue;const r=(await C.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),i=await C.stat(r),a=o.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{FC.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&FC.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async findCursorSessions(e=0){try{FC.addEvent({type:"progress",message:"Scanning Cursor sessions..."});const t=await findCursorSessions(process.cwd(),e);return dlog(`[Import] found ${t.length} Cursor sessions`),t}catch(e){return dlog("[Import] no cursor sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await C.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[],o=[];try{FC.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),i=s.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,o=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length},{name:"Cursor",count:n.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);FC.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${o.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&s.push({agent:"cursor",sessionIds:n.map(e=>e.id),displayName:"Cursor"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:r,learnedSessions:a+l+u,agentSessions:s,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));o.push(...e)}const y=n.length+r.length+o.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${o.length})`),FC.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:o,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){FC.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});FC.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const s=getApiBaseUrl(),i=new hS({baseUrl:s});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&FC.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),s=new fx({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await s.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),FC.markLearningComplete(),await E,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}if(o.length>0){const e=o.map(e=>e.id);await markSessionsAsLearned("cursor",e),dlog(`[Import] marked ${e.length} cursor sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const l=await this.extractLearningSummary(),u=[];if(n.length>0&&u.push(`Claude Code (${n.length})`),r.length>0&&u.push(`Codex (${r.length})`),o.length>0&&u.push(`Cursor (${o.length})`),!a){const s=FC.getEvents().some(e=>"error"===e.type&&e.message?.toLowerCase().includes("insufficient credits")),i="Learning failed - sessions not marked as learned";return e.push(i),s||FC.addEvent({type:"error",message:i}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}return FC.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),FC.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const t=e.join(process.cwd(),".commandcode","taste","taste.md"),n=await C.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}},OM=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),FM=__name(e=>{const[t,n]=se({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return ae(()=>{FC.reset(),FC.markImportStarted(),(async()=>{try{const t=await Promise.race([DM.importAndLearn(),OM(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");Bt();var jM=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");Bt(),ir();var UM=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=se(null),[o,s]=se(null),i=ie(!1);return ae(()=>{if(i.current)return;let n=null;return(async()=>{try{i.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{FC.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{FC.reset(),e()}}Bt(),ir(),Bt(),ir(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var BM=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=ie(n),o=ce(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ce(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ce(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ce(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ce(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Bt(),ir();var qM=__name(({conditions:e,autoLearn:t})=>{const[n,r]=se("checking"),o=ie(!1);return ae(()=>{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]),ae(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Bt(),Bt(),Vr();var zM=__name(({error:e})=>re.createElement(Q,{padding:1},re.createElement(Q,{flexDirection:"column",borderColor:br.RED,padding:1},re.createElement(Q,{marginBottom:1},re.createElement(Y,null,"Error initializing onboarding: ",e)),re.createElement(Q,null,re.createElement(Y,null,"Continuing without onboarding...")))),"OnboardingError");Bt(),Bt(),Vr();var HM=__name(()=>re.createElement(Y,null,"Skip"),"SkipOptionText"),WM=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=se(1);return Z((e,t)=>{t.escape?r():"n"!==e&&"N"!==e?t.upArrow||t.downArrow?s(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===o?n():r()):r():n():dismissOnboardingForeverForProject().then(()=>r())}),re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:vr.TEXT,paddingX:1,paddingY:0},re.createElement(Y,{color:vr.TEXT,bold:!0},"Build Your Coding Taste"),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Y,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),re.createElement(Q,{marginTop:1},re.createElement(Y,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),re.createElement(Q,{marginTop:1,flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:1===o?vr.TEXT:br.GRAY},1===o?Re.pointer:" "," 1. Yes, learn (recommended)")),re.createElement(Q,null,re.createElement(Y,{color:2===o?vr.TEXT:br.GRAY},2===o?Re.pointer:" "," 2."," ",re.createElement(HM,null)))),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"↑↓ · "),re.createElement(Y,{color:Fr.CODE},"enter"),re.createElement(Y,{color:br.DIM}," ok · "),re.createElement(Y,{color:Fr.CODE},"esc"),re.createElement(Y,{color:br.DIM}," skip · "),re.createElement(Y,{color:Fr.CODE},"n"),re.createElement(Y,{color:br.DIM}," never")))},"ImportChoice");Bt(),Bt(),Vr();var GM=__name(({error:e})=>re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:br.RED,paddingX:2,paddingY:1,marginBottom:2},re.createElement(Y,{color:br.RED,bold:!0},"Oops, something went wrong:"),re.createElement(Q,{marginTop:1},re.createElement(Y,null,e))),"ErrorSection");Bt(),Bt(),Vr(),Bt(),Bt(),Bt(),Vr(),Bt(),Vr();var VM=__name(()=>re.createElement(Y,{backgroundColor:vr.BADGE_BG,color:vr.BADGE_FG},$x),"TasteBadge");Bt(),Vr(),Bt();var KM=["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"],QM="⎿",YM=__name(()=>{const[e,t]=se(()=>Math.floor(Math.random()*KM.length));return ae(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*KM.length))},2e3);return()=>clearInterval(e)},[]),re.createElement(Y,{color:br.YELLOW},KM[e],"...")},"PulsingText");Bt(),Vr();var JM=[Re.bullet,Re.squareSmallFilled,Re.lozenge,Re.star,Re.triangleRight,Re.triangleUp,Re.circleFilled,Re.pointer],XM=__name(e=>String(e).padStart(3," "),"padNum"),ZM=__name(e=>JM[e%JM.length],"getSymbol"),eR=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${XM(t)} ↓${XM(n)} (↑↓ scroll)`,"buildStatusLine"),tR=__name(({insights:e})=>{const[t,n]=se(0),[r,o]=se(!0),s=e.length,i=s>10,a=Math.max(0,s-10);if(ae(()=>{r&&i&&n(a)},[s,r,i,a]),Z((e,t)=>{if(i)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&o(!0),t}))}),0===s)return null;const l=e.slice(t,t+10),u=t,d=s-t-10;return re.createElement(Q,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&re.createElement(Y,{color:br.DIM},eR(s,u,d,r)),l.map((e,n)=>{const r=t+n;return re.createElement(Q,{key:r,marginBottom:0},re.createElement(Y,{color:br.DIM},ZM(r)," ",e))}))},"ScrollableInsights");Bt(),Vr();var nR=__name(()=>{const[e,t]=se(!0);return ae(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),re.createElement(Y,{color:br.YELLOW},e?Re.circleFilled:Re.circle)},"PulsingDot"),rR=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return re.createElement(Q,{flexDirection:"column",marginBottom:0},re.createElement(VM,null),re.createElement(Q,{marginTop:0},re.createElement(Y,{color:br.DIM},QM),re.createElement(Q,{marginLeft:2},a?re.createElement(Y,{color:vr.TEXT},"learned your coding taste"):re.createElement(YM,null))));const u=__name(()=>r?re.createElement(Y,{color:_r.BG},Re.square):n?re.createElement(nR,null):re.createElement(Y,{color:br.DIM},Re.circle),"getStatusIcon"),d=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||d?re.createElement(Q,{flexDirection:"column",marginBottom:0},(n||r)&&re.createElement(Q,{marginBottom:0},re.createElement(Q,{marginRight:1},u()),re.createElement(Y,{color:r?br.WHITE:n?br.YELLOW:br.DIM},e)),r&&t&&(!l||0===l.learningCount)&&re.createElement(Q,{marginLeft:3,marginBottom:0},re.createElement(Y,{color:br.DIM},t)),o.length>0&&re.createElement(Q,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>re.createElement(Y,{key:t,color:br.DIM},`${Re.bullet} ${e}`))),s.length>0&&re.createElement(tR,{insights:s}),r&&l&&l.learningCount>0&&re.createElement(Q,{flexDirection:"column",marginLeft:1,marginBottom:0},re.createElement(Q,{marginBottom:1,flexDirection:"row"},re.createElement(Y,null,QM),re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:vr.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),re.createElement(Q,{flexDirection:"column",marginLeft:1},re.createElement(Y,{color:br.DIM},Re.pointerSmall," Stored in ",l.storage),re.createElement(Y,{color:br.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),oR=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return re.createElement(Q,{flexDirection:"column",marginBottom:1},e.map((e,n)=>re.createElement(Q,{key:e.id,marginLeft:0===n?0:3},re.createElement(rR,{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"),sR=__name(({steps:e})=>re.createElement(oR,{steps:e}),"ProgressSection");Bt(),Vr();var iR=__name(({isImporting:e=!1,waitingForInput:t=!1})=>re.createElement(re.Fragment,null,e&&re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"ESC to cancel")),t&&re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Bt();var aR=[{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"}}],lR=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=$M(aR),{isImporting:s,waitingForInput:i,error:a}=FM(t);return jM({onEscape:__name(()=>{i&&((a||o)&&n?n():e())},"onEscape"),onEnter:__name(()=>{i&&((a||o)&&n?n():e())},"onEnter"),enabled:s||i}),re.createElement(Q,{flexDirection:"column",padding:1},o&&re.createElement(GM,{error:o}),!o&&re.createElement(sR,{steps:r}),re.createElement(iR,{isImporting:s,waitingForInput:i}))},"ImportProgress"),cR=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?re.createElement(WM,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?re.createElement(lR,{onComplete:r,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),uR=__name(({onComplete:e,autoLearn:t=!1})=>{ae(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=UM({autoLearn:t,onShouldSkip:e}),{step:s,setStep:i}=qM({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=BM({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?re.createElement(zM,{error:r}):"done"===s?null:re.createElement(cR,{step:s,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");Bt(),Co(),Vr();var dR=[{label:"Dark theme",value:"dark",description:"Use purple accent colors on dark backgrounds."},{label:"Light theme",value:"light",description:"Use higher-contrast colors for white terminal backgrounds."}],mR=__name(({onSelect:e,onCancel:t})=>{const[n,r]=se(null);ae(()=>{r(getCliTheme())},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(Z((e,n)=>{n.escape&&t()}),null===n)return null;const s=dR.findIndex(e=>e.value===n);return re.createElement(Q,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Q,null,re.createElement(Y,{color:Er,bold:!0},"Select a theme")),re.createElement(Q,{marginBottom:1},re.createElement(Y,{color:br.DIM},"Choose the color palette for this terminal.")),re.createElement(ft,{items:dR,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>re.createElement(Y,{color:e?br.CYAN:br.GRAY,bold:e&&isLightTheme()},e?Re.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=dR.find(e=>e.label===t),o=r?.value===n,s=dR.findIndex(e=>e.label===t);return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,null,re.createElement(Y,{color:e?br.CYAN:o?br.GREEN:br.DIM,bold:e&&isLightTheme()},` ${s+1}. ${r?.label??t}`),o&&re.createElement(Y,{color:br.GREEN}," ",Re.tick)),re.createElement(Y,{color:br.DIM},` ${r?.description??""}`))}}),re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"Press "),re.createElement(Y,{color:br.DIM,bold:!0},"Esc"),re.createElement(Y,{color:br.DIM}," to cancel")))},"ThemeSelector");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const o=[];for(const e of n)if(o.unshift(e),r-=getEntryCharCount(e),r<=0)break;return o}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var pR=oe(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:i,tasteOnboardingEntryId:a,autoLearnTaste:l,showTasteSkipBanner:u,showZdrNotice:d,retryAttempt:m,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,showFileList:w,setShowFileList:S,showProviderSelector:E,showModelSelector:v,showEffortSelector:C,showMemorySelector:k,showMcpManager:T,showAgentsConfig:_,showRewindSelector:x,showLoginOverlay:A,showUsageOverlay:P,showAddDirModal:I,showCompactModeSelector:M,showConfigureModels:R,setShowConfigureModels:N,showThemeSelector:L,authComponentInfo:$,status:D,currentProvider:O,currentModel:F,showProviderNotification:j,shareInfo:U,showShareNotification:B,unshareNotificationMessage:q,updateStatus:z,updateFailedInfo:H,creditWarning:W,permissionMode:G,hintMessage:V,pendingExitKey:K,tasteLearningEnabled:J,interactionTokens:X,contextUsage:Z,historyManagerRef:ee,executionState:te,contextEngineRef:ne,onSubmit:oe,onCommand:se,onToggleAutoAccept:ie,onResetPendingExitKey:ae,onDoubleEscapeEmpty:ue,onTasteOnboardingComplete:de,permissionPanel:me,questionPanel:pe,designSuggestionPanel:ge,onRewindSelect:he,onRewindCancel:fe,onLoginComplete:ye,onLoginCancel:we,setShowProviderSelector:Se,setShowModelSelector:be,setShowEffortSelector:Ee,setShowMemorySelector:ve,setShowMcpManager:Ce,setShowAgentsConfig:ke,setShowAddDirModal:Te,setShowUsageOverlay:_e,handleProviderSelect:xe,handleProviderCancel:Ae,handleModelSelect:Pe,handleModelCancel:Ie,handleCompactModeSelect:Me,handleCompactModeCancel:Re,handleThemeSelect:Ne,handleThemeCancel:Le,handleAuthSuccess:$e,handleAuthCancel:De,showDesignGuide:Oe,setShowDesignGuide:Fe}){const je=le(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Ue=ce(()=>Fe(!1),[Fe]),Be=useTerminalWidth(),qe=le(()=>"off"===i?je:getBudgetedFeed(je,"limited"===i?15e3:5e4),[je,i]),ze=le(()=>"off"===i?0:Math.max(0,je.length-qe.length),[je.length,qe.length,i]),He=le(()=>0===ze?qe:qe.filter(e=>"user"!==e.role),[qe,ze]),We=ce(()=>ke(!1),[ke]),Ge=ce(()=>ve(!1),[ve]),Ve=ce(()=>Ce(!1),[Ce]),Ke=ce(()=>Te(!1),[Te]),Qe=ce(()=>be(!0),[be]),Ye=ce(()=>Ee(!1),[Ee]),Je=ce(()=>{hardResetForResize(),s(e=>e+1)},[s]),Xe=!("off"!==i||me||pe||ge||E||v||C||$||k||T||_||x||A||P||I||M||R||L||Oe||a);return re.createElement(Q,{flexDirection:"column",width:"100%"},re.createElement(SM,{staticKey:o,feed:He,showHeader:!0,expandedToolOutput:"off"!==i,currentModel:F,currentProvider:O,hiddenCount:ze}),a&&re.createElement(uR,{onComplete:de,autoLearn:l}),u&&re.createElement(TasteSkipMessage,null),d&&re.createElement(ZdrPausedMessage,null),t.map(e=>e.metadata?.isAgent?re.createElement(EM,{key:e.id,entry:e}):re.createElement(Q,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==i))),re.createElement(RetryMessage,{attempt:m}),ge,pe,me,"off"!==i&&re.createElement(Q,{flexDirection:"column",marginTop:1},re.createElement(Q,null,re.createElement(Y,{color:br.DIM},"─".repeat(Be))),re.createElement(Q,{paddingRight:1},re.createElement(Y,{backgroundColor:_r.BG,color:_r.FG,bold:!0},`${Lx}DETAILED TRANSCRIPT${Lx}`),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+o"),re.createElement(Y,{color:br.DIM}," to toggle"),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+e"),re.createElement(Y,{color:br.DIM}," ","to"," ","limited"===i?"show all":"collapse"),re.createElement(Y,{color:br.DIM}," · "),re.createElement(Y,{bold:!0},"esc"),re.createElement(Y,{color:br.DIM}," to exit"))),Xe&&re.createElement(mM,{queuedMessages:n,isProcessing:r,executionState:te,status:D,input:g,setInput:h,onSubmit:oe,showFileList:w,setShowFileList:S,fileSearchQuery:f,setFileSearchQuery:y,onCommand:se,outputTokens:X,contextUsage:Z,tasteLearning:J,shareInfo:U,showShareNotification:B,unshareNotificationMessage:q,updateStatus:z,updateFailedInfo:H,creditWarning:W,currentProvider:O,currentModel:F,showProviderInfo:j,permissionMode:G,onToggleAutoAccept:ie,hintMessage:V,historyManager:ee.current,pendingExitKey:K,onResetPendingExitKey:ae,onDoubleEscapeEmpty:ue,retryAttempt:m,onAltP:Qe,renderKey:o}),E&&re.createElement(Q,{marginY:1},re.createElement(PM,{onSelect:xe,onCancel:Ae,currentProvider:O})),v&&re.createElement(Q,{marginY:1},re.createElement(xM,{onSelect:Pe,onCancel:Ie,currentModel:F,currentProvider:O,refreshBanner:Je})),C&&re.createElement(Q,{marginY:1},re.createElement(AM,{currentModel:F,onClose:Ye,refreshBanner:Je})),Oe&&re.createElement(Q,{marginY:1},re.createElement(LM,{onCancel:Ue})),M&&re.createElement(Q,{marginY:1},re.createElement(RI,{onSelect:Me,onCancel:Re})),R&&re.createElement(Q,{marginY:1},re.createElement(DI,{onClose:()=>N(!1)})),L&&re.createElement(Q,{marginY:1},re.createElement(mR,{onSelect:Ne,onCancel:Le})),_&&re.createElement(Q,{marginY:1},re.createElement(II,{onCancel:We})),k&&re.createElement(Q,{marginY:1},re.createElement(hM,{onClose:Ge})),T&&re.createElement(Q,{marginY:1},re.createElement(gM,{onClose:Ve})),x&&ne.current&&re.createElement(Q,{marginY:1},re.createElement(MM,{checkpoints:ne.current.listCheckpoints(),onSelect:he,onCancel:fe})),$&&re.createElement(Q,{marginY:1},re.createElement($.Component,{onSuccess:$e,onCancel:De})),A&&re.createElement(Q,{marginY:1},re.createElement(pM,{onComplete:ye,onCancel:we})),I&&re.createElement(Q,{marginY:1},re.createElement(gI,{onClose:Ke})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:v,creditWarning:C,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:A,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return re.createElement(dP,{staticKey:o.staticKey,onTrust:k,onExit:T});if(o.showSessionSelector)return re.createElement(hP,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!s.projectTrusted)return null;const I=o.pendingDesignSuggestion?re.createElement(lP,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{f(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,M=a.pendingQuestion?re.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,R=a.pendingPermission?re.createElement(PP,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null,{closeFullScreenOverlay:N}=o;return o.showLearningFeed?re.createElement(GP,{onClose:()=>N(o.setShowLearningFeed),onExit:()=>i.setShouldExit(!0)}):o.showTasteConfig?re.createElement(TasteConfigView,{staticKey:o.staticKey,onClose:()=>N(o.setShowTasteConfig),loadTasteStatus:P}):o.showSkillsConfig?re.createElement(SkillsConfigView,{staticKey:o.staticKey,onClose:()=>N(o.setShowSkillsConfig)}):o.showUsageOverlay?re.createElement(UsageView,{staticKey:o.staticKey,onClose:()=>N(o.setShowUsageOverlay)}):o.showContextView?re.createElement(ContextConfigView,{staticKey:o.staticKey,contextEngineRef:u,onClose:()=>N(o.setShowContextView),setInput:w}):o.showStatusView?re.createElement(StatusConfigView,{staticKey:o.staticKey,onClose:()=>N(o.setShowStatusView),setInput:w}):re.createElement(pR,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:o.staticKey,setStaticKey:o.setStaticKey,transcriptMode:o.transcriptMode,tasteOnboardingEntryId:s.tasteOnboardingEntryId,autoLearnTaste:s.autoLearnTaste,showTasteSkipBanner:o.showTasteSkipBanner,showZdrNotice:o.showZdrNotice,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:o.showFileList,setShowFileList:o.setShowFileList,showProviderSelector:o.showProviderSelector,showModelSelector:o.showModelSelector,showEffortSelector:o.showEffortSelector,showMemorySelector:o.showMemorySelector,showMcpManager:o.showMcpManager,showAgentsConfig:o.showAgentsConfig,showRewindSelector:o.showRewindSelector,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,showConfigureModels:o.showConfigureModels,setShowConfigureModels:o.setShowConfigureModels,showThemeSelector:o.showThemeSelector,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:v,creditWarning:C,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:A,permissionPanel:R,questionPanel:M,designSuggestionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleThemeSelect:g.handleThemeSelect,handleThemeCancel:g.handleThemeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView");var gR=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u,sessionTitleHolder:d})=>{const{exit:m}=te(),{stdout:g}=X();ae(()=>{prefetchBillingContext()},[]);const[h,f]=se(""),[y,w]=se(""),S=ie(!1),E=ie(!1),v=ie(null),C=ie(null),k=useUiOverlays(),T=useFeed(),_=useSession(),x=useStatus(s),A=useAuth(),P=usePendingOps(),I=useOnboarding(),M=useExit(),{executeBash:R,executionState:N}=B_(),L=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:x.setStatus,contextEngineRef:C}),{createContextEngineCallbacks:$}=useContextEngine({sessionId:_.sessionId,sessionLoaded:_.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:I.projectTrusted,setFeed:T.setFeed,setLiveEntries:T.setLiveEntries,setQueuedMessages:T.setQueuedMessages,queuedMessagesRef:T.queuedMessagesRef,setStatus:x.setStatus,pinnedStatusRef:x.pinnedStatusRef,setRetryAttempt:x.setRetryAttempt,setInteractionTokens:x.setInteractionTokens,setContextUsage:x.setContextUsage,setCurrentProvider:A.setCurrentProvider,shareInfoRef:x.shareInfoRef,permissionsService:L.permissionsService,permissionModeRef:L.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:C}),{onCommand:D}=useCommandCtx({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,permissionState:L,contextEngineRef:C,isSubmittingRef:S,executeBash:R,createContextEngineCallbacks:$,setInput:f}),{loadTasteStatus:O,loadCurrentProvider:F,onSubmit:j}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:g,feedState:T,sessionState:_,statusState:x,authState:A,onboarding:I,uiOverlays:k,permissionState:L,contextEngineRef:C,isSubmittingRef:S,initialPromptSubmittedRef:E,historyManagerRef:v,executeBash:R,createContextEngineCallbacks:$,setInput:f,onCommand:D});useLifecycle({exit:m,feedState:T,exitState:M,statusState:x,authState:A,onboarding:I,uiOverlays:k,skipOnboarding:l,contextEngineRef:C,sessionTitleHolder:d});const{handleToggleAutoAccept:U,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,handleTrust:z,handleNoTrust:H}=useHandlers({resume:e,feedState:T,onboarding:I,uiOverlays:k,exitState:M,pendingOps:P,permissionState:L,statusState:x,authState:A,contextEngineRef:C,loadTasteStatus:O,loadCurrentProvider:F,setInput:__name(e=>f(e),"setInput")}),W=useMainActionCallbacks({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,permissionState:L,contextEngineRef:C,createContextEngineCallbacks:$,setInput:f}),{creditWarning:G}=useCreditWarning({interactionTokens:x.interactionTokens});return renderView({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,pendingOps:P,permissionState:L,contextEngineRef:C,historyManagerRef:v,executionState:N,actionCallbacks:W,onSubmit:j,onCommand:D,input:h,setInput:f,fileSearchQuery:y,setFileSearchQuery:w,updateFailedInfo:i,creditWarning:G,handleTrust:z,handleNoTrust:H,handleToggleAutoAccept:U,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,loadTasteStatus:O})},"InteractiveCLI");Qr(),uE(),ur(),Sv(),Vr(),Co();var hR=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),fR=ue.hex(br.DIM),yR=__name(()=>{const e=getInvokedCommandName();return"win32"===process.platform&&"cmd"===e?"cmdc":e},"getResumeCommandName"),wR=__name(e=>{const t=yR(),n=st([e]);return`${fR("Resume this session with:")}\n${fR(`${t} --resume ${n}`)}\n`},"formatResumeHint"),SR=__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"),bR=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),ER=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),vR=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{let r;return e.permissionMode?r=e.permissionMode:e.plan&&(r="plan"),{resume:"boolean"==typeof e.resume?e.resume:void 0,resumeSessionId:t,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:r,sessionTitleHolder:n}},"buildInteractiveCLIProps"),CR=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),kR=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),TR=__name(()=>{kR()},"initializeTerminal"),_R=__name(async(e={})=>{const t=SR(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),TR(),"string"==typeof e.resume){const t=e.resume.trim();if(await fv.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1)),await fv.sessionExists(t))n=t;else{const e=await fv.findSessionByName(t);e||(console.error(`No session named "${t}" found.`),process.exit(1)),n=e.id}}if(bR(e)&&!n){const e=await fv.isProjectInitialized(),t=e?await fv.listSessions():[],n=ER({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture(),applyTuiTheme(getCliTheme());const r={},o=vR({options:e,resumeSessionId:n,sessionTitleHolder:r}),s=CR(),i=ee(re.createElement(gR,{...o}),s);registerInkControl({clear:i.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await i.waitUntilExit();const a=r.sessionId;if(a&&await fv.sessionExists(a)){const e=await(r.loadTitle?.()),t=e?hR(e):"";process.stdout.write(wR(t||a))}},"interactiveMode");Xo(),Bt(),_n(),cC(),Kv();var xR=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${Re.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${Re.cross} Login failed: ${getErrorMessage2(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||xR()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated"),Co(),Bt(),_n(),bo();var AR={bold:__name((e,t)=>t?`${e}`:e,"bold"),dim:__name((e,t)=>t?`${e}`:e,"dim"),green:__name((e,t)=>t?`${e}`:e,"green")};function modelNameOf(e){const t=e.lastIndexOf("/");return(-1===t?e:e.slice(t+1)).toLowerCase()}function displayModelId(e){return e.replace(ao,"")}function resolveModelFlag({model:e}){const t=resolveKnownModelId(e);if(t)return t;const n=modelNameOf(e),r=getAllModelOptions().filter(e=>modelNameOf(e.id)===n);return 1===r.length?r[0].id:void 0}function editDistance(e,t){const n=e.length+1,r=t.length+1;let o=Array.from({length:r},(e,t)=>t);for(let s=1;s<n;s++){const n=[s];for(let i=1;i<r;i++){const r=e[s-1]===t[i-1]?0:1;n[i]=Math.min(o[i]+1,n[i-1]+1,o[i-1]+r)}o=n}return o[r-1]}function suggestModel(e){const t=e.trim().toLowerCase();if(!t)return;let n;for(const e of getAllModelOptions()){const r=displayModelId(e.id),o=Math.min(editDistance(t,r.toLowerCase()),editDistance(t,modelNameOf(r)));(!n||o<n.distance)&&(n={id:r,distance:o})}if(!n)return;const r=Math.min(4,Math.ceil(t.length/3));return n.distance<=r?n.id:void 0}function formatModelList(e={}){const t=e.color??!1,n=getModelGroupsInOrder(),r=n.flatMap(e=>e.models),o=Math.max(...r.map(e=>displayModelId(e.id).length)),s=n.map(e=>{const n=e.models.map(e=>{const n=displayModelId(e.id).padEnd(o),r=AR.dim(e.description,t);return`${n} ${"free"===e.badge?`${AR.green("FREE",t)} `:""}${r}${e.id===fn?` ${AR.green("(default)",t)}`:""}`});return[AR.bold(e.label,t),"",...n].join("\n")});return[`${AR.bold("Available models",t)} ${AR.dim(`· ${r.length} models`,t)}`,"",s.join("\n\n"),"",AR.dim('Pass the full id, or just the short name after the last "/":',t),"cmd --model moonshotai/Kimi-K2.5","cmd --model kimi-k2.5","","Docs: https://commandcode.ai/docs/reference/cli/models"].join("\n")}function printModelList(){const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`)}function resolveModelFlagOrExit({model:e}){const t=resolveModelFlag({model:e});if(t)return t;const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "cmd --list-models" to see all available models\n`),process.exit(1)}__name(modelNameOf,"modelNameOf"),__name(displayModelId,"displayModelId"),__name(resolveModelFlag,"resolveModelFlag"),__name(editDistance,"editDistance"),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit");var PR=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),IR=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),MR=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),e.plan&&(t.plan=!0),e.permissionMode&&(t.permissionMode=e.permissionMode),t},"buildRuntimeOptions"),RR=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>{const r=e.resume??e.sessions;return r?{resume:r,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n}},"getInteractiveConfig"),NR=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(t.listModels)return void printModelList();if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)addDirectory(e);const n=t.model?resolveModelFlagOrExit({model:t.model}):void 0;if(void 0!==t.print){const r=NR(t,e);return void await printMode({query:r,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:n,benchmarkOutput:t.benchmarkOutput,resume:t.resume,continue:t.continue})}n&&setModelOverride(n),setGoalMaxTurnsOverride(t.maxTurns);const r=PR(e);await IR();const o=MR(t),s=RR({options:t,runtimeOptions:o,initialPrompt:r});await _R(s)}__name(interactiveModeAction,"interactiveModeAction"),Bt(),ir(),Bs(),Co(),Gv(),cC();var LR=new Set(["update"]),$R=__name(()=>process.argv.slice(2).find(e=>!e.startsWith("-")),"getInvokedCommand");globalThis.COMMAND_CODE_CWD=process.cwd();var DR=__name(()=>process.cwd(),"getCwd"),OR=__name(()=>process.argv.slice(2),"getArgs"),FR=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),jR=__name(()=>{const e=DR(),t=OR(),n=FR(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){if(jR(),process.argv.includes("--ide-setup")){const e=await runIDESetup();formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}const e=LR.has($R()??"");e||(notifyCompletedUpdate(),maybeRunPendingUpdate()),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),e||checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100).unref()}__name(preRun,"preRun"),Bt(),_n(),ir(),Go(),uE(),Ro();var UR=getPackageJson(),BR=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=UR.version,t=getInvokedCommandName(),n=GT.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ue.bold("Command Code")+ue.gray(` v${e}`)),console.log(ue.gray(BT)),console.log(),console.log(ue.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ue.bold("Options"));for(const e of WT){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(qT)+ue.gray(e.description))}console.log(),console.log(ue.bold("Commands"));for(const e of VT){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(qT)+ue.gray(e.description))}console.log(),console.log(ue.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(qT)+ue.gray(e.description));console.log(),console.log(ue.bold("Keyboard Shortcuts"));for(const e of HT)console.log(" "+e.key.padEnd(qT)+ue.gray(e.description));console.log(),console.log(ue.bold("Examples"));for(const e of QT){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(qT)+ue.gray(e.description))}console.log(),console.log(ue.cyan("❯")+" "+ue.gray(YT.replace(/cmd/,t))),console.log(),console.log(ue.bold("Links"));for(const e of KT)console.log(" "+e.key.padEnd(qT)+ue.cyan(e.description));console.log()}function createProgram(){const e=new Ne;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(UR.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by id or name, or pick from history").option("--sessions [name]","Alias of --resume — resume a session by id or name, or pick from history").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").addOption(new Le("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Le("--yolo","Bypass all permission prompts (alias for --dangerously-skip-permissions)").implies({dangerouslySkipPermissions:!0})).option("--plan","Start in plan mode (read-only exploration and planning)").addOption(new Le("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Le("--permission-mode <mode>","Set permission mode").choices(["standard","plan","auto-accept"])).option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--max-turns <number>","Max agentic turns (model API round trips): print mode limit (default 10); interactive mode sets the /goal turn budget (default 100)",e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new $e("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--ide-setup",zT).option("--add-dir <directory>","Add directory to workspace context",BR,[]).option("-m, --model <model>","Run on a specific model this session (e.g. claude-sonnet-4-6, kimi-k2.5). Unknown ids are rejected; see --list-models.").option("--list-models","List the models available for use").addOption(new Le("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Le("--experimental","Enable experimental features").hideHelp()).addOption(new Le(zt).hideHelp()).addOption(new Le(Ht).hideHelp()).addOption(new Le("-d, --debug","Enable debug mode").hideHelp()).addOption(new Le("--local","Use local server").hideHelp()).addOption(new Le("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Bt(),Bs(),ls(),Tv(),kC(),Fv(),Go(),cC(),Bt(),__name(isTTY,"isTTY");var qR=!1;function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=w.platform(),t=w.arch();let n,r,o,s;try{const e=await getAuthenticatedEntity();e.success&&(n=e.user?.userName,r=e.user?.id,o=e.org?.login,s=e.org?.id)}catch{}if(!r)try{const e=await loadCredentials();r=e?.userId}catch{}systemInfo({userName:n,userId:r,orgLogin:o,orgId:s,platform:e,arch:t})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){qR||(qR=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=w.platform(),r=w.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=De("Opening GitHub issues...").start();try{await he(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),cC(),Bt(),Po(),__name(openGitHubIssue,"openGitHubIssue");var zR=new Ne("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Bt();var HR=new Ne("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const t=getSystemInfo(),{waitUntilExit:n}=ee(re.createElement(mA,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}Bt(),Bt(),__name(runInfo,"runInfo");var WR=new Ne("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=ee(re.createElement(lR,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}Bt(),_n(),Bt(),__name(runLearnTaste,"runLearnTaste"),ir(),Bs();var GR=new Ne(an.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:Ls.LEARN_TASTE_COMMAND,heading:"Learn taste render failed"}}),dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),await shutdownTelemetry(),process.exit(1)}});function addMcpCommand(){const e=new Ne("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new Le("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1)),"stdio"!==n.transport&&"http"!==n.transport&&(console.error(ue.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ue.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ue.red("Error: URL is required for http transport")),console.error(ue.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ue.red(`Error: Invalid URL '${t}'`)),process.exit(1)}s={transport:"http",enabled:!0,url:t,...Object.keys(n.header).length>0&&{headers:n.header},...Object.keys(n.env).length>0&&{env:n.env}},console.log(ue.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ue.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ue.cyan("Server requires OAuth authentication.")),isSecureOrLoopback(t)||(console.error(ue.red(`Error: Server '${e}' requires OAuth, but URL '${t}' is not secure.`)),console.error(ue.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ue.gray("Switch the URL to https:// or use a non-OAuth server.")),process.exit(1));let n,o="command-code";if(r.metadata.registrationEndpoint){console.log(ue.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${lE}/callback`]});e&&(o=e.clientId,n=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},console.log(ue.gray("A browser window will open for authentication.\n"));const a=await performOAuthFlow(e,t,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});a.success?console.log(ue.green("✓ Successfully authenticated")):(i=!0,console.log(ue.yellow(`Warning: Authentication failed: ${a.error}`)),console.log(ue.gray("You can retry with: cmd mcp auth "+e)),console.log(ue.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ue.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);looksLikeHttpUrl2(a)&&(console.error(ue.red(`Error: '${a}' looks like a URL, not a local command.`)),console.error(ue.gray(`Did you mean: cmd mcp add --transport http ${e} ${a}`)),process.exit(1)),s={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:s,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(ue.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===s.transport)console.log(ue.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function looksLikeHttpUrl2(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(ue.red(`Error: Invalid format '${e}', expected KEY=value`)),process.exit(1)),t[n]=r.join("="),t}function collectHeaders(e,t){const n=e.indexOf(":");-1===n&&(console.error(ue.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),o=e.substring(n+1).trim();return r||(console.error(ue.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new Ne("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ue.yellow("\nNo MCP servers configured\n")),console.log(ue.gray("Add a server with:")),console.log(ue.gray(" cmd mcp add --transport http <name> <url>")),console.log(ue.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ue.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ue.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ue.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ue.green("enabled"):ue.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ue.green(Re.tick):ue.red(Re.cross):o.config.headers||o.config.env?ue.green(Re.tick):ue.gray("-"),console.log(` ${ue.white(o.name.padEnd(t))} ${ue.cyan(o.config.transport.padEnd(n))} ${ue.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ue.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ne("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServer({name:e});t||(console.error(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ue.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ue.dim("Scope:")} ${r}`),console.log(` ${ue.dim("Transport:")} ${n.transport}`),console.log(` ${ue.dim("Status:")} ${n.enabled?ue.green("enabled"):ue.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ue.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ue.dim("Headers:")}`);for(const[e,t]of Object.entries(n.headers)){const n=e.toLowerCase().includes("auth")||e.toLowerCase().includes("token")||e.toLowerCase().includes("key")?"***":t;console.log(` ${e}: ${n}`)}}}else console.log(` ${ue.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ue.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ue.dim("Environment:")}`);for(const[e,t]of Object.entries(n.env)){const n=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token")||e.toLowerCase().includes("password")?"***":t;console.log(` ${e}=${n}`)}}console.log("")}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ne("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Le("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await getMcpServer({name:e});n||(console.error(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ue.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ue.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ue.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ne("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new Le("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("--client-secret <secret>","OAuth client secret (injected into oauth config)").action(async(e,t,n)=>{const r=getInvokedCommandName();try{let o,s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{o=JSON.parse(t)}catch{console.error(ue.red("Error: Invalid JSON")),console.error(ue.gray("Make sure to quote the JSON string properly")),console.error(ue.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}o?.oauth?.callbackPort&&(s=o.oauth.callbackPort,delete o.oauth.callbackPort),n.clientSecret&&o?.oauth&&(o.oauth.clientSecret=n.clientSecret);const i=Yb.safeParse(o);if(!i.success){console.error(ue.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ue.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ue.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ue.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ue.cyan("Starting OAuth authentication...")),console.log(ue.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,a.url??"",t,{...s&&{port:s},onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});n.success?console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ue.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ue.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ue.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(ue.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ue.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ne("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list){const e=await listServersWithTokens();if(0===e.length)return void console.log(ue.yellow("No servers with stored authentication."));console.log(ue.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ue.yellow("expired"):ue.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ue.red("Error: Server name is required")),console.error(ue.gray(`Usage: ${n} mcp auth <server>`)),console.error(ue.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ue.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ue.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ue.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ue.gray(" A refresh token is available for re-authentication"));else{if(console.log(ue.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ue.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ue.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ue.green(`✓ Cleared authentication for '${e}'`)):console.log(ue.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ue.red(`Error: MCP server '${e}' not found`)),console.error(ue.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),console.log(ue.cyan(`Authenticating with '${e}'...`)),console.log(ue.gray("A browser window will open for authentication.\n"));const o=__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus");let s;if(r.config.oauth){const t={authorizationUrl:r.config.oauth.authorizationUrl,tokenUrl:r.config.oauth.tokenUrl,clientId:r.config.oauth.clientId,clientSecret:r.config.oauth.clientSecret,scopes:r.config.oauth.scopes};s=await performOAuthFlow(e,r.config.url??"",t,{onStatus:o})}else"http"===r.config.transport&&r.config.url||(console.error(ue.red("Error: Discovery-based auth requires an http server with a url")),process.exit(1)),s=await discoverAndAuthenticate({serverName:e,serverUrl:r.config.url,onStatus:o});if(s.success)return console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ue.gray("Restart the session to connect with the authenticated server."));console.error(ue.red(`\nError: Authentication failed: ${s.error}`)),console.log(ue.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ne("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}async function runCommand(e){return new Promise((t,n)=>{const r=ve(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let o="",s="";r.stdout.on("data",e=>{o+=String(e)}),r.stderr.on("data",e=>{s+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${s?`: ${s.trim()}`:""}`)):t({stdout:o,stderr:s})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await C.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await C.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const o=parseGitHubSource({source:n});if(!o){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const s=String(t.maxCommits??200),i=`https://github.com/${o.owner}/${o.repo}.git`,a=await C.mkdtemp(e.join(w.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",s,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await C.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${o.owner}/${o.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${o.owner}/${o.repo}`,repoDir:a,repoName:o.repo,github:o,cleanup:__name(async()=>{await C.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),o=new hS({baseUrl:r}),s=new fx({request:o,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await s.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(ue.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let o=0;for(let s=0;shouldContinueExtraction({offset:s,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:o});s+=10){const i=t.slice(s,s+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;o++;const s=groupCrossFilePatterns(t);for(const t of s.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const o=[`Commit: ${e.subject}`];o.push(`File: ${t.file}`),t.context&&o.push(`In: ${t.context}`);const s=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(s&&o.push(s),r.push({text:`${truncate3(t.removed,60)} → ${truncate3(t.added,60)}`,evidence:o,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${o} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],o=e.branch?[e.branch]:[],s=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...o,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(s)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",o=""]=e.split("");return{hash:t.trim(),subject:o.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let o="",s="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:o,context:s||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),o=e.match(/b\/(.+)$/)?.[1]??"",s="",l=[],isNoiseFile(o)&&(o="");continue}if(e.startsWith("@@")){g(),m(),s=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!o)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Bt(),Bt(),uE(),__name(addMcpCommand,"addMcpCommand"),__name(looksLikeHttpUrl2,"looksLikeHttpUrl"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Bt(),__name(listMcpCommand,"listMcpCommand"),Bt(),__name(getMcpCommand,"getMcpCommand"),Bt(),__name(removeMcpCommand,"removeMcpCommand"),Bt(),uE(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Bt(),uE(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Bt(),_n(),Bt(),hC(),Bt(),_n(),Bt(),__name(runCommand,"runCommand"),Bt(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Bt(),LS(),VS(),Co(),No(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Bt(),Bt(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var VR=5,KR=3;function buildSnippet(e,t,n){const r=e??[],o=n??[],s=t.split("\n").map(e=>e.trimEnd());if(0===s.length&&0===r.length&&0===o.length)return;let i,a=0;s.length>KR?(i=s.slice(0,KR-1),a=s.length-i.length):i=s;const l=i.length+(a>0?1:0),u=Math.max(0,VR-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(o.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of o.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var QR=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return QR.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var YR=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),JR=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!YR.has(n)||!(!n.includes("[bot]")||!JR.some(e=>e.test(t)))}function truncate3(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let o=0;const s=__name(async()=>{for(;o<t.length;){const e=o++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>s())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:o}=e,s=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${s}Commits analyzed: ${o}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){FC.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await FC.waitForAuth()}catch{return FC.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),FC.markLearningComplete(),{summary:n()}}}t.isLocalSource||FC.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const o="github"===r.type,s=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=o?e.resolve(process.cwd(),s):i;o&&FC.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await C.mkdir(a,{recursive:!0}),FC.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{FC.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");FC.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),FC.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:s,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};FC.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return FC.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),FC.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate3,"truncate"),__name(runBounded,"runBounded"),Bt(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Bt(),Bt(),Bt();var XR=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return XR.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Bt(),Rs(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Bt(),Bt();var ZR=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],eN=[{id:"cloning",label:"Cloning repository"},...ZR],tN=[Re.bullet,Re.squareSmallFilled,Re.lozenge,Re.star,Re.triangleRight,Re.triangleUp];function createInitialRepoLearnSteps(e){return(e??ZR).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Bt();var nN={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var rN=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),oN=__name(e=>e??nN,"withBase");function useRepoLearnState(e){const t=e??ZR,[n,r]=se(()=>createInitialRepoLearnSteps(t)),[o,s]=se(""),[i,a]=se([]),[l,u]=se(null),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w,S]=se(0),E=ie(null),[v,C]=se(null),k=ce(()=>{E.current=Date.now()},[]);return ae(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),s(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,C(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(rN),void s("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),s(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=oN(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=oN(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):s(e.message):u(t=>{const n=oN(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),o=__name(()=>{h(e=>e||(r(rN),!0)),s(""),E.current&&C(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return FC.on("reset",e),FC.on("new-event",n),FC.on("learning-complete",o),()=>{FC.off("reset",e),FC.off("new-event",n),FC.off("learning-complete",o)}},[t]),{steps:n,currentMessage:o,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:v,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Bt(),Bt(),Vr();var sN=__name(({isComplete:e,hasError:t})=>re.createElement(Q,{flexDirection:"column",marginTop:1,marginBottom:0},re.createElement(VM,null),re.createElement(Q,{marginTop:0},re.createElement(Y,{color:br.DIM},QM),re.createElement(Q,{marginLeft:2},t?re.createElement(Y,{color:br.DIM},"learning interrupted"):e?re.createElement(Y,{color:vr.TEXT},"learned your coding taste"):re.createElement(YM,null)))),"RepoLearnTastePill");Bt(),Vr();var iN=__name(({status:e})=>"active"===e?re.createElement(Q,null,re.createElement(Y,{color:br.YELLOW},re.createElement(We,{type:"dots"})),re.createElement(Y,null," ")):"complete"===e?re.createElement(Y,{color:_r.BG},Re.square," "):re.createElement(Y,{color:br.DIM},Re.circle," "),"StepStatusIndicator"),aN=__name(({steps:e,currentMessage:t})=>re.createElement(Q,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return re.createElement(Q,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},re.createElement(Q,null,re.createElement(Q,{marginRight:1},re.createElement(iN,{status:e.status})),re.createElement(Y,{bold:n,color:"complete"===e.status?br.WHITE:n?br.YELLOW:br.DIM},e.label)),n&&t?re.createElement(Q,{marginLeft:3},re.createElement(Y,{color:br.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Bt(),Vr();var lN=__name(({insights:e,insightCount:t})=>0===e.length?null:re.createElement(Q,{flexDirection:"column",marginTop:1,marginLeft:4},re.createElement(Y,{color:br.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>re.createElement(Y,{key:`${t}-${e}`,color:br.DIM},tN[t%tN.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Bt(),Vr();var cN=__name(({message:e})=>re.createElement(Q,{flexDirection:"column",borderStyle:"single",borderColor:br.RED,paddingX:2,paddingY:1,marginTop:1},re.createElement(Y,{color:br.RED,bold:!0},"Oops, something went wrong:"),re.createElement(Q,{marginTop:1},re.createElement(Y,null,e))),"RepoLearnErrorPanel");Bt(),Vr(),ko();var uN=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return re.createElement(Q,{flexDirection:"column",marginLeft:3},re.createElement(Q,{marginBottom:1,flexDirection:"row"},re.createElement(Y,{color:br.DIM},QM),re.createElement(Q,{marginLeft:2},re.createElement(Y,{color:vr.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),re.createElement(Q,{flexDirection:"column",marginLeft:1},re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," Taste stored in"," "),re.createElement(Eo,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:br.CYAN})),re.createElement(Q,null,re.createElement(Y,{color:br.DIM},Re.pointerSmall," Share your coding taste:"," ",re.createElement(Y,{color:br.CYAN},"npx taste push --all")))),re.createElement(Q,{marginTop:1,marginLeft:1},re.createElement(Y,{color:br.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Bt(),Vr();var dN=__name(({done:e,error:t})=>t?re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0},"Press ESC to exit")):e?re.createElement(Q,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue")):re.createElement(Q,{marginTop:1},re.createElement(Y,{color:br.DIM},"ESC to cancel")),"RepoLearnFooter");Bt(),Vr();var mN=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=le(()=>DP(n),[n]);return re.createElement(Q,{flexDirection:"column"},re.createElement(Q,{flexDirection:"column",marginBottom:1},re.createElement(qP,null,r.trimEnd())),e?re.createElement(Y,{color:br.WHITE},e):re.createElement(re.Fragment,null,re.createElement(Y,{color:br.WHITE},"Learning your coding taste from"," ",re.createElement(Y,{bold:!0,color:br.CYAN},t??"repository")),re.createElement(Y,{color:br.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?re.createElement(cN,{message:e}):t?re.createElement(uN,{summary:n,elapsedSeconds:r}):re.createElement(lN,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=ie(!1);return ae(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),Z((e,n)=>{if(s.showLogin)return;const r=n.escape||""===e,o=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(s.done||s.error)&&o&&t({published:!1,cancelled:!!s.error})}),s.showLogin?re.createElement(Q,{flexDirection:"column"},re.createElement(mN,{text:r,repoName:o}),re.createElement(pM,{onComplete:(e,t)=>{s.setShowLogin(!1),e?FC.resolveAuth():FC.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),FC.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):re.createElement(Q,{flexDirection:"column"},re.createElement(mN,{text:r,repoName:o}),re.createElement(sN,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),re.createElement(aN,{steps:s.steps,currentMessage:s.currentMessage}),re.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),re.createElement(dN,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{FC.reset();const r=new AbortController;let o,s,i=!1,a=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,FC.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),FC.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),FC.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=ee(re.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{FC.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),cC();var pN=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new Ne("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",pN("--max-commits"),200).addOption(new Le("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(pN("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await C.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),o=await resolveDisplayName(t.source),s=!await getAuthKey();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:o}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:s,signal:e});return i=o?.cleanup,r},"runTask");if(r){const t=n?void 0:[...eN];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:o,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),uC(),await _R({skipOnboarding:!0})}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(w.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Bt(),Bt(),Bt(),_n(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Bt(),Bt();var gN=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||gN.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:gN.test(o)&&!o.startsWith("#")&&!o.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:o}=findLookaheadEnd(e,t),s=o?r+1:r;return{combined:[n,...e.slice(t,s).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:s}}function processRawLine(e,t){const n=e[t],r=t+1,o=n.trim();if(!o.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(gN.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:o}=processRawLine(e,n);t.push(r),n=o}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!gN.test(o))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),i=s.length>0?s[s.length-1]:null;if(!i)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?o.substring(0,i.index).trim():o.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r)}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),o=r.findIndex(e=>e.trim().startsWith("# "));return(-1===o?r:r.slice(0,o)).some(e=>e.includes("See [")&&e.includes("taste.md"))}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),o=t.filter(e=>"warning"===e.severity),s=0===r.length;if(0===t.length)return{valid:s,issues:[...t],summary:`${Re.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&i.push(`${o.length} warning${o.length>1?"s":""}`);const a=r.length>0?Re.cross:Re.warning;return{valid:s,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ue.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ue.dim(` → ${e.suggestion}`)),n}function formatIssueGroup(e,t,n){return 0===e.length?[]:[n,...e.flatMap(e=>formatSingleIssue(e,t)),""]}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${ue.green(e)} ${ue.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?ue.red(t.summary):ue.yellow(t.summary),"",...formatIssueGroup(r,ue.red,ue.bold(ue.red("Errors:"))),...formatIssueGroup(o,ue.yellow,ue.bold(ue.yellow("Warnings:")))].join("\n").trim()}__name(findLookaheadEnd,"findLookaheadEnd"),__name(joinMultiLineLearning,"joinMultiLineLearning"),__name(processRawLine,"processRawLine"),__name(preprocessLines,"preprocessLines"),__name(validateLearningLine,"validateLearningLine"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(buildResult,"buildResult"),Bt(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var hN=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:o}=e;hN.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,o),r.currentCategory=t.trim().substring(2).trim(),r.categoryLineNumber=n,r.learningsInCurrentCategory=0)}function processLearning(e){const{line:t,lineNum:n,state:r}=e;r.currentCategory?(r.learningsInCurrentCategory++,r.issues.push(...validateLearningLine({line:t.trim(),lineNum:n}))):r.issues.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'})}__name(warnIfEmptyCategory,"warnIfEmptyCategory"),__name(processHeading,"processHeading"),__name(processLearning,"processLearning");var fN=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,yN=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:o}=e,s=t.trim();s&&(s.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:o}):s.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):fN.test(s)||yN.test(s)||r.issues.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"}))}function checkFinalCategory(e){const{state:t,rawLines:n}=e;!t.currentCategory||t.learningsInCurrentCategory>0||!t.categoryLineNumber||hasReferenceAfterCategory({lines:n,categoryLineIndex:t.categoryLineNumber-1})||t.issues.push({line:t.categoryLineNumber,severity:"warning",message:`Category '${t.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const o=t.split("\n"),s=preprocessLines(o),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:i,rawLines:o});return checkFinalCategory({state:i,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var wN=__name(e=>"local-global"===e?"global":"project","locationLabel"),SN=__name(({file:e,error:t})=>({success:!1,filesLinted:[],errors:[{file:e,error:t}],totalErrors:0,totalWarnings:0}),"failResult");function resolvePackageFile(e,t){const n=getCategoryTasteFile({target:t,category:e});return O(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${wN(t)}`}}}function collectSpecificFiles(e){const{packages:t,target:n}=e,r=t.map(e=>resolvePackageFile(e,n));return{files:r.filter(e=>"result"in e).map(e=>e.result),errors:r.filter(e=>"error"in e).map(e=>e.error)}}async function collectAllFiles(e){const{tastePath:t,target:n}=e,r=[],o=getRootTasteFile({target:n});O(o)&&r.push({path:o,displayName:"taste.md"});const s=(await C.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>O(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...s),r}async function lintFile(e){let t=await C.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await C.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),o=r.issues.filter(e=>"error"===e.severity).length,s=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:o}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&o.length>0)return{success:!1,filesLinted:[],errors:o,totalErrors:0,totalWarnings:0};if(0===r.length)return SN({file:"all",error:`No taste files found in ${wN(n)}`});const s=await Promise.all(r.map(lintFile)),i=s.reduce((e,t)=>e+t.errors,0),a=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return SN({file:"all",error:`No taste files found in ${wN(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),i=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return O(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):SN({file:"all",error:`No taste directory found in ${wN(n)}`})}function resolveConflictStrategy(e){const t=[e.skip&&"skip",e.merge&&"merge",e.overwrite&&"overwrite"].filter(Boolean);return t.length>1&&exitWithError(`Cannot combine --${t[0]} and --${t[1]}. Choose one conflict strategy.`),t[0]}__name(resolvePackageFile,"resolvePackageFile"),__name(collectSpecificFiles,"collectSpecificFiles"),__name(collectAllFiles,"collectAllFiles"),__name(lintFile,"lintFile"),__name(lintSpecificPackages,"lintSpecificPackages"),__name(lintAllFiles,"lintAllFiles"),__name(lint,"lint"),Bt(),Bs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var bN=ue.bgGreen.black.bold(" TASTE ");function shortenPath(e){const t=process.env.HOME??process.env.USERPROFILE??"";return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function exitWithError(e){console.error(`${ue.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`),process.exit(1)}function formatUsageLine(e){const t=e.match(/^(\s*(?:Usage:|or:)?\s*)(cmd)(\s+.+?)(\s+\(.*\))?$/);return t?`${ue.dim(t[1])}${ue.green(t[2])}${ue.white(t[3]??"")}${t[4]?ue.dim(t[4]):""}`:ue.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ue.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function resolveRemoteDefault(e){return e.global||e.remote?e:{...e,remote:!0}}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(resolveRemoteDefault,"resolveRemoteDefault");var EN=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return Ct(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:EN})}function getProfileLink(e){return Ct(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:EN})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return vt(e,n,{trim:!1})}function formatMergeParts(e){const t=[];return e.added>0&&t.push(`${e.added} ${1===e.added?"learning":"learnings"} added`),e.updated>0&&t.push(`${e.updated} ${1===e.updated?"learning":"learnings"} updated`),e.unchanged>0&&t.push(`${e.unchanged} ${1===e.unchanged?"learning":"learnings"} unchanged`),t}function hasMergeConflictRisk(e){return(e.added>0||e.updated>0)&&e.unchanged>0}function hasMergeConflictRiskInRecord(e){return Object.values(e).some(hasMergeConflictRisk)}function logMergeReviewTip(){console.log(ue.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function parseOwnerPackage(e){if(!e.includes("/"))return;const[t,n]=e.split("/");return t&&n?{owner:t,packageName:n}:void 0}function handleResultErrors(e){for(const t of e){const e=t.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${t.pkg}' `);console.error(`${ue.red("Error:")} ${e}`)}process.exit(1)}function getTimeAgo(e){const t=Date.now()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),o=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${o} day${o>1?"s":""} ago`}async function flushAndExit(e){await Promise.race([shutdownTelemetry(),new Promise(e=>setTimeout(e,500))]).catch(()=>{}),process.exit(e)}function withErrorHandler(e){return async(...t)=>{try{await e(...t),await flushAndExit(0)}catch(e){const t=e instanceof Error?e.message:String(e);console.error(ue.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ne("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${ue.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){e||t.all||exitWithUsage({message:"Specify a taste package name or use --all to validate everything",usage:["cmd taste lint <package> validate a taste package","cmd taste lint --all validate all taste packages"]}),e&&t.all&&exitWithError("Use either a package name or --all, not both")}function logLintResults(e){for(const t of e.filesLinted)console.log(t.formatted);e.filesLinted.length>1&&logLintSummary(e),e.success||process.exit(1)}function logLintSummary({filesLinted:e,totalErrors:t,totalWarnings:n}){if(console.log(""),0===t&&0===n)return void console.log(`${ue.green(Re.tick)} All ${ue.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ue.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ue.yellow(`${n} warning${n>1?"s":""}`)),console.log(`Summary: ${r.join(", ")} across ${e.length} files`)}async function runLint({packageName:e,options:t}){console.log(""),validateLintOptions({packageName:e,options:t});const n=await lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(ue.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),o=r[0].trim(),s=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===s.length?null:{category:normalizeCategory({category:o}),learnings:s,sourcePath:n}}function parsePackages(e){const{content:t,sourcePath:n}=e;return t.split(/^# /gm).filter(e=>e.trim()).filter(e=>!e.includes("See [")).map(e=>parseSection({section:e,sourcePath:n})).filter(e=>null!==e)}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatPackage(e){const{pkg:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}async function readAndMigrateFile(e){const{filePath:t}=e,n=await C.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await C.writeFile(t,r,"utf-8"),r)}function trimTrailingBlanks(e){const{lines:t,until:n}=e;let r=e.from;for(;r>n&&""===t[r].trim();)r--;return r}function findCategoryRange(e){const{lines:t,pattern:n}=e,r=t.findIndex(e=>n.test(e));if(-1===r)return null;const o=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===o)return{start:r,end:t.length-1};const s=trimTrailingBlanks({lines:t,from:o-1,until:r});return{start:r,end:s}}function ensureHeader(e){if(!e)return BC+"\n\n";const t=e.trim();return t.startsWith(jC)||t.startsWith(qC)||t.startsWith(zC)?e:BC+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Bt(),ri(),Bt(),Bt(),Bt(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Bt(),__name(formatPackage,"formatPackage"),Bt(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var vN="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:vN,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await C.stat(e.sourcePath);return{category:e.category,learningCount:e.learnings.length,lastUpdated:t.mtime,filePath:e.sourcePath}}catch{return{category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}}}async function getAllPackages(){const e=getTastePath({target:vN});if(!O(e))return[];const t=await C.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:vN,category:t});return O(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:vN});await C.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:vN,category:n.category}),s=e.dirname(o);await C.mkdir(s,{recursive:!0});const i=formatPackage({pkg:n});await C.writeFile(o,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Bt(),Bt();var CN="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!O(n))return null;const r=migrateHeader({content:await C.readFile(n,"utf-8")}).split("\n"),o=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!o)return null;const s=r.slice(0,o.start),i=o.end<r.length-1?r.slice(o.end+1):[],a={before:s.join("\n").trim(),after:i.join("\n").trim()},l=[...s,...i].join("\n").trim();return""===l&&await C.rm(n,{force:!0}),""!==l&&await C.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:CN}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:CN,category:n}),i=e.dirname(s);return O(i)&&await C.rm(i,{recursive:!0,force:!0}),o}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,o=formatPackage({pkg:t});if(r){let e=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=o.trim()+t,void await C.writeFile(n,e.trim()+"\n","utf-8")}let s="";O(n)&&(s=await C.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await C.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:CN,category:n.category}),i=e.dirname(s);await C.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await C.writeFile(s,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=ensureHeader(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=l.trim()+t,void await C.writeFile(r,e.trim()+"\n","utf-8")}let u="";O(r)&&(u=await C.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await C.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var kN="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:kN,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:kN});if(!O(e))return[];const t=[],n=getRootTasteFile({target:kN});if(O(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await C.readdir(e,{withFileTypes:!0}),o=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...o),t}async function getPackage2(e){const{category:t}=e;return(await getAllPackages2()).find(e=>e.category===t)||null}async function writePackage2(e){const{pkg:t}=e,n=getTastePath({target:kN});await C.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:kN}),o=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:o}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:o})}function exists2(){const e=getTastePath({target:kN});return O(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!O(n))return;const r=await C.readFile(n,"utf-8"),o=new Blob([r],{type:"text/markdown"}),s=new File([o],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,s)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:o,type:s="category",isPublic:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),o&&l.append("description",o),l.append("type",s),l.append("isPublic",String(i)),l.append("overwrite",String(a));const u=formatPackage({pkg:r}),d=new Blob([u],{type:"text/markdown"}),m=new File([d],"taste.md",{type:"text/markdown"});if(l.append("files[taste.md]",m),"category"===s)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!O(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!O(f))return l;const y=await C.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1,overwrite:s=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(o)),i.append("overwrite",String(s));const a=getRootTasteFile({target:"local-project"});if(O(a)){const e=await C.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}const l=t.map(e=>appendCategoryFile(i,e));return await Promise.all(l),i}function parseLearningLine(e){const t=e.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(!t)return null;const n=t[1].trim(),r=parseFloat(t[2]);return!n||isNaN(r)?null:{text:n,confidence:r}}function parseTasteContent(e){return e.split("\n").filter(e=>{const t=e.trim();return t&&!t.startsWith("#")&&t.startsWith("-")}).map(e=>parseLearningLine(e.trim())).filter(e=>null!==e)}async function parseApiError(e){const{response:t,fallback:n}=e;try{const e=await t.json();return e.error?.message||e.message||n}catch{return n}}function throwTrackedError(e){const{message:t,label:n,heading:r,status:o,extra:s}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:Ls.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),o=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(o)return o;const s=await getAuthKey();if(!s)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");return tryAuthenticatedDownload({baseUrl:r,owner:t,packageName:n,apiKey:s})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,o=`${t}${Gt.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let s;try{s=await fetch(o,{method:"GET"})}catch{return null}if(s.ok){const{data:e}=await s.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===s.status)return null;throwTrackedError({message:await parseApiError({response:s,fallback:`Failed to download taste package (${s.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:s.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:o}=e,s=`${t}${Gt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:Ls.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${n.message}`),null}}async function getAllPackages3(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list taste packages",status:n.status});const{data:r}=await n.json(),o=r.packages||[];if(0===o.length)return[];const s=[];for(let e=0;e<o.length;e+=5){const t=o.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));s.push(...n.filter(e=>null!==e))}return s}async function getPackage3(e){const{category:t}=e;let n;await requireAuthKey();try{n=await getAuthenticatedEntity()}catch(e){const n=e instanceof Error?e:new Error(String(e));throw dlog(`[Auth] getPackage: entity endpoint unavailable — ${n.message}`),trackError({error:sanitizeErrorForTelemetry({error:n,label:"get_entity_error"}),context:{component:Ls.TASTE_REMOTE_STORAGE,heading:"getAuthenticatedEntity failed in getPackage"}}),new Error(`Could not resolve your account to fetch '${t}'. Check your connection and try again.`)}if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");return downloadRemotePackage({owner:n.user.userName,packageName:t})}async function downloadRemotePackage(e){const{owner:t,packageName:n}=e,r=await downloadPackage({owner:t,packageName:n});if(!r)return null;const o=r.files||[];if(0===o.length)return null;const s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1,overwrite:o=!1}=e,s=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:o}),a=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${s}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:l.status}),await l.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:o=!1,overwrite:s=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o,overwrite:s}),l=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:a});u.ok||throwTrackedError({message:await parseApiError({response:u,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:u.status,extra:{"package.count":t.length}}),await u.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${Gt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list packages",status:n.status});const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}async function list(e){const{location:t}=e;if("local-global"===t)return listPackages();if("remote-project"===t||"remote-user"===t)return listPackages2();if("local-project"===t){const e=getRootTasteFile({target:"local-project"}),t=await getAllPackages2();return Promise.all(t.map(async t=>{let n;if(t.sourcePath!==e)try{n=(await C.stat(t.sourcePath)).mtime}catch{}return{category:t.category,learningCount:t.learnings.length,lastUpdated:n,filePath:t.sourcePath}}))}throw new Error(`Invalid location: ${t}`)}function createListCommand(){return new Ne("list").alias("ls").option("-g, --global","List global packages").addOption(new Le("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Le("--staging","Use staging environment").hideHelp()).description(`List available packages ${ue.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Bt(),VS(),Bt(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),_n(),Bt(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),kC(),Bs(),Bt(),cC(),Bs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Bt(),VS(),cC(),_n(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),ir(),__name(fetchSinglePackage,"fetchSinglePackage"),__name(getAllPackages3,"getAllPackages"),__name(getPackage3,"getPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage3,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages2,"listPackages"),__name(list,"list"),__name(createListCommand,"createListCommand");var TN={remote:{location:"remote-project",name:"remote",subtitle:"commandcode.ai account"},global:{location:"local-global",name:"global",subtitle:"~/.commandcode/taste"},project:{location:"local-project",name:"project",subtitle:".commandcode/taste"}};function resolveStorage(e){return e.remote?TN.remote:e.global?TN.global:TN.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Re.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Re.arrowDown}${e.downloadCount}`.length),t}function formatPackageLine({pkg:e,maxLen:t}){const n=" ".repeat(t-getPackageDisplayLength(e)+2),r=e.lastUpdated?getTimeAgo(e.lastUpdated):null,o=r?`, updated ${r}`:"";return` ${ue.white(e.category)}${e.isPublic?ue.green(" [public]"):""}${e.isPublic&&e.starCount?ue.yellow(` ${Re.star}${e.starCount}`):""}${e.downloadCount?ue.gray(` ${Re.arrowDown}${e.downloadCount}`):""}${n}${ue.dim.gray(`(${e.learningCount} learnings${o})`)}`}function validateListOptions(e){e.global&&e.remote&&exitWithError("Error: Cannot specify both --global and --remote flags")}async function fetchPackages({options:e}){const t=resolveStorage(e),n=e.remote?De(`Fetching ${t.name} packages`).start():null,r=await list({location:t.location});return n?.stop(),{packages:r,storage:t}}async function getStorageLabel({options:e,fallback:t}){if(!e.remote)return t;const n=await getUserName();return n?getProfileLink(n):t}function printPackageTable({packages:e,subtitle:t}){console.log(`\n${bN} Packages`),console.log(`${ue.gray("⎿")} ${ue.dim(t)}\n`);const n=Math.max(...e.map(getPackageDisplayLength));let r=0;for(const t of e)r+=t.learningCount,console.log(formatPackageLine({pkg:t,maxLen:n}));console.log(ue.dim(`\nTotal: ${e.length} packages, ${r} learnings\n`))}async function runList({options:e}){console.log(""),validateListOptions(e);const{packages:t,storage:n}=await fetchPackages({options:e});0!==t.length?printPackageTable({packages:t,subtitle:await getStorageLabel({options:e,fallback:n.subtitle})}):console.log(ue.yellow(`No taste packages found in ${n.name}`))}async function fetchAllPackages(e){const{target:t}=e;return"local-project"===t?getAllPackages2():"local-global"===t?getAllPackages():getAllPackages3()}function handleOpenError(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}async function readCategoryLineNumber(t){const{filePath:n,category:r}=t,o=await C.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const s=o.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return s>=0?s+1:1}async function findCategoryLineNumber(e){try{return await readCategoryLineNumber(e)}catch{return 1}}async function openPackage(e){const{packageName:t,target:n}=e,r=(await fetchAllPackages({target:n})).find(e=>e.category===t);if(!r){let e="project";return"local-global"===n&&(e="global"),"remote-project"!==n&&"remote-user"!==n||(e="remote"),{success:!1,error:`Taste package '${t}' not found in ${e}`}}const o=r.sourcePath,s=await findCategoryLineNumber({filePath:o,category:t});return await Et([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Bt(),Bt(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var _N=new Set(["local-project","local-global","remote-project","remote-user"]);async function open11(e){const{package:t,target:n}=e;if(!_N.has(n))return{success:!1,error:`Invalid target: ${n}`};try{return await openPackage({packageName:t,target:n})}catch(e){return handleOpenError(e)}}function getEditorSetupInstructions(){const e=kt.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}function createOpenCommand(){return new Ne("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${ue.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){e||exitWithUsage({message:"Specify a taste package name to open",usage:["cmd taste open <package> open taste package in editor","cmd taste open <package> -g open global taste package in editor","cmd taste open owner/package open package page in browser"]})}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor3({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await he(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ue.green(Re.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open11({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ue.green(Re.tick)} Opened ${ue.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open11,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Bt(),Bt(),Bt(),Bt();var xN=null,AN=!1;function setActiveSpinner(e){xN=e}function stopActiveSpinner(e){xN&&(xN.stop(e),xN=null)}function setPrompted(e){AN=e}function wasPrompted(){return AN}function beginPrompt(e,t){stopActiveSpinner(),Ge.intro(ue.dim(e)),t&&Ge.log.message(ue.dim(t)),setPrompted(!0)}function handleCancel(e){Ge.isCancel(e)&&(Ge.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Ge.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Ge.spinner();r.start(t),setActiveSpinner({stop:__name(e=>r.stop(e??n),"stop"),cancel:__name(e=>r.cancel(e),"cancel"),error:__name(e=>r.error(e),"error")})}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:o}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from ${n}`,s),Ge.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ue.dim(`(from ${n})`)}`);const i=await Ge.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${o} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(i);const a=i;return startStrategySpinner(a),a}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,o="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ue.green(`'${t}'`)} to global`,o),Ge.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await Ge.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});handleCancel(s);const i=s;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from global`,o),Ge.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await Ge.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});handleCancel(s);const i=s;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),Ge.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),Ge.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await Ge.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),Ge.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),Ge.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),Ge.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await Ge.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${o} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const o=t.get(e.text);return o?e.confidence>o.confidence?(n.set(e.text,e),void r.updated++):void r.unchanged++:(n.set(e.text,e),void r.added++)}function mergePackages(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},o=new Map(n.map(e=>[e.text,e])),s=new Map(o);for(const e of t)mergeSingleLearning(e,o,s,r);const i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{merged:Array.from(s.values()),details:r}}function validateSinglePackage(e,t){const n=validateTasteFile({content:formatPackage({pkg:e}),filePath:`${e.category}/taste.md`});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:e.category,error:`Validation failed for taste package in ${t}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${e.category}' in ${t} has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validateSingleRemoteFile(e,t){const n=validateTasteFile({content:e.content,filePath:e.file});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:t,error:`Validation failed for ${e.file}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validatePackages(e){const{packages:t,label:n}=e;return t.map(e=>validateSinglePackage(e,n)).filter(e=>null!==e)}function validateRemoteFiles(e){const{files:t,packageName:n}=e;return t.map(e=>validateSingleRemoteFile(e,n)).filter(e=>null!==e)}function mergeOrKeep(e){const{source:t,existing:n}=e;if(!n)return{pkg:t,details:{added:t.learnings.length,updated:0,unchanged:0}};const r=mergePackages({source:t.learnings,target:n.learnings});return{pkg:{...t,learnings:r.merged},details:r.details}}async function resolveRemotePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,tastePkg:o,owner:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:o.category,owner:s,localPkg:r,remoteLearningsCount:o.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void s.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:o,flagStrategy:s,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:o,flagStrategy:s,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:o,flagStrategy:s,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Bt(),Bt(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Bt(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var PN=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),IN=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),MN=__name(e=>"local-global"===e?"global":"remote-project"===e?"remote project":"remote-user"===e?"remote":"source","sourceName");async function resolvePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,source:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPullStrategy({packageName:s.category,localPkg:r,globalLearningsCount:s.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void s.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return PN({pkg:"all",error:`Invalid source: ${n}`});const s=MN(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return PN({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return PN({pkg:"all",error:`No taste packages found in ${s}`});const a=validatePackages({packages:i,label:s});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=IN();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return PN({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:o,result:s};return"project"===a?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=IN();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return PN({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,i=wasPrompted()?"":`${Re.tick} `,a=r?ue.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ue.green(i)}Replaced ${ue.green(`'${t}'`)} taste package in project`+a;if(s){const e=formatMergeParts(s);return`${ue.green(i)}Pulled ${ue.green(`'${t}'`)} taste package from ${n} ${ue.gray(`(${e.join(", ")})`)}`+a}return`${ue.green(i)}Pulled ${ue.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const o=t.packagesPulled[0],s=t.filePaths?.[o],i=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+o.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return s.length>0&&l.push(wrapLine(`${ue.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ue.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${ue.dim("Skipped")} (${o.length}) ${ue.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Ge.log.message(l.join("\n")),Ge.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ue.green(Re.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ue.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ne("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new Le("--local","Use local server").hideHelp()).option("--remote","Pull taste package from commandcode.ai remote").option("--all","Pull all taste packages from global").option("--overwrite","Replace local package without prompting").option("--skip","Keep local package, skip conflicting pull").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Le("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ue.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:o}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?o??"remote":"global",options:n})}))}function validatePullOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one source"),n.remote&&n.all&&exitWithUsage({message:"--all is not supported for remote pull — specify a package instead",usage:["cmd taste pull <owner>/<package> pull a taste package from remote"]}),n.remote&&!t&&exitWithUsage({message:"Specify a taste package to pull from remote",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),n.remote&&t&&!t.includes("/")&&exitWithUsage({message:`Remote pull requires owner/package format — got '${t}'`,usage:["cmd taste pull <owner>/<package> e.g. cmd taste pull ahmadawais/code-style"]}),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to pull everything",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePullOptions({packageName:t,options:r});const o=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:o}):pullGlobal({packageName:t,options:r,strategy:o})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,o=parseOwnerPackage(t);o||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(De("Pulling taste package").start());const s=await pullRemote({owner:o.owner,packageName:o.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s,owner:o.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(De("Pulling taste package").start());const o=n.all||!t?[]:[t],s=await pull({packages:o,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new hS({baseUrl:e}),n=await t.get({endpoint:Gt.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}function logResult2(e){if(wasPrompted())return Ge.outro(e),void setPrompted(!1);console.log(e)}function logPushAllSuccess(t){const{result:n,options:r}=t;if(!r.all)return!1;if(0===n.packagesPushed.length){const e=n.skipped?.length??0;if(e>0){const t=wasPrompted()?"":`${Re.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ue.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${Re.tick} `;if(!a)return logResult2(`${ue.green(l)}Pushed ${s} to remote`),!1;if(r.overwrite||Boolean(n.overwritten?.length)){let e=0;if(n.mergeDetails)for(const t of Object.values(n.mergeDetails))e+=t.updated??0;const t=e>0?` ${ue.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ue.green(l)}Replaced ${s} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ue.green(l)}Pushed ${s} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${ue.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${ue.green(l)}Pushed ${s} to ${a}${h}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],o=t.filePaths?.[r],s=n.remote&&o,i=s?o:"global",a=wasPrompted()?"":`${Re.tick} `,l=!s&&o?ue.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ue.green(a)}Replaced ${ue.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ue.green(a)}Pushed ${ue.green(`'${r}'`)} taste package to ${i} ${ue.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ue.green(a)}Pushed ${ue.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",o=wasPrompted()?"":`${Re.tick} `;return logResult2(wrapLine(`${ue.green(o)}Pushed ${ue.green(t.packagesPushed.length)} taste packages ${ue.green(`(${t.packagesPushed.join(", ")})`)} to ${r}`)),!(n.overwrite||!t.mergeDetails)&&hasMergeConflictRiskInRecord(t.mergeDetails)}function logPushUrls(e){const{result:t,options:n}=e;if(!n.remote||!t.filePaths)return;const r=new Set;for(const e of t.packagesPushed){const n=t.filePaths[e];if(!n||!n.includes("/"))continue;const[o,s]=n.split("/");if(!o||!s)continue;const i=getPackageLink({owner:o,packageName:s});r.has(i)||(r.add(i),console.log(ue.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],o=t.packagesPushed.filter(e=>!n.includes(e)),s=t.packagesPushed.length+r.length,i=[];o.length>0&&i.push(wrapLine(`${ue.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ue.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ue.dim("Skipped")} (${r.length}) ${ue.dim(r.join(", "))}`,4)),i.length>0&&Ge.log.message(i.join("\n"));const a=`${s} ${1===s?"package":"packages"}`;Ge.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),o=[];r.length>0&&o.push(wrapLine(`${ue.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ue.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ue.dim("Skipped")} (${n.length}) ${ue.dim(n.join(", "))}`)),o.length>0&&console.log(o.join("\n"))}function logPushSuccess(e){const{result:t,options:n}=e;if(wasPrompted())return setPrompted(!1),logConflictSummary({result:t}),void logPushUrls({result:t,options:n});const r=logPushAllSuccess({result:t,options:n})||logPushSingleSuccess({result:t,options:n})||logPushMultiSuccess({result:t,options:n});n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r&&logMergeReviewTip()}__name(resolvePullStrategy,"resolvePullStrategy"),__name(executePullStrategy,"executePullStrategy"),__name(pullSinglePackage,"pullSinglePackage"),__name(pull,"pull"),__name(executePullRemote,"executePullRemote"),__name(pullRemote,"pullRemote"),Bt(),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSingleSuccess,"logPullSingleSuccess"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),__name(createPullCommand,"createPullCommand"),__name(validatePullOptions,"validatePullOptions"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Bt(),ir(),Bt(),VS(),LS(),_n(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Bt(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Bt(),kC(),Bt();var RN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),NN=__name(e=>e.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0),"countRemoteLearnings");async function resolvePushAllStrategy(e){const{flagStrategy:t,overwrite:n,existingProject:r,packagesToPush:o,projectName:s,owner:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=o.reduce((e,t)=>e+t.learnings.length,0),u=NN(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l}),m=await resolvePushAllStrategy({flagStrategy:a,overwrite:o,existingProject:d,packagesToPush:n,projectName:l,owner:r});if("skip"===m)return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?s:d?.isPublic??!1,overwrite:"overwrite"===m});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return RN({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var LN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),$N=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o,overwrite:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o,overwrite:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var DN=__name(e=>{const{target:t,category:n,owner:r}=e;return"local-global"===t?getCategoryTasteFile({target:"local-global",category:n}):"remote-project"!==t&&"remote-user"!==t||!r?void 0:`${r}/${n}`},"getDestPath");async function getUserOwner(){try{const e=await getAuthenticatedEntity();if(e.success&&e.user?.userName)return e.user.userName}catch{}}async function resolveSinglePushStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,target:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPushStrategy({packageName:s.category,localLearningsCount:s.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:o,userOwner:s,isPublic:i,result:a}=e,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:o,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:s,isPublic:i,overwrite:!0}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:s,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=DN({target:n,category:t.category,owner:s});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e;if(!exists2())return LN({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return LN({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:i}):LN({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return LN({pkg:"all",error:`Invalid target: ${r}`});const m=$N();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:o,userOwner:d,isPublic:s,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return LN({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return LN({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:o,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?s:u?.isPublic??!1,g=$N();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return LN({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return LN({pkg:t,error:e instanceof Error?e.message:String(e)})}}async function promptOwnerSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],o=await Ge.select({message:"Owner",options:r,initialValue:t});return Ge.isCancel(o)&&(Ge.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new Ne("push").description(`Push taste packages to remote ${ue.dim("(commandcode.ai)")} or global ${ue.dim("(~/.commandcode)")}`).argument("[package]","Taste package name to push (omit with --all)").option("--all","Push all taste packages to remote").option("--remote","Push to commandcode.ai remote (default)").option("-g, --global","Push to local global storage (~/.commandcode)").addOption(new Le("--local","Use local server").hideHelp()).option("--public","Make package publicly discoverable on commandcode.ai").option("--private","Make package private (not publicly discoverable)").option("--owner <owner>","Push under a specific owner or organization").option("--overwrite","Replace existing package without prompting").option("--skip","Keep existing package, skip conflicting push").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Le("--staging","Push to staging environment").hideHelp()).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),r=await runPush({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPushSuccess({result:r,options:n})}))}function validatePushOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one destination"),n.public&&n.private&&exitWithError("--public and --private are mutually exclusive — pick one visibility"),n.owner&&n.global&&exitWithError("--owner only applies to remote pushes, not --global"),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to push everything",usage:["cmd taste push <package> push a taste package to remote (default)","cmd taste push --all push all taste packages to remote","cmd taste push <package> -g push a taste package to global (~/.commandcode)"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}__name(getUserOwner,"getUserOwner"),__name(resolveSinglePushStrategy,"resolveSinglePushStrategy"),__name(executePushStrategy,"executePushStrategy"),__name(pushSinglePackage,"pushSinglePackage"),__name(push,"push"),__name(executeRemotePush,"executeRemotePush"),__name(pushRemote,"pushRemote"),Bt(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var ON=__name(e=>!!e.public||!e.private&&void 0,"resolveVisibility");async function validateOwnerAccess(e){let t;try{t=await fetchUserNamespaces()}catch(e){return void dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${e instanceof Error?e.message:String(e)}`)}const n=[t.userName,...t.orgs.map(e=>e.login)];n.includes(e)||exitWithError(`No push access to '${e}'. Available: ${n.join(", ")}`)}async function resolveOwnerForPush(e){const{packageName:t,owner:n}=e,r=parseOwnerPackage(t);if(r)return await validateOwnerAccess(r.owner),r;if(n)return await validateOwnerAccess(n),{owner:n,packageName:t};Ge.intro(ue.dim(`pushing ${t}`)),setPrompted(!0);const o=Ge.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),Ge.outro(ue.red(`Taste package '${t}' not found in project`)),process.exit(1));const s=await fetchUserNamespaces();return o.stop(s.orgs.length>0?"Select owner to push to":""),{owner:s.orgs.length>0?await promptOwnerSelection(s):s.userName,packageName:t}}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePushOptions({packageName:t,options:r});const o=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:o}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:o}):pushGlobal({packageName:t,options:r,strategy:o})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const o=(await getAllPackages2()).length,s=`${o} ${1===o?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ue.dim(` Pushing ${s} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(De("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:ON(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:o,packageName:s}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:o,pkgName:s});const i=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:ON(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=Ge.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(De("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),i=o.length>0?o.length:s.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(ue.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(De("Pushing taste packages").start());const d=await push({packages:o,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new Ne(an.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?de.bold(de.green(t)):de.white(t);return`${de.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${de.bold(de.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(de.dim(`Run ${de.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(de.dim("Try updating manually:")),console.log(de.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(de.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(`${de.green(Re.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${de.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} ${Re.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:Ls.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 ${de.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),Co(),__name(createTasteCommand,"createTasteCommand"),Bt(),_n(),Bs(),__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 FN=new Ne("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Bt(),cC(),kC();var jN=__name((e,t)=>`${Re.info} ${e}: ${de.cyan(t)}`,"formatInfoLine"),UN=__name(e=>de.bold(`${e}:`),"formatSectionHeader"),BN=__name(e=>de.red(e),"formatError"),qN=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),zN=__name(e=>["",UN("User Information"),jN("Name",e.name),jN("Email",e.email),jN("Username",e.userName)],"buildUserOutput"),HN=__name(e=>["",UN("Organization"),jN("Name",e.name),jN("Login",e.login)],"buildOrgOutput"),WN=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),GN=__name((e,t)=>{WN(zN(e)),t&&WN(HN(t)),console.log("")},"displayUserInfo"),VN=__name(e=>null!==e&&e.length>0,"validateApiKey"),KN=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=De("Fetching user information...").start();try{const t=await getAuthKey();VN(t)||(e.fail(BN('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();KN(n)||(e.fail(BN("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),GN(n.user,n.org)}catch(t){e.fail(BN(`Error: ${qN(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var QN=new Ne("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function normalizeGitUrl(e){let t=e.trim();const n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);return n?`https://${n[1]}/${n[2]}`:(t=t.replace(/\.git$/,""),t)}function validateGitRepo(){try{if("true"!==Ce("git rev-parse --is-inside-work-tree",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error("Not inside a git repository.")}catch{throw new Error("Sandbox requires a git repository with a GitHub remote.")}let e;try{e=Ce("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("No GitHub remote found. Add one with: git remote add origin https://github.com/you/repo")}const t=normalizeGitUrl(e);let n;try{n=Ce("git branch --show-current",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("Failed to determine current branch.")}if(!n)throw new Error("Detached HEAD state. Please checkout a branch first.");if(!/^[\w./-]+$/.test(n))throw new Error("Branch name contains invalid characters. Please use a simpler branch name.");try{if(!Ce(`git ls-remote --heads origin ${n}`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}catch(e){if(e instanceof Error&&e.message.includes("not found on remote"))throw e;throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}return{repoUrl:t,branch:n,isClean:""===Ce("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}Bt(),Bt(),_n(),LS(),oi(),VS(),Un(),Ro(),Bt(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Bt(),VS(),cC(),Bt();var YN=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return YN.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var JN={setting_up:"Setting up sandbox...",cloning:"Cloning repository..."};function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusEvent({event:e,state:t}){const n=e.data.status,r=JN[n],o="setup"===t.phase;if(t.isResume&&o&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&o&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=De({stream:process.stderr,text:r}).start()),"running"===n)return t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="running",void(t.workingSpinner||(t.workingSpinner=De({stream:process.stderr}).start()));if("completed"===n){t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="done";const n=e.data.prUrl;return void(n&&console.error(`PR: ${de.cyan(n)}`))}if("failed"===n){const n=e.data.message||"Unknown error";return t.workingSpinner&&(t.workingSpinner.fail(n),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(n),t.currentSpinner=null),void(t.phase="done")}if("timed_out"===n)return t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null),void(t.phase="done");"cancelled"===n&&(stopAllSpinners({state:t}),t.phase="done",console.error(`\n${de.yellow("Cancelled.")}`))}}function renderEvent({event:e,state:t}){if("status"!==e.type){if("pty"===e.type){const n=e.data.content;return void(n&&(t.workingSpinner&&t.workingSpinner.stop(),process.stdout.write(n),t.workingSpinner&&t.workingSpinner.start()))}if("error"===e.type){t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null);const n=e.data.message;console.error(`${Re.cross} ${de.red(n)}`)}}else renderStatusEvent({event:e,state:t})}function setupInputHandling({callbacks:e}){const t=__name(t=>{3===t[0]?e.onCancel():4===t[0]&&e.onDetach()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({ws:e}){const t=__name(()=>{e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({action:"resize",cols:process.stdout.columns,rows:process.stdout.rows}))},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}function sendTerminalSize({ws:e}){e.send(JSON.stringify({action:"resize",cols:process.stdout.columns||120,rows:process.stdout.rows||30}))}async function streamSession({sessionId:e,prompt:t,lastEventId:n=0,isResume:r=!1}){const o=getApiBaseUrl().replace(/^http/,"ws"),s=await getAuthKey();if(!s)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:s,...n>0?{lastEventId:String(n)}:{}}),a=`${o}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,o)=>{const s=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=De({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.close(),console.error(`\n${de.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.readyState===WebSocket.OPEN&&s.send(JSON.stringify({action:"cancel"})),s.close(),console.error(`\n${de.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:s}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");s.addEventListener("open",()=>{sendTerminalSize({ws:s}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${de.yellow("[Ctrl+C]")} ${de.dim("stop")} ${de.yellow("[Ctrl+D]")} ${de.dim("detach")}`),console.error(`${de.dim("Session:")} ${de.gray(e)}`),console.error(""),r&&(i.workingSpinner=De({stream:process.stderr}).start())}),s.addEventListener("message",e=>{try{const n="string"==typeof e.data?e.data:e.data.toString(),r=JSON.parse(n);renderEvent({event:r,state:i}),void 0!==r.id&&(i.lastEventId=r.id),"status"===r.type&&isTerminalStatus(r.data.status)&&(s.close(),g(),t())}catch{}}),s.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),o(new Error("WebSocket connection failed"))}),s.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${de.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=$.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=$.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=dt.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function startSandboxSession({repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}){return new hS({baseUrl:getApiBaseUrl()}).post({endpoint:Gt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,isInternalTeam:r,configFiles:o}})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateGitRepo();n.isClean||console.error(de.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),s=e||await askQuestion(`${de.bold("What do you want to do?")}\n${de.cyan(">")} `);if(!s.trim())return void console.error(de.yellow("No prompt provided. Aborting."));const i=s.trim().slice(0,ln.MAX_PROMPT_CHARS),a=De({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:i,isInternalTeam:r,configFiles:o});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:i}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=e instanceof Ws,r=t?e.code:void 0;if(401===(t?e.status:void 0)||"UNAUTHORIZED"===r)console.error(de.red("\nAuthentication failed. Try logging in again: cmd login"));else if("GITHUB_APP_NOT_INSTALLED"===r){const e=de.cyan(de.underline(n.repoUrl)),t=de.cyan(de.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${de.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(de.dim(" Then run this command again."))}else{const n=t&&"string"==typeof e.message?e.message:"Something went wrong. Please try again.";console.error(de.red(`\n${n}`))}process.exit(1)}}function createSandboxCommand(){return new Ne("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(de.red(t)),process.exit(1)}})}function validateSafeString(e,t){if(e.includes("..")||e.includes("\\"))throw new Error(`Invalid ${t}: path traversal sequences are not allowed.\nExpected format: owner/repo or owner/repo/path`);if(!/^[a-zA-Z0-9._/-]+$/.test(e))throw new Error(`Invalid ${t}: contains unsupported characters.\nOnly letters, numbers, hyphens, underscores, dots, and slashes are allowed.`)}function parseGitHubRepo(e){let t,n=e.replace(/^https?:\/\/github\.com\//,"");const r=n.lastIndexOf("@");r>0&&r<n.length-1&&(t=n.slice(r+1),n=n.slice(0,r),validateSafeString(t,"branch name"));const o=n.split("/");if(o.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[s,i,...a]=o;validateSafeString(s,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:s,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:o}=e;let s=`gh:${t}/${n}`;return r&&(s+=`/${r}`),o&&(s+=`#${o}`),s}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:o,path:s}=n;let i;if(s){const e=s.split("/").filter(Boolean);i=e[e.length-1]}else i=o;const a=t.join(S.tmpdir(),`commandcode-skill-${N()}`);await k.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:s}=await import("giget");try{await s(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,o),await s(e,{dir:a,force:!0,silent:!0})}const l=t.join(a,"SKILL.md"),u=t.join(a,"skill.md");let d=!1;try{await k.access(l),d=!0}catch{}if(!d)try{await k.access(u),d=!0}catch{}if(!d)throw new Error(`SKILL.md not found in ${e}. Make sure the repository contains a SKILL.md file.`);return{tempDir:a,skillName:i}}catch(e){if(await k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,o)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:o,path:s,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(RC(),MC)),u=await l({owner:r,repo:o,path:s,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${o}${s?` at path "${s}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await k.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await k.access(r),r}catch{}throw new Error(`SKILL.md not found in ${e}`)}function validateSkillName(e){const t=e.trim();if(!t||0===t.length)throw new Error("Invalid skill name: name cannot be empty");if(t.includes("/")||t.includes("\\"))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain path separators (/ or \\).`);if(t.includes(".."))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain parent directory references (..).`);if(t.startsWith("."))throw new Error(`Invalid skill name: "${e}". Skill names cannot start with a dot.`);if(!/^[a-z0-9-]+$/.test(t))throw new Error(`Invalid skill name: "${e}". Skill names must contain only lowercase letters, numbers, and hyphens.`);return t}async function validateSkillContent(e){const t=await resolveSkillMdPath(e),n=await k.readFile(t,"utf-8"),{data:r}=qe(n),o=zf.parse(r);return{name:validateSkillName(o.name),description:o.description}}async function skillExists(e){const{skillName:n,location:r}=e,o="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),s=t.join(o,n);try{return await k.access(s),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:o=!1,force:s=!1,skillName:i,discoveredSkill:a,cachedTempDir:l}=r;let u,d,m=n;if(i){let e;if(a)e=a;else{const t=await discoverSkillsInRepo(n);if(0===t.skills.length)throw new Error(`No skills found in repository: ${n}`);const r=t.skills.find(e=>e.name.toLowerCase()===i.toLowerCase());if(!r){const e=t.skills.map(e=>e.name).join(", ");throw new Error(`Skill "${i}" not found in repository. Available skills: ${e}`)}e=r}const t=parseGitHubRepo(n),r=[t.path,e.path&&"."!==e.path?e.path:void 0].filter(Boolean).join("/"),o=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${o}@${t.branch}`:o}if(l&&a){u=a.path&&"."!==a.path?t.join(l,a.path):l,d=!1;try{await resolveSkillMdPath(u)}catch{const e=a.path&&"."!==a.path?`at ${a.path}`:"at root";throw new Error(`SKILL.md not found in cached directory ${e}. Make sure the repository contains a SKILL.md file.`)}}else u=(await fetchSkillFromGitHub(m)).tempDir,d=!0;try{const{name:e,description:n}=await validateSkillContent(u),r=e,i=o?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!s)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await k.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await k.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&s&&await k.rm(d,{recursive:!0,force:!0}),await k.rename(g,d)}catch(e){if(await k.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await k.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),o=n?"global":"project",s="global"===o?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(s,r);if(!await skillExists({skillName:r,location:o}))throw new Error(`Skill "${r}" not found in ${"global"===o?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===o?"":" Use -g/--global to check global skills."}`);await k.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t,warnings:n}=await loadAllSkillSummariesWithWarnings(),r=getBundledSkillsDir(),o=[],s=[];for(const t of e){const e={name:t.name,description:t.description,location:isBundledSkillPath({filePath:t.filePath,bundledDir:r})?"bundled":"global",path:t.filePath};("bundled"===e.location?o:s).push(e)}return{global:s,project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath})),bundled:o,warnings:n}}__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusEvent,"renderStatusEvent"),__name(renderEvent,"renderEvent"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(sendTerminalSize,"sendTerminalSize"),__name(streamSession,"streamSession"),__name(readLocalConfigFiles,"readLocalConfigFiles"),__name(askQuestion,"askQuestion"),__name(startSandboxSession,"startSandboxSession"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),Co(),Bt(),Bt(),Bt(),Bt(),IC(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),QS(),iy(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),_n();var XN=[`${de.dim("Usage:")}`,` ${de.cyan("cmd skills add")} ${de.white("<owner/repo>")}`,"",`${de.dim("Examples:")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/my-skills")} ${de.dim("# single-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/skills/path/to/skill")} ${de.dim("# specific path in repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/multi-skills -s my-skill")} ${de.dim("# pick one from multi-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo@branch")} ${de.dim("# specific branch")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo --global")} ${de.dim("# install to ~/.commandcode/skills/")}`],ZN=__name((e,t)=>`${de.green(Re.tick)} Installed ${de.cyan(e)} ${de.dim(`${Re.arrowRight} ${t}/`)}`,"formatInstalled"),eL=__name(e=>`${de.red(Re.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await x(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(eL("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),XN.forEach(e=>console.log(e)),process.exit(1));const t=e.replace(/^https?:\/\/github\.com\//,""),n=t.lastIndexOf("@");(n>0?t.slice(0,n):t).split("/").filter(Boolean).length<2&&(console.error(eL(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${de.cyan("owner/repo")} or ${de.cyan("owner/repo/path")}`),console.log(""),XN.forEach(e=>console.log(e)),process.exit(1))}async function addAction(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let o;validateRepoFormat(e);const s=De({text:`Fetching ${de.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(o=u,s.stop(),0===l.length&&(console.error(eL(`No skills found in ${de.cyan(e)}`)),console.log(de.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(eL(`Skill "${t.skill}" not found in ${de.cyan(e)}`)),console.log(""),console.log(de.dim("Available skills:")),l.forEach(e=>console.log(` ${de.cyan(e.name)}`)),await cleanupAndExit(o,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await Ve({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(de.dim("Cancelled")),await cleanupAndExit(o,0));const n=t;i=l.filter(e=>n.includes(e.name))}else i=l;let d=0;for(const n of i)try{const s=De({text:`Installing ${de.cyan(n.name)}...`,color:"cyan"});s.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:o}});s.stop(),console.log(ZN(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(eL(`Failed to install "${n.name}"`)),console.log(de.dim(` ${t}`))}await cleanupAndExit(o,d>0?1:0)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(eL(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var tL=new Ne("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${XN.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(eL("No repository specified.")),console.log(""),XN.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Bt(),_n();var nL=__name((e,t)=>`${de.green(Re.tick)} Removed ${de.cyan(e)} from ${t} skills`,"formatRemoved"),rL=__name(e=>`${de.red(Re.cross)} ${e}`,"formatError");function validateSkillNameEarly(e){return e.includes("/")||e.includes("\\")?`"${e}" is not a valid skill name — it cannot contain path separators.`:e.includes("..")?`"${e}" is not a valid skill name — it cannot contain "..".`:e.startsWith(".")?`"${e}" is not a valid skill name — it cannot start with a dot.`:/^[a-z0-9-]+$/.test(e.trim())?null:`"${e}" is not a valid skill name — use only lowercase letters, numbers, and hyphens.`}async function removeAction(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",o=validateSkillNameEarly(e);if(o&&(console.error(rL(o)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Ke({message:`Remove ${de.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(de.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(nL(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(rL(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(de.dim(`Try ${de.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`))):console.error(rL(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var oL=new Ne("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction);Bt(),QS(),Nv(),_n();var sL=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${de.cyan(e)} ${de.dim(`· ${n}`)}`},"formatSkillLine"),iL=__name((e,t)=>`${de.bold(de.white(e))} ${de.dim(`(${t})`)}`,"formatSectionHeader"),aL=__name(e=>{if(0===e.length)return;const t=groupWarnings(e);console.log(""),console.log(`${de.bold(de.yellow("Skipped"))} ${de.dim(`(${e.length})`)}`);for(const e of t){console.log(""),console.log(` ${de.bold(e.category)} ${de.dim(`(${e.items.length})`)}`);for(const t of e.items)console.log(` ${de.bold(skillIdentifier(t.path))}`),console.log(` ${de.dim(t.reason)}`)}},"printWarnings"),lL=__name(()=>{const e=process.cwd(),n=t.join(e,".commandcode","skills"),r=t.join(e,".agents","skills"),o=getProjectSkillsDir(),s=getProjectAgentsCompatSkillsDir(),i=["",de.dim("No skills installed."),"",de.dim("Looking in:"),de.dim(` ${getGlobalSkillsDir()} ${de.white("(global)")}`),de.dim(` ${getGlobalAgentsCompatSkillsDir()} ${de.white("(global, .agents)")}`)];return n!==o&&i.push(de.dim(` ${n} ${de.white("(cwd)")}`)),r!==s&&i.push(de.dim(` ${r} ${de.white("(cwd, .agents)")}`)),i.push(de.dim(` ${o} ${de.white("(project)")}`),de.dim(` ${s} ${de.white("(project, .agents)")}`),"",`Install a skill: ${de.cyan("cmd skills add")} ${de.dim("<owner/repo>")}`,""),i},"formatEmptyHint"),cL=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){const e="true"===process.env.DEBUG;try{const{global:t,project:n,bundled:r,warnings:o}=await listSkills(),s=t.length+n.length,i=__name(()=>{e||0===o.length||(console.log(""),console.log(de.dim(`${o.length} skill${1===o.length?"":"s"} skipped · run with ${de.cyan("--debug")} to see issues`)))},"printDebugHint");0===s&&(cL(lL()),r.length>0&&(console.log(iL("Bundled",r.length)),r.forEach(e=>{console.log(sL(e.name,e.description))}),console.log("")),e&&(aL(o),o.length>0&&console.log("")),e||(i(),console.log("")),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:de.dim(`${s} installed`)})),n.length>0&&(console.log(""),console.log(iL("Project",n.length)),n.forEach(e=>{console.log(sL(e.name,e.description))})),t.length>0&&(console.log(""),console.log(iL("Global",t.length)),t.forEach(e=>{console.log(sL(e.name,e.description))})),r.length>0&&(console.log(""),console.log(iL("Bundled",r.length)),r.forEach(e=>{console.log(sL(e.name,e.description))})),e&&aL(o),e||i(),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${de.red(Re.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var uL=new Ne("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction),dL=new Ne("skills").description("Manage skills from GitHub repositories").addCommand(tL).addCommand(oL).addCommand(uL);handleUnhandledErrors(),setupTelemetry(),await preRun();var mL=createProgram();mL.action(interactiveModeAction),mL.addCommand(HR),mL.addCommand(WR),mL.addCommand(QN),mL.addCommand(FN),mL.addCommand(zR),mL.addCommand(createTasteCommand()),mL.addCommand(createMcpCommand()),mL.addCommand(GR),mL.addCommand(zs),mL.addCommand(Wv),mL.addCommand(eC),mL.addCommand(dL),isExperimentalEnabled()&&mL.addCommand(createSandboxCommand()),setupCommanderHooks(mL),mL.parse();