#!/usr/bin/env bun
// @bun
import{A as Gz,P as Az,S as bz,T as Nz,Y as Fz,Z as Tz,a as rz,ba as xz,t as n,u as l,w as i,y as Hz}from"./index-wn2m4wma.js";async function m(z,W){let X=Bun.spawn(["git",...z],{cwd:W,stdout:"pipe",stderr:"pipe"}),Y=await new Response(X.stdout).text(),$=await new Response(X.stderr).text(),Q=await X.exited;return{stdout:Y.trim(),stderr:$.trim(),exitCode:Q}}async function jz(z){let{exitCode:W}=await m(["rev-parse","--git-dir"],z);return W===0}async function Mz(z){let{stdout:W,exitCode:X}=await m(["rev-parse","--abbrev-ref","HEAD"],z);if(X!==0)return"HEAD";return W||"HEAD"}async function wz(z){let{stdout:W,exitCode:X}=await m(["rev-list","--left-right","--count","@{upstream}...HEAD"],z);if(X!==0||!W)return{ahead:0,behind:0};let Y=W.split(/\s+/);if(Y.length>=2&&Y[0]!==void 0&&Y[1]!==void 0)return{ahead:parseInt(Y[0],10)||0,behind:parseInt(Y[1],10)||0};return{ahead:0,behind:0}}async function Pz(z){let{stdout:W,exitCode:X}=await m(["status","--porcelain"],z);if(X!==0||!W)return{staged:[],unstaged:[],untracked:[],conflicted:[]};let Y=[],$=[],Q=[],K=[],J=W.split(`
`);for(let U of J){if(!U)continue;let E=U[0],R=U[1],O=U.substring(3);if(O.includes(" -> ")){let _=O.split(" -> ");O=_[1]??_[0]??O}if(E==="U"||R==="U"||E==="A"&&R==="A"||E==="D"&&R==="D"||E==="A"&&R==="U"||E==="U"&&R==="A"||E==="D"&&R==="U"||E==="U"&&R==="D"){K.push(O);continue}if(E==="?"&&R==="?"){Q.push(O);continue}if(E!==" "&&E!=="?"&&E!=="!")Y.push(O);if(R!==" "&&R!=="?"&&R!=="!"){if(!Y.includes(O))$.push(O)}}return{staged:Y,unstaged:$,untracked:Q,conflicted:K}}async function k(z){try{if(!await jz(z))return null;let[X,Y,$]=await Promise.all([Mz(z),wz(z),Pz(z)]);return{branch:X,ahead:Y.ahead,behind:Y.behind,staged:$.staged,unstaged:$.unstaged,untracked:$.untracked,conflicted:$.conflicted}}catch(W){return console.error("Error getting git status:",W),null}}import{randomUUID as Dz}from"crypto";import{execSync as d}from"child_process";var h=process.env.CLAUDE_CHECKPOINTS_DIR||`${process.env.HOME}/.claude/checkpoints`;function vz(z){let W=0;for(let X=0;X<z.length;X++){let Y=z.charCodeAt(X);W=(W<<5)-W+Y,W=W&W}return Math.abs(W).toString(16)}function yz(z){try{d("git rev-parse --is-inside-work-tree",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let W=d("git rev-parse --abbrev-ref HEAD",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),X=0,Y=0;try{let U=d("git rev-list --left-right --count @{upstream}...HEAD 2>/dev/null || echo '0 0'",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(/\s+/);Y=parseInt(U[0]||"0",10),X=parseInt(U[1]||"0",10)}catch{}let $=d("git status --porcelain",{cwd:z,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),Q=[],K=[],J=[];for(let U of $.split(`
`)){if(!U.trim())continue;let E=U[0],R=U[1],O=U.slice(3);if(E==="?"&&R==="?")J.push(O);else if(E!==" "&&E!=="?")Q.push(O);else if(R!==" ")K.push(O)}return{branch:W,ahead:X,behind:Y,staged:Q,unstaged:K,untracked:J}}catch(W){return}}async function Sz(z,W){let X=[];for(let Y of W)try{let $=`${z}/${Y}`,Q=Bun.file($);if(await Q.exists()){let K=await Q.text();X.push({path:Y,content:K,hash:vz(K)})}}catch{}return X}async function Iz(z,W){let X=0,Y=0;for(let $ of W)try{let Q=`${z}/${$.path}`;await Bun.write(Q,$.content),X++}catch{Y++}return{restored:X,failed:Y}}async function r(){if(!await Bun.file(h).exists())await Bun.write(h+"/.gitkeep","")}function o(z){return`${h}/${z}.json`}async function S(z){let W=new Map;try{let X=o(z),Y=Bun.file(X);if(await Y.exists()){let $=await Y.text(),Q=JSON.parse($);for(let K of Q)W.set(K.id,K)}}catch(X){}return W}async function fz(z,W){await r();let X=o(z),Y=Array.from(W.values());await Bun.write(X,JSON.stringify(Y,null,2))}async function t(z,W,X={}){let Y=await S(z),$=X.workingDirectory||process.cwd(),Q=yz($),K=[];if(X.trackFiles!==!1&&Q){let U=[...Q.staged,...Q.unstaged,...Q.untracked];K=await Sz($,U)}let J={id:Dz().slice(0,8),sessionId:z,timestamp:Date.now(),label:X.label||`Checkpoint ${Y.size+1}`,description:X.description,messages:JSON.parse(JSON.stringify(W)),files:K,gitState:Q,metadata:{model:X.model,workingDirectory:$,totalCost:X.totalCost||0,messageCount:W.length,fileCount:K.length}};return Y.set(J.id,J),await fz(z,Y),J}async function g(z,W){return(await S(z)).get(W)||null}async function I(z,W={}){let X=W.workingDirectory||z.metadata.workingDirectory||process.cwd(),Y=0,$=0;if(W.restoreFiles!==!1&&z.files.length>0){let Q=await Iz(X,z.files);Y=Q.restored,$=Q.failed}return{messages:W.restoreMessages!==!1?z.messages:[],filesRestored:Y,filesFailed:$}}async function e(z){let W=await S(z);return Array.from(W.values()).sort((X,Y)=>Y.timestamp-X.timestamp)}function v(z,W=!1){let X=new Date(z.timestamp),Y=X.toLocaleTimeString(),$=X.toLocaleDateString(),Q=`\x1B[33m${z.id}\x1B[0m `;if(Q+=`\x1B[1m${z.label}\x1B[0m `,Q+=`\x1B[90m(${$} ${Y})\x1B[0m`,z.files.length>0)Q+=` \x1B[32m[${z.files.length} files]\x1B[0m`;if(z.gitState)Q+=` \x1B[34m(${z.gitState.branch})\x1B[0m`;if(W){if(Q+=`
  Messages: ${z.metadata.messageCount}`,Q+=`
  Files: ${z.metadata.fileCount}`,Q+=`
  Cost: $${z.metadata.totalCost.toFixed(4)}`,z.gitState){let K=z.gitState.staged.length+z.gitState.unstaged.length+z.gitState.untracked.length;Q+=`
  Git changes: ${K}`}if(z.description)Q+=`
  ${z.description}`}return Q}function s(z){if(z.length===0){console.log("\x1B[90mNo checkpoints saved.\x1B[0m"),console.log("\x1B[90mUse /checkpoint <label> to create one.\x1B[0m");return}console.log(`
\x1B[1mCheckpoints (${z.length}):\x1B[0m`),console.log("\x1B[90m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m");for(let W of z)console.log(v(W));console.log("\x1B[90m\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\x1B[0m"),console.log("\x1B[90m/restore <id>        - Restore checkpoint (files + chat)\x1B[0m"),console.log("\x1B[90m/restore-chat <id>   - Restore chat only (no files)\x1B[0m"),console.log("\x1B[90m/checkpoint <label>  - Create new checkpoint\x1B[0m")}function zz(z){let W=[];if(z.files.length>0)W.push(`${z.files.length} files`);if(W.push(`${z.metadata.messageCount} msgs`),z.gitState){let X=z.gitState.staged.length+z.gitState.unstaged.length+z.gitState.untracked.length;if(X>0)W.push(`${X} changes`)}return W.join(" | ")}var Wz=(z)=>`${h}/${z}-nav.json`;async function u(z){try{let W=Bun.file(Wz(z));if(await W.exists())return JSON.parse(await W.text())}catch{}return{sessionId:z,checkpointIds:[],currentIndex:-1,undoneIds:[]}}async function c(z){await r(),await Bun.write(Wz(z.sessionId),JSON.stringify(z,null,2))}async function Xz(z,W){let X=await u(z);if(X.currentIndex<X.checkpointIds.length-1)X.checkpointIds=X.checkpointIds.slice(0,X.currentIndex+1);X.checkpointIds.push(W),X.currentIndex=X.checkpointIds.length-1,X.undoneIds=[],await c(X)}async function Yz(z){let W=await u(z),X=await S(z);if(W.currentIndex<=0)return{checkpoint:null,canRedo:!1};let Y=W.checkpointIds[W.currentIndex];if(Y)W.undoneIds.push(Y);W.currentIndex--;let $=W.checkpointIds[W.currentIndex];return await c(W),{checkpoint:$?X.get($)||null:null,canRedo:W.undoneIds.length>0}}async function Zz(z){let W=await u(z),X=await S(z);if(W.undoneIds.length===0)return{checkpoint:null,canRedo:!1};let Y=W.undoneIds.pop();return W.currentIndex++,await c(W),{checkpoint:X.get(Y)||null,canRedo:W.undoneIds.length>0}}async function $z(z){let W=await u(z);return{total:W.checkpointIds.length,current:W.currentIndex+1,canUndo:W.currentIndex>0,canRedo:W.undoneIds.length>0,currentId:W.checkpointIds[W.currentIndex]}}import{readFile as Cz,access as mz}from"fs/promises";import{join as Qz}from"path";var kz={globalPath:`${process.env.HOME}/.claude/CLAUDE.md`,projectPath:".claude/CLAUDE.md",rootPath:"CLAUDE.md"};async function dz(z){try{return await mz(z),!0}catch{return!1}}async function a(z){try{if(await dz(z))return(await Cz(z,"utf-8")).trim()}catch(W){}return null}async function hz(z=process.cwd(),W={}){let X={...kz,...W},Y=[],$=null,Q=null,K=X.globalPath;if($=await a(K),$)Y.push(K);let J=Qz(z,X.projectPath),U=Qz(z,X.rootPath);if(Q=await a(J),Q)Y.push(J);else if(Q=await a(U),Q)Y.push(U);let E=[];if($)E.push(`# Global Instructions

${$}`);if(Q)E.push(`# Project Instructions

${Q}`);return{global:$,project:Q,merged:E.join(`

---

`),sources:Y}}async function Jz(z=process.cwd()){let{merged:W,sources:X}=await hz(z);if(!W)return"";return`
## Project Instructions

${X.length>0?`Loaded from: ${X.join(", ")}`:""}

${W}
`}import{readFile as uz,access as pz}from"fs/promises";import{join as f}from"path";var Bz=process.env.HOME||"",Vz=f(Bz,".claude"),w={main:f(Bz,".claude.json"),settings:f(Vz,"settings.json"),keybindings:f(Vz,"keybindings.json"),projectSettings:(z)=>f(z,".claude","settings.json")};async function lz(z){try{return await pz(z),!0}catch{return!1}}async function p(z,W){try{if(await lz(z)){let X=await uz(z,"utf-8");return{config:JSON.parse(X),loaded:!0}}}catch(X){}return{config:W,loaded:!1}}async function gz(){return p(w.main,{})}async function cz(){return p(w.settings,{})}async function az(){return p(w.keybindings,{bindings:[]})}async function nz(z){return p(w.projectSettings(z),{})}function iz(z,W){return z.projects?.[W]}async function Uz(z=process.cwd()){let W=[],{config:X,loaded:Y}=await gz();if(Y)W.push(w.main);let{config:$,loaded:Q}=await cz();if(Q)W.push(w.settings);let{config:K,loaded:J}=await az();if(J)W.push(w.keybindings);let{config:U,loaded:E}=await nz(z);if(E)W.push(w.projectSettings(z));return{main:X,settings:$,keybindings:K,projectSettings:U,sources:W}}function Kz(z,W){return{hooks:{...z.hooks,...W.hooks},permissions:{...z.permissions,...W.permissions}}}function Lz(z,W){let X={};if(z.mcpServers)Object.assign(X,z.mcpServers);let Y=iz(z,W);if(Y?.mcpServers)Object.assign(X,Y.mcpServers);return X}function Ez(z){let W={};if(!z.hooks)return W;for(let[X,Y]of Object.entries(z.hooks)){let $=[],Q=X;for(let K of Y)for(let J of K.hooks)$.push({event:Q,command:J.type==="command"?J.command||"":"",timeout:J.timeout||60000,enabled:!0,_matcher:K.matcher,_prompt:J.type==="prompt"?J.prompt:void 0});if($.length>0)W[Q]=$}return W}function Rz(z){return z.permissions?.defaultMode||"default"}function Oz(z){return new Set(z.permissions?.allowedTools||[])}function _z(z){return new Set(z.permissions?.disallowedTools||[])}async function oz(z){try{let X=await Bun.file(z).text(),Y=JSON.parse(X);if("servers"in Y&&typeof Y.servers==="object"&&Y.servers!==null)return Y.servers;if("type"in Y){let $={};return $.default=Y,$}return Y}catch(W){let X=W instanceof Error?W.message:String(W);throw Error(`Failed to load MCP config from ${z}: ${X}`)}}function tz(z){let W=[];for(let[X,Y]of z)for(let $ of Y.tools)W.push({name:`mcp__${X}__${$.name}`,description:$.description,input_schema:$.inputSchema,handler:async(Q,K)=>{if(!Y.connected)return{content:`Error: MCP server "${X}" is not connected`,is_error:!0};return Y.callTool($.name,Q)}});return W}function ez(){let z=process.argv.slice(2),W={model:"claude-sonnet-4-6",permissionMode:"default",maxTokens:4096};for(let X=0;X<z.length;X++)switch(z[X]){case"--model":case"-m":W.model=z[++X]??"claude-sonnet-4-6";break;case"--permission-mode":case"-p":W.permissionMode=z[++X]??"default";break;case"--max-tokens":W.maxTokens=parseInt(z[++X]??"4096",10);break;case"--system-prompt":W.systemPrompt=z[++X];break;case"--append-system-prompt":W.appendSystemPrompt=z[++X];break;case"--config":W.configFile=z[++X];break;case"--mcp-config":W.mcpConfig=z[++X];break;case"--resume":W.resumeSession=z[++X];break;case"--sessions":W.listSessions=!0;break;case"--teammate-mode":W.teammateMode=!0;break;case"--agent-id":W.agentId=z[++X];break;case"--agent-name":W.agentName=z[++X];break;case"--team-name":W.teamName=z[++X];break;case"--agent-color":W.agentColor=z[++X];break;case"--interleaved":W.interleaved=!0;break;case"--no-interleaved":W.interleaved=!1;break;case"--extended-thinking":case"-e":W.extendedThinking=!0;break;case"--effort":W.effort=z[++X]??"medium";break;case"--query":case"-q":W.query=z[++X];break;case"--loop":case"-l":W.loop=!0;break;case"--max-iterations":W.maxIterations=parseInt(z[++X]??"10",10);break;case"--help":case"-h":sz(),process.exit(0)}return W}function sz(){console.log(`
Coder v0.1.0
A reimplementation of Claude Code CLI

USAGE:
  coder [OPTIONS] [QUERY]

OPTIONS:
  -m, --model <model>           Model to use (default: claude-sonnet-4-6)
  -p, --permission-mode <mode>  Permission mode (default, acceptEdits, bypassPermissions)
  --max-tokens <tokens>         Maximum output tokens (default: 4096)

Extended Thinking:
  -e, --extended-thinking       Enable extended thinking mode
  --effort <level>              Thinking effort: low, medium, high, max
  --interleaved                 Enable interleaved thinking (default: true)
  --no-interleaved              Disable interleaved thinking

Autonomous Loop:
  -l, --loop                    Enable autonomous loop mode
  --max-iterations <n>          Max iterations in loop mode (default: 10)

Other:
  --system-prompt <prompt>      Override system prompt
  --append-system-prompt <p>    Append to system prompt
  --config <file>               Configuration file path
  --mcp-config <file>           MCP server configuration file
  --resume <session-id>         Resume a previous session
  --sessions                    List recent sessions
  --teammate-mode               Run as teammate agent
  --agent-id <id>               Agent identifier
  --agent-name <name>           Agent display name
  --team-name <name>            Team name
  --agent-color <color>         Agent color for UI
  -q, --query <query>           Single query to execute
  -h, --help                    Show this help message

EXAMPLES:
  coder "What files are in this directory?"
  coder -m claude-opus-4-6 "Explain this codebase"
  coder --permission-mode acceptEdits "Add a test"
  coder --loop "Fix all TypeScript errors"     # Autonomous loop
  coder --loop --max-iterations 20 "Big task"  # More iterations
  coder --sessions
  coder --resume abc123-def456
`)}async function zW(){let z=ez(),W=new Hz;if(await W.init(),z.listSessions){let B=await W.listSessions(20);Gz(B),process.exit(0)}let X=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.Z_AI_API_KEY;if(!X)console.error("Error: ANTHROPIC_API_KEY, CLAUDE_API_KEY, ANTHROPIC_AUTH_TOKEN, or Z_AI_API_KEY environment variable required"),process.exit(1);console.log("\x1B[90mLoading configuration...\x1B[0m");let Y;try{Y=await Uz(process.cwd())}catch(B){let F=B instanceof Error?B.message:String(B);console.error(`\x1B[33mWarning: Failed to load config: ${F}\x1B[0m`),Y={main:{},settings:{},keybindings:{bindings:[]},projectSettings:{},sources:[]}}let $=Kz(Y.settings,Y.projectSettings);if(Y.sources.length>0)console.log(`\x1B[90m  Config sources: ${Y.sources.length} files\x1B[0m`);if(z.permissionMode==="default"){let B=Rz($);if(B!=="default")z.permissionMode=B,console.log(`\x1B[90m  Permission mode: ${B} (from config)\x1B[0m`)}let Q=Oz($),K=_z($),J=new Nz,U=new Fz,E=new xz,R=Ez($);for(let[B,F]of Object.entries(R))for(let b of F)J.register(B,b);if(Object.keys(R).length>0)console.log(`\x1B[90m  Hooks registered: ${Object.keys(R).length} events\x1B[0m`);let O=process.cwd()+"/.claude/skills";U.loadFromDirectory(O,"project");let T=new Map,x=Lz(Y.main,process.cwd());if(z.mcpConfig)try{console.log(`\x1B[90mLoading MCP config from ${z.mcpConfig}...\x1B[0m`),x=await oz(z.mcpConfig)}catch(B){let F=B instanceof Error?B.message:String(B);console.error(`\x1B[33mWarning: Failed to load MCP config file: ${F}\x1B[0m`)}if(Object.keys(x).length>0){let F=Object.entries(x).filter(([b,M])=>!M.disabled).length;if(F>0){console.log(`\x1B[90m  Connecting to ${F} MCP server(s)...\x1B[0m`);let b=await bz(x,(M)=>{console.log(`\x1B[90m    ${M}\x1B[0m`)});for(let[M,y]of b)T.set(M,y);if(T.size>0)console.log(`\x1B[32m  Connected to ${T.size} MCP server(s)\x1B[0m`);else console.log("\x1B[33m  Warning: No MCP servers connected successfully\x1B[0m")}else if(Object.keys(x).length>0)console.log(`\x1B[90m  MCP config loaded but all ${Object.keys(x).length} server(s) are disabled\x1B[0m`)}let A=[...Az,...tz(T)],q=await k(process.cwd()),H=z.systemPrompt||await YW(q);if(z.appendSystemPrompt)H+=`

${z.appendSystemPrompt}`;if(z.teammateMode&&z.teamName)H+=`

You are running as a teammate agent in the "${z.teamName}" team.`,H+=`
Agent ID: ${z.agentId}`,H+=`
Agent Name: ${z.agentName}`;let L=[],N;if(z.resumeSession){let B=await W.resumeSession(z.resumeSession);if(!B)console.error(`Error: Session not found: ${z.resumeSession}`),process.exit(1);L=B.messages,N=z.resumeSession,z.model=B.metadata.model,z.agentName=B.metadata.agentName,z.agentColor=B.metadata.agentColor,z.teamName=B.metadata.teamName,console.log(`\x1B[90mResumed session: ${z.resumeSession}\x1B[0m`),console.log(`\x1B[90mModel: ${z.model} | Messages: ${L.length}\x1B[0m
`)}else N=await W.createSession({model:z.model,workingDirectory:process.cwd(),agentName:z.agentName,agentColor:z.agentColor,teamName:z.teamName});let G=z.query,j=process.argv[2];if(!G&&process.argv.length>2&&j&&!j.startsWith("-"))G=process.argv.slice(2).join(" ");if(!G)console.log("Coder v0.1.0"),console.log(`Session: ${N}`),console.log(`Type your message or /help for commands.
`),await WW(X,z,H,A,J,U,W,L,N,T);else await XW(X,z,H,A,G,W,N)}async function WW(z,W,X,Y,$,Q,K,J,U,E){let R=process.stdin.isTTY,O=process.env.CLAUDE_FORCE_INTERACTIVE==="true";if(!R&&!O){console.error("Error: Interactive mode requires a TTY. Use -q for single query mode."),console.error("       Or set CLAUDE_FORCE_INTERACTIVE=true for testing.");return}let T=!0,_=0,x=await k(process.cwd()),A=rz("readline").createInterface({input:process.stdin,output:process.stdout,terminal:!0,historySize:1000,removeHistoryDuplicates:!0});process.on("SIGINT",()=>{console.log(`
\x1B[90mGoodbye!\x1B[0m`),A.close(),process.exit(0)});let q=(L)=>{return new Promise((N,G)=>{if(A.closed){G(Error("Readline closed"));return}A.question(L,(j)=>{N(j)})})},H=async(L)=>{if(console.log(`
\x1B[36m\u2501\u2501\u2501 Permission Required \u2501\u2501\u2501\x1B[0m`),console.log(`Tool: \x1B[1m${L.toolName}\x1B[0m`),console.log(`Risk: \x1B[32m${L.riskLevel.toUpperCase()}\x1B[0m`),console.log(`Action: ${L.description}`),L.file)console.log(`File: ${L.file}`);else if(L.command)console.log(`Command: ${L.command}`);else if(L.toolInput.file_path)console.log(`File: ${L.toolInput.file_path}`);else if(L.toolInput.command)console.log(`Command: ${L.toolInput.command}`);while(!0)try{switch((await q(`
Allow? [y]es / [n]o / [a]lways / [d]eny always: `)).trim().toLowerCase()){case"y":case"yes":case"":return{decision:"allow"};case"n":case"no":return{decision:"deny",reason:"User denied"};case"a":case"always":return{decision:"allowAlways"};case"d":case"deny":return{decision:"denyAlways",reason:"User denied always"};default:console.log("Please enter y, n, a, or d")}}catch{return{decision:"deny",reason:"Input error"}}};while(T)try{let L=await q(`
\x1B[1;36mYou:\x1B[0m `);if(!L.trim())continue;if(L.startsWith("/")){let F=L.slice(1).split(" ")[0]??"",b=L.slice(F.length+2);switch(F){case"exit":case"quit":case"q":T=!1,console.log("\x1B[90mGoodbye!\x1B[0m");continue;case"help":case"?":console.log(`
\x1B[1mCommands:\x1B[0m
  /help, /?              Show this help
  /exit, /quit, /q       Exit the session
  /clear                 Clear conversation history
  /compact               Force context compaction
  /model <model>         Switch model
  /tools                 List available tools
  /mcp                   List MCP servers and tools
  /skills                List available skills
  /cost                  Show total cost
  /status                Show session status

\x1B[1mCheckpoints (chat + code):\x1B[0m
  /checkpoint <label>    Save checkpoint (chat + files)
  /checkpoints           List saved checkpoints
  /restore <id>          Restore checkpoint (asks about files)
  /restore-chat <id>     Restore chat only (no files)
  /undo                  Go back to previous checkpoint
  /redo                  Go forward after undo
  /cps-status            Show checkpoint navigation status

\x1B[1mExport:\x1B[0m
  /export [format]       Export session (jsonl/json/md)
`);continue;case"clear":J.length=0,console.log("\x1B[90mConversation cleared.\x1B[0m");continue;case"compact":console.log("\x1B[90mForcing context compaction...\x1B[0m");continue;case"model":if(b)W.model=b,console.log(`\x1B[90mSwitched to model: ${b}\x1B[0m`);else console.log(`Current model: \x1B[1m${W.model}\x1B[0m`);continue;case"tools":console.log("\x1B[1mAvailable tools:\x1B[0m");for(let Z of Y){let V=Z.description.split(".")[0]??Z.description;console.log(`  \x1B[33m${Z.name}\x1B[0m: ${V}`)}continue;case"mcp":if(E.size===0)console.log("\x1B[90mNo MCP servers connected.\x1B[0m"),console.log("\x1B[90mUse --mcp-config to specify a config file.\x1B[0m");else{console.log("\x1B[1mConnected MCP Servers:\x1B[0m");for(let[Z,V]of E){let P=V.connected?"\x1B[32m\u25CF\x1B[0m":"\x1B[31m\u25CB\x1B[0m";console.log(`  ${P} \x1B[1m${Z}\x1B[0m (${V.tools.length} tools)`);for(let D of V.tools)console.log(`      \x1B[33m${D.name}\x1B[0m: ${D.description.slice(0,50)}...`)}}continue;case"skills":let M=Q.getAll();if(M.length===0)console.log("\x1B[90mNo skills loaded.\x1B[0m");else{console.log("\x1B[1mAvailable skills:\x1B[0m");for(let Z of M){let V=Z.description??Z.prompt.slice(0,50);console.log(`  \x1B[33m/${Z.name}\x1B[0m: ${V}...`)}}continue;case"cost":console.log(`Total cost: \x1B[1m${l(_)}\x1B[0m`);continue;case"status":case"session":console.log("\x1B[1mSession Status:\x1B[0m"),console.log(`  ID: ${U}`),console.log(`  Model: ${W.model}`),console.log(`  Messages: ${J.length}`),console.log(`  Total cost: ${l(_)}`),console.log(`  Permission mode: ${W.permissionMode}`);continue;case"export":try{let Z=b||"markdown",V=await K.exportSession(U,Z);console.log(`\x1B[90mSession exported to: ${V}\x1B[0m`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mExport failed: ${V}\x1B[0m`)}continue;case"checkpoint":case"cp":if(!b){console.log("\x1B[31mUsage: /checkpoint <label>\x1B[0m"),console.log("\x1B[90mExample: /checkpoint before-refactor\x1B[0m"),console.log("\x1B[90mCreates checkpoint with chat history + file snapshots\x1B[0m");continue}try{let Z=await t(U,J,{label:b,model:W.model,workingDirectory:process.cwd(),totalCost:_,trackFiles:!0});await Xz(U,Z.id);let V=zz(Z);if(console.log(`\x1B[32m\u2713 Checkpoint saved:\x1B[0m ${v(Z)}`),V)console.log(`\x1B[90m  ${V}\x1B[0m`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to create checkpoint: ${V}\x1B[0m`)}continue;case"checkpoints":case"cps":try{let Z=await e(U);s(Z)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to list checkpoints: ${V}\x1B[0m`)}continue;case"restore":case"rollback":case"rewind":if(!b){console.log("\x1B[31mUsage: /${command} <checkpoint-id>\x1B[0m"),console.log("\x1B[90mUse /checkpoints to see available checkpoints\x1B[0m");continue}try{let Z=b.trim(),V=await g(U,Z);if(!V){console.log(`\x1B[31mCheckpoint not found: ${Z}\x1B[0m`),console.log("\x1B[90mUse /checkpoints to see available checkpoints\x1B[0m");continue}console.log(`
\x1B[1mRestoring checkpoint:\x1B[0m ${v(V)}`);let P=V.files.length>0,D=!1;if(P){console.log(`\x1B[33m${V.files.length} file(s) saved in checkpoint:\x1B[0m`);for(let qz of V.files.slice(0,5))console.log(`  - ${qz.path}`);if(V.files.length>5)console.log(`  ... and ${V.files.length-5} more`);D=(await q(`
\x1B[36mRestore files too? [Y/n]: \x1B[0m`)).trim().toLowerCase()!=="n"}let C=await I(V,{restoreFiles:D,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...C.messages),_=V.metadata.totalCost,console.log(`
\x1B[32m\u2713 Checkpoint restored:\x1B[0m`),console.log(`  Messages: ${J.length}`),D&&P){if(console.log(`  Files restored: ${C.filesRestored}`),C.filesFailed>0)console.log(`  \x1B[33mFiles failed: ${C.filesFailed}\x1B[0m`)}console.log(`  Cost reset to: $${_.toFixed(4)}`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to restore checkpoint: ${V}\x1B[0m`)}continue;case"restore-chat":if(!b){console.log("\x1B[31mUsage: /restore-chat <checkpoint-id>\x1B[0m"),console.log("\x1B[90mRestores chat only, no files\x1B[0m");continue}try{let Z=b.trim(),V=await g(U,Z);if(!V){console.log(`\x1B[31mCheckpoint not found: ${Z}\x1B[0m`);continue}let P=await I(V,{restoreFiles:!1,restoreMessages:!0});J.length=0,J.push(...P.messages),_=V.metadata.totalCost,console.log(`\x1B[32m\u2713 Chat restored:\x1B[0m ${J.length} messages (no files changed)`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to restore chat: ${V}\x1B[0m`)}continue;case"undo":try{let Z=await Yz(U);if(!Z.checkpoint){console.log("\x1B[33mNothing to undo\x1B[0m");continue}let V=await I(Z.checkpoint,{restoreFiles:!0,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...V.messages),_=Z.checkpoint.metadata.totalCost,console.log(`\x1B[32m\u2713 Undone to:\x1B[0m ${v(Z.checkpoint)}`),console.log(`\x1B[90mMessages: ${J.length} | Files: ${V.filesRestored}\x1B[0m`),Z.canRedo)console.log("\x1B[90mUse /redo to go forward\x1B[0m")}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mUndo failed: ${V}\x1B[0m`)}continue;case"redo":try{let Z=await Zz(U);if(!Z.checkpoint){console.log("\x1B[33mNothing to redo\x1B[0m");continue}let V=await I(Z.checkpoint,{restoreFiles:!0,restoreMessages:!0,workingDirectory:process.cwd()});if(J.length=0,J.push(...V.messages),_=Z.checkpoint.metadata.totalCost,console.log(`\x1B[32m\u2713 Redone to:\x1B[0m ${v(Z.checkpoint)}`),console.log(`\x1B[90mMessages: ${J.length} | Files: ${V.filesRestored}\x1B[0m`),Z.canRedo)console.log("\x1B[90mUse /redo to go forward again\x1B[0m")}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mRedo failed: ${V}\x1B[0m`)}continue;case"checkpoint-status":case"cps-status":try{let Z=await $z(U);if(console.log("\x1B[1mCheckpoint Navigation:\x1B[0m"),console.log(`  Position: ${Z.current}/${Z.total}`),console.log(`  Can undo: ${Z.canUndo?"\x1B[32myes\x1B[0m":"\x1B[31mno\x1B[0m"}`),console.log(`  Can redo: ${Z.canRedo?"\x1B[32myes\x1B[0m":"\x1B[31mno\x1B[0m"}`),Z.currentId)console.log(`  Current: ${Z.currentId}`)}catch(Z){let V=Z instanceof Error?Z.message:String(Z);console.error(`\x1B[31mFailed to get status: ${V}\x1B[0m`)}continue;default:let y=Q.get(F);if(y){console.log(`\x1B[90mLoading skill: ${y.name}\x1B[0m`),X+=`

`+Tz(y);continue}console.log(`\x1B[31mUnknown command: /${F}\x1B[0m`),console.log("\x1B[90mType /help for available commands.\x1B[0m");continue}}J.push({role:"user",content:[{type:"text",text:L}]}),await K.saveMessage(J[J.length-1]),process.stdout.write(`
\x1B[1;35mClaude:\x1B[0m `);let N=W.extendedThinking?{enabled:!0,effort:W.effort??"medium",interleaved:W.interleaved??!0}:void 0,G=await n(J,{apiKey:z,model:W.model,maxTokens:W.maxTokens,systemPrompt:X,tools:Y,permissionMode:W.permissionMode,workingDirectory:process.cwd(),gitStatus:x,extendedThinking:N,onText:(B)=>{process.stdout.write(B)},onThinking:(B)=>{process.stdout.write(`\x1B[90m${B}\x1B[0m`)},onToolUse:(B)=>{process.stdout.write(`
\x1B[90m[Trying: ${B.name}]\x1B[0m `)},onToolResult:(B)=>{if(B.result.is_error)process.stdout.write("\x1B[31m[Error]\x1B[0m ")},onMetrics:async(B)=>{console.log(`
\x1B[90m${i(B)}\x1B[0m`),await K.saveMetrics(B)},onPermissionRequest:async(B)=>{return await H({toolName:B.toolName,toolInput:B.toolInput,riskLevel:B.riskLevel,description:B.description,file:B.file,command:B.command})}}),j=G.messages[G.messages.length-1];if(j&&j.role==="assistant")await K.saveMessage(j);J.length=0,J.push(...G.messages),_+=G.totalCost}catch(L){if(L instanceof Error&&L.message==="Readline closed")break;let N=L instanceof Error?L.message:String(L);console.error(`
\x1B[31mError: ${N}\x1B[0m`)}A.close()}async function XW(z,W,X,Y,$,Q,K){let J=W.loop??!1,U=W.maxIterations??10,R=[{role:"user",content:[{type:"text",text:J?`IMPORTANT: You MUST use the available tools (Read, Bash, Glob, Grep, etc.) to actually perform the task. Do not just describe what you would do - execute the tools to get real results.

Task: ${$}`:$}]}];await Q.saveMessage(R[0]);let O=await k(process.cwd()),T=W.extendedThinking?{enabled:!0,effort:W.effort??"medium",interleaved:W.interleaved??!0}:void 0,_=0,x=0;try{while(!0){if(_++,J)console.log(`
\x1B[36m\u2501\u2501\u2501 Iteration ${_}/${U} \u2501\u2501\u2501\x1B[0m`);let A=await n(R,{apiKey:z,model:W.model,maxTokens:W.maxTokens,systemPrompt:X,tools:Y,permissionMode:W.permissionMode,workingDirectory:process.cwd(),gitStatus:O,extendedThinking:T,onText:(H)=>{process.stdout.write(H)},onThinking:(H)=>{process.stdout.write(`\x1B[90m${H}\x1B[0m`)},onMetrics:async(H)=>{console.log(`
\x1B[90m${i(H)}\x1B[0m`),await Q.saveMetrics(H)}}),q=A.messages[A.messages.length-1];if(q&&q.role==="assistant")await Q.saveMessage(q);if(x+=A.totalCost,R.length=0,R.push(...A.messages),J){let H=A.messages.filter((G)=>G.role==="assistant").pop(),L=H?.content?.some((G)=>G.type==="tool_use"),N=H?.content?.some((G)=>G.type==="tool_result");if(!L&&!N){console.log(`
\x1B[32m\u2713 Task completed in ${_} iteration(s)\x1B[0m`);break}if(_>=U){console.log(`
\x1B[33m\u26A0 Max iterations (${U}) reached\x1B[0m`),console.log("\x1B[90mTask may not be fully complete. Use --max-iterations to increase.\x1B[0m");break}R.push({role:"user",content:[{type:"text",text:"Continue working on the task. If you believe the task is complete, summarize what was done."}]})}else break}console.log(`
\x1B[90mSession: ${K}\x1B[0m`),console.log(`\x1B[90mTotal cost: ${l(x)}\x1B[0m`)}catch(A){let q=A instanceof Error?A.message:String(A);console.error(`Error: ${q}`),process.exit(1)}}async function YW(z){let W=`You are Claude Code, an AI coding assistant created by Anthropic.

You help users with software engineering tasks:
- Reading, writing, and editing code
- Running commands and scripts
- Searching and exploring codebases
- Debugging and fixing issues

Guidelines:
1. Be helpful, direct, and thorough
2. Explain your reasoning when asked
3. Follow user preferences and project conventions
4. Use tools effectively to accomplish tasks
5. Ask clarifying questions when needed

Available tools:
- Read: Read file contents
- Write: Write new files
- Edit: Make precise edits to files
- Bash: Execute shell commands
- Glob: Find files by pattern
- Grep: Search file contents

Working directory: ${process.cwd()}`;if(z){if(W+=`

Git Status:`,W+=`
Branch: ${z.branch}`,z.ahead>0||z.behind>0)W+=` (${z.ahead} ahead, ${z.behind} behind)`;if(z.staged.length>0||z.unstaged.length>0||z.untracked.length>0)W+=`
Changes: ${z.staged.length} staged, ${z.unstaged.length} unstaged, ${z.untracked.length} untracked`}let X=await Jz();if(X)W+=`

${X}`;return W}zW().catch((z)=>{console.error("Fatal error:",z),process.exit(1)});
