@cdoing/opentuicli 0.1.21 → 0.1.26

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/README.md CHANGED
@@ -5,20 +5,16 @@
5
5
 
6
6
  Lightweight terminal interface for [Cdoing Agent](https://github.com/awaisshah228/cdoing-agent) — built on the OpenTUI framework. An open-source, multi-provider AI coding assistant.
7
7
 
8
- ## Requirements
9
-
10
- **[Bun](https://bun.sh) is required.** This package uses the OpenTUI framework which relies on Bun-native terminal rendering APIs and does not work with Node.js.
11
-
12
- If you need Node.js compatibility, use [`@cdoing/cli`](https://www.npmjs.com/package/@cdoing/cli) instead (same agent, Ink-based UI).
13
-
14
8
  ## Installation
15
9
 
16
10
  ```bash
17
- # Bun (required)
18
- bun install -g @cdoing/opentuicli
11
+ # Install globally (no Bun required — standalone binary with embedded runtime)
12
+ npm install -g @cdoing/opentuicli
19
13
 
20
- # Install Bun if you don't have it
21
- curl -fsSL https://bun.sh/install | bash
14
+ # Or with other package managers
15
+ yarn global add @cdoing/opentuicli
16
+ pnpm add -g @cdoing/opentuicli
17
+ bun install -g @cdoing/opentuicli
22
18
  ```
23
19
 
24
20
  ## Quick Start
@@ -34,15 +30,28 @@ cdoing-tui "refactor this function to use async/await"
34
30
  cdoing-tui --provider openrouter --model anthropic/claude-sonnet-4
35
31
  ```
36
32
 
33
+ ## How It Works
34
+
35
+ The published package includes a **standalone compiled binary** with the Bun runtime embedded — no Bun, Node.js, or any runtime needed to run it. Install with any package manager (`npm`, `yarn`, `pnpm`, or `bun`). This is the same approach used by [opencode](https://github.com/opencode-ai/opencode).
36
+
37
+ For development, you need [Bun](https://bun.sh) to build from source:
38
+
39
+ ```bash
40
+ # Build for current platform
41
+ bun run build
42
+
43
+ # Build for all platforms (linux, macOS, windows × arm64/x64)
44
+ bun run build:all
45
+ ```
46
+
37
47
  ## Why OpenTUI?
38
48
 
39
49
  This is the **lightweight alternative** to `@cdoing/cli`. While the main CLI uses Ink + React for a rich terminal UI, this package uses the OpenTUI framework for a minimal, fast, keyboard-driven experience.
40
50
 
41
51
  | | `@cdoing/cli` | `@cdoing/opentuicli` |
42
52
  |---|---|---|
43
- | **Runtime** | Node.js (npm/yarn/pnpm) | **Bun only** |
44
- | **UI Framework** | Ink + React | OpenTUI |
45
- | **Bundle size** | Larger | Smaller |
53
+ | **Runtime** | Node.js | **Standalone binary** |
54
+ | **UI Framework** | Ink + React | OpenTUI + React |
46
55
  | **Startup time** | ~1s | ~0.5s |
47
56
  | **Features** | Full (tabs, history) | Essential |
48
57
  | **Best for** | Daily use | Quick tasks, low-resource |
package/package.json CHANGED
@@ -1,21 +1,25 @@
1
1
  {
2
2
  "name": "@cdoing/opentuicli",
3
- "version": "0.1.21",
3
+ "version": "0.1.26",
4
4
  "description": "OpenTUI-based terminal interface for cdoing agent (inspired by opencode's TUI)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
8
  "bin": {
9
- "cdoing-tui": "dist/index.js"
9
+ "cdoing-tui": "dist/cdoing-tui-current/bin/cdoing-tui"
10
10
  },
11
+ "files": [
12
+ "dist/"
13
+ ],
11
14
  "scripts": {
12
- "build": "node esbuild.config.cjs",
15
+ "build": "bun run build.ts --single",
16
+ "build:all": "bun run build.ts",
13
17
  "typecheck": "tsc --noEmit",
14
- "dev": "node esbuild.config.cjs --watch",
15
- "start": "bun dist/index.js",
18
+ "dev": "bun --watch src/index.ts",
19
+ "start": "./dist/cdoing-tui-current/bin/cdoing-tui",
16
20
  "clean": "rm -rf dist"
17
21
  },
18
- "dependencies": {
22
+ "devDependencies": {
19
23
  "@cdoing/ai": "*",
20
24
  "@cdoing/core": "*",
21
25
  "@opentui/core": "0.1.87",
@@ -23,9 +27,8 @@
23
27
  "chalk": "^4.1.2",
24
28
  "commander": "^13.1.0",
25
29
  "react": "^19.1.0",
26
- "zustand": "^5.0.12"
27
- },
28
- "devDependencies": {
30
+ "zustand": "^5.0.12",
31
+ "@types/bun": "^1.3.10",
29
32
  "@types/node": "^22.13.10",
30
33
  "@types/react": "^19.1.0",
31
34
  "esbuild": "^0.25.0",
package/dist/index.js DELETED
@@ -1,64 +0,0 @@
1
- #!/usr/bin/env node
2
- var br=Object.defineProperty;var Je=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,o)=>(typeof require<"u"?require:n)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var K=(e,n)=>()=>(e&&(n=e(e=0)),n);var pr=(e,n)=>{for(var o in n)br(e,o,{get:n[o],enumerable:!0})};var Sn,vn,Gt=K(()=>{Sn=e=>{let n,o=new Set,t=(h,b)=>{let d=typeof h=="function"?h(n):h;if(!Object.is(d,n)){let D=n;n=b??(typeof d!="object"||d===null)?d:Object.assign({},n,d),o.forEach(y=>y(n,D))}},i=()=>n,a={setState:t,getState:i,getInitialState:()=>l,subscribe:h=>(o.add(h),()=>o.delete(h))},l=n=e(t,i,a);return a},vn=(e=>e?Sn(e):Sn)});import St from"react";function Sr(e,n=yr){let o=St.useSyncExternalStore(e.subscribe,St.useCallback(()=>n(e.getState()),[e,n]),St.useCallback(()=>n(e.getInitialState()),[e,n]));return St.useDebugValue(o),o}var yr,wn,Dn,kn=K(()=>{Gt();yr=e=>e;wn=e=>{let n=vn(e),o=t=>Sr(n,t);return Object.assign(o,n),o},Dn=(e=>e?wn(e):wn)});var Cn=K(()=>{Gt();kn()});function Wt(e,n){let o;try{o=e()}catch{return}return{getItem:i=>{var r;let c=l=>l===null?null:JSON.parse(l,n?.reviver),a=(r=o.getItem(i))!=null?r:null;return a instanceof Promise?a.then(c):c(a)},setItem:(i,r)=>o.setItem(i,JSON.stringify(r,n?.replacer)),removeItem:i=>o.removeItem(i)}}var Ut,vr,Mn,Tn=K(()=>{Ut=e=>n=>{try{let o=e(n);return o instanceof Promise?o:{then(t){return Ut(t)(o)},catch(t){return this}}}catch(o){return{then(t){return this},catch(t){return Ut(t)(o)}}}},vr=(e,n)=>(o,t,i)=>{let r={storage:Wt(()=>window.localStorage),partialize:f=>f,version:0,merge:(f,g)=>({...g,...f}),...n},c=!1,a=0,l=new Set,h=new Set,b=r.storage;if(!b)return e((...f)=>{console.warn(`[zustand persist middleware] Unable to update item '${r.name}', the given storage is currently unavailable.`),o(...f)},t,i);let d=()=>{let f=r.partialize({...t()});return b.setItem(r.name,{state:f,version:r.version})},D=i.setState;i.setState=(f,g)=>(D(f,g),d());let y=e((...f)=>(o(...f),d()),t,i);i.getInitialState=()=>y;let k,N=()=>{var f,g;if(!b)return;let T=++a;c=!1,l.forEach(R=>{var F;return R((F=t())!=null?F:y)});let I=((g=r.onRehydrateStorage)==null?void 0:g.call(r,(f=t())!=null?f:y))||void 0;return Ut(b.getItem.bind(b))(r.name).then(R=>{if(R)if(typeof R.version=="number"&&R.version!==r.version){if(r.migrate){let F=r.migrate(R.state,R.version);return F instanceof Promise?F.then(L=>[!0,L]):[!0,F]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,R.state];return[!1,void 0]}).then(R=>{var F;if(T!==a)return;let[L,v]=R;if(k=r.merge(v,(F=t())!=null?F:y),o(k,!0),L)return d()}).then(()=>{T===a&&(I?.(t(),void 0),k=t(),c=!0,h.forEach(R=>R(k)))}).catch(R=>{T===a&&I?.(void 0,R)})};return i.persist={setOptions:f=>{r={...r,...f},f.storage&&(b=f.storage)},clearStorage:()=>{b?.removeItem(r.name)},getOptions:()=>r,rehydrate:()=>N(),hasHydrated:()=>c,onHydrate:f=>(l.add(f),()=>{l.delete(f)}),onFinishHydration:f=>(h.add(f),()=>{h.delete(f)})},r.skipHydration||N(),k||y},Mn=vr});import*as fe from"fs";import*as vt from"path";import*as $n from"os";var ke,wr,se,qt=K(()=>{"use strict";Cn();Tn();ke=vt.join($n.homedir(),".cdoing","tui-settings.json"),wr={getItem:e=>{try{if(!fe.existsSync(ke))return null;let n=JSON.parse(fe.readFileSync(ke,"utf-8"));return JSON.stringify(n[e]??null)}catch{return null}},setItem:(e,n)=>{try{let o=vt.dirname(ke);fe.existsSync(o)||fe.mkdirSync(o,{recursive:!0});let t={};try{fe.existsSync(ke)&&(t=JSON.parse(fe.readFileSync(ke,"utf-8")))}catch{}t[e]=JSON.parse(n),fe.writeFileSync(ke,JSON.stringify(t,null,2),"utf-8")}catch{}},removeItem:e=>{try{if(!fe.existsSync(ke))return;let n=JSON.parse(fe.readFileSync(ke,"utf-8"));delete n[e],fe.writeFileSync(ke,JSON.stringify(n,null,2),"utf-8")}catch{}}},se=Dn()(Mn(e=>({themeId:"vercel",mode:"dark",syncTerminalBg:!0,sidebarMode:"auto",provider:"anthropic",model:"",setThemeId:n=>e({themeId:n}),setMode:n=>e({mode:n}),setSyncTerminalBg:n=>e({syncTerminalBg:n}),setSidebarMode:n=>e({sidebarMode:n}),setProvider:n=>e({provider:n}),setModel:n=>e({model:n})}),{name:"tui-settings",storage:Wt(()=>wr),partialize:e=>({themeId:e.themeId,mode:e.mode,syncTerminalBg:e.syncTerminalBg,sidebarMode:e.sidebarMode,provider:e.provider,model:e.model})}))});import{RGBA as Kt,rgbToHex as Dr,SyntaxStyle as kr}from"@opentui/core";import{createContext as Cr,useContext as Mr,useState as rt,useEffect as Tr,useRef as wt,useMemo as $r}from"react";import{jsx as Rr}from"@opentui/react/jsx-runtime";function Z(e){return Kt.fromHex(e)}function _(e){return{text:Z(e.text),textMuted:Z(e.textMuted),textDim:Z(e.textDim),primary:Z(e.primary),secondary:Z(e.secondary),success:Z(e.success),error:Z(e.error),warning:Z(e.warning),info:Z(e.info),border:Z(e.border),borderFocused:Z(e.primary),bg:Z(e.bg),bgSubtle:Z(e.bgSubtle),userText:Z(e.success),assistantText:Z(e.text),systemText:Z(e.warning),toolText:Z(e.textMuted),toolRunning:Z(e.warning),toolDone:Z(e.success),toolError:Z(e.error),diffAdd:Z(e.diffAdd||e.success),diffRemove:Z(e.diffRemove||e.error),diffHunk:Z(e.info)}}function An(){return Object.keys(Ye).sort((e,n)=>e==="default"?-1:n==="default"?1:e.localeCompare(n))}function Re(e,n){let o=Ye[e]||Ye.default;return n==="light"?o.light:o.dark}function Ar(e,n,o){let[t,i,r]=[e,n,o].map(c=>{let a=c/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)});return .2126*t+.7152*i+.0722*r}function Or(){return new Promise(e=>{if(!process.stdin.isTTY||!process.stdout.isTTY){e(null);return}let n=setTimeout(()=>{i(),e(null)},500),o="",t=c=>{o+=c.toString();let a=o.match(/\x1b\]11;rgb:([0-9a-fA-F]{2,4})\/([0-9a-fA-F]{2,4})\/([0-9a-fA-F]{2,4})/);if(a){i();let l=h=>h.length<=2?parseInt(h,16):Math.round(parseInt(h,16)/65535*255);e({r:l(a[1]),g:l(a[2]),b:l(a[3])})}},i=()=>{clearTimeout(n),process.stdin.removeListener("data",t),r===!1&&process.stdin.setRawMode(!1)},r=process.stdin.isRaw;try{process.stdin.setRawMode(!0)}catch{e(null);return}process.stdin.on("data",t),process.stdout.write("\x1B]11;?\x07")})}function Pr(){let e=process.env.COLORFGBG;if(e){let n=e.split(";");if(parseInt(n[n.length-1]||"0",10)>8)return"light"}return"dark"}async function On(){if(it)return it;let e=await Or();return e?it=Ar(e.r,e.g,e.b)>.5?"light":"dark":it=Pr(),it}function Ve(e){if(!process.stdout.isTTY)return;let n=Dr(e);process.stdout.write(`\x1B]11;${n}\x07`)}function Dt(){process.stdout.isTTY&&process.stdout.write("\x1B]111;\x07")}function Ir(e){return kr.fromStyles({default:{fg:e.text},"markup.heading.1":{fg:e.primary,bold:!0},"markup.heading.2":{fg:e.primary,bold:!0},"markup.heading.3":{fg:e.info,bold:!0},"markup.heading.4":{fg:e.info,bold:!0},"markup.heading.5":{fg:e.info},"markup.heading.6":{fg:e.info},"markup.bold":{bold:!0},"markup.italic":{italic:!0},"markup.list":{fg:e.warning},"markup.link":{fg:e.info,underline:!0},"markup.raw":{fg:e.warning},"markup.quote":{fg:e.textMuted,italic:!0},keyword:{fg:e.secondary,bold:!0},"keyword.control":{fg:e.secondary,bold:!0},"keyword.operator":{fg:e.secondary},string:{fg:e.success},"string.quoted":{fg:e.success},comment:{fg:e.textDim,italic:!0},"comment.line":{fg:e.textDim,italic:!0},"comment.block":{fg:e.textDim,italic:!0},constant:{fg:e.warning},"constant.numeric":{fg:e.warning},number:{fg:e.warning},variable:{fg:e.text},"variable.parameter":{fg:e.text},function:{fg:e.info},"entity.name.function":{fg:e.info},"support.function":{fg:e.info},type:{fg:e.primary},"entity.name.type":{fg:e.primary},"support.type":{fg:e.primary},operator:{fg:e.textMuted},punctuation:{fg:e.textMuted}})}function In(e){let n=e.mode==="light"?"light":e.mode==="auto"&&e.detectedMode||"dark",o=e.themeId||"vercel",[t,i]=rt(o),[r,c]=rt(n),[a,l]=rt(Re(o,n)),[h,b]=rt(e.syncTerminalBg??!1),[d,D]=rt(null),y=wt(h);y.current=h;let k=wt(d);k.current=d;let N=wt(r);N.current=r;let f=wt(t);f.current=t;let g=v=>{y.current&&(k.current?Ve(Kt.fromHex(k.current)):Ve(v.bg))},T=v=>{i(v),f.current=v;let M=Re(v,N.current);l(M),g(M),se.getState().setThemeId(v)},I=v=>{c(v),N.current=v;let M=Re(f.current,v);l(M),g(M),se.getState().setMode(v)},R=v=>{D(v),k.current=v,y.current&&Ve(v?Kt.fromHex(v):Re(f.current,N.current).bg)},F=v=>{if(b(v),y.current=v,v){let M=Re(f.current,N.current);g(M)}else Dt();se.getState().setSyncTerminalBg(v)};Tr(()=>{if(y.current){let v=Re(o,n);g(v)}return()=>{y.current&&Dt()}},[]);let L=$r(()=>Ir(a),[a]);return Rr(Pn.Provider,{value:{theme:a,themeId:t,mode:r,syntaxStyle:L,customBg:d,setThemeId:T,setMode:I,setCustomBg:R,syncTerminalBg:h,setSyncTerminalBg:F},children:e.children})}function G(){let e=Mr(Pn);if(!e)throw new Error("useTheme must be used within ThemeProvider");return e}var Ye,it,Pn,te=K(()=>{"use strict";qt();Ye={default:{name:"Default",dark:_({bg:"#000000",bgSubtle:"#111111",text:"#e5e7eb",textMuted:"#9ca3af",textDim:"#6b7280",primary:"#06b6d4",secondary:"#8b5cf6",success:"#22c55e",error:"#ef4444",warning:"#eab308",info:"#3b82f6",border:"#374151"}),light:_({bg:"#ffffff",bgSubtle:"#f3f4f6",text:"#1f2937",textMuted:"#6b7280",textDim:"#9ca3af",primary:"#0891b2",secondary:"#7c3aed",success:"#16a34a",error:"#dc2626",warning:"#ca8a04",info:"#2563eb",border:"#d1d5db"})},catppuccin:{name:"Catppuccin",dark:_({bg:"#1e1e2e",bgSubtle:"#313244",text:"#cdd6f4",textMuted:"#a6adc8",textDim:"#6c7086",primary:"#89b4fa",secondary:"#cba6f7",success:"#a6e3a1",error:"#f38ba8",warning:"#f9e2af",info:"#74c7ec",border:"#45475a"}),light:_({bg:"#eff1f5",bgSubtle:"#e6e9ef",text:"#4c4f69",textMuted:"#6c6f85",textDim:"#9ca0b0",primary:"#1e66f5",secondary:"#8839ef",success:"#40a02b",error:"#d20f39",warning:"#df8e1d",info:"#04a5e5",border:"#ccd0da"})},dracula:{name:"Dracula",dark:_({bg:"#282a36",bgSubtle:"#44475a",text:"#f8f8f2",textMuted:"#6272a4",textDim:"#44475a",primary:"#bd93f9",secondary:"#ff79c6",success:"#50fa7b",error:"#ff5555",warning:"#f1fa8c",info:"#8be9fd",border:"#44475a"}),light:_({bg:"#f8f8f2",bgSubtle:"#e6e6e6",text:"#282a36",textMuted:"#6272a4",textDim:"#999999",primary:"#7c3aed",secondary:"#d946ef",success:"#16a34a",error:"#dc2626",warning:"#ca8a04",info:"#0891b2",border:"#d1d5db"})},nord:{name:"Nord",dark:_({bg:"#2e3440",bgSubtle:"#3b4252",text:"#eceff4",textMuted:"#d8dee9",textDim:"#4c566a",primary:"#88c0d0",secondary:"#b48ead",success:"#a3be8c",error:"#bf616a",warning:"#ebcb8b",info:"#81a1c1",border:"#434c5e"}),light:_({bg:"#eceff4",bgSubtle:"#e5e9f0",text:"#2e3440",textMuted:"#4c566a",textDim:"#7b88a1",primary:"#5e81ac",secondary:"#b48ead",success:"#a3be8c",error:"#bf616a",warning:"#ebcb8b",info:"#81a1c1",border:"#d8dee9"})},tokyonight:{name:"Tokyo Night",dark:_({bg:"#1a1b26",bgSubtle:"#24283b",text:"#c0caf5",textMuted:"#a9b1d6",textDim:"#565f89",primary:"#7aa2f7",secondary:"#bb9af7",success:"#9ece6a",error:"#f7768e",warning:"#e0af68",info:"#7dcfff",border:"#3b4261"}),light:_({bg:"#d5d6db",bgSubtle:"#cbccd1",text:"#343b58",textMuted:"#565a6e",textDim:"#9699a3",primary:"#34548a",secondary:"#5a4a78",success:"#485e30",error:"#8c4351",warning:"#8f5e15",info:"#0f4b6e",border:"#b4b5b9"})},gruvbox:{name:"Gruvbox",dark:_({bg:"#282828",bgSubtle:"#3c3836",text:"#ebdbb2",textMuted:"#a89984",textDim:"#665c54",primary:"#fabd2f",secondary:"#d3869b",success:"#b8bb26",error:"#fb4934",warning:"#fe8019",info:"#83a598",border:"#504945"}),light:_({bg:"#fbf1c7",bgSubtle:"#f2e5bc",text:"#3c3836",textMuted:"#7c6f64",textDim:"#a89984",primary:"#b57614",secondary:"#8f3f71",success:"#79740e",error:"#9d0006",warning:"#af3a03",info:"#427b58",border:"#d5c4a1"})},rosepine:{name:"Ros\xE9 Pine",dark:_({bg:"#191724",bgSubtle:"#1f1d2e",text:"#e0def4",textMuted:"#908caa",textDim:"#6e6a86",primary:"#c4a7e7",secondary:"#ebbcba",success:"#31748f",error:"#eb6f92",warning:"#f6c177",info:"#9ccfd8",border:"#26233a"}),light:_({bg:"#faf4ed",bgSubtle:"#f2e9e1",text:"#575279",textMuted:"#797593",textDim:"#9893a5",primary:"#907aa9",secondary:"#d7827e",success:"#286983",error:"#b4637a",warning:"#ea9d34",info:"#56949f",border:"#dfdad9"})},monokai:{name:"Monokai",dark:_({bg:"#272822",bgSubtle:"#3e3d32",text:"#f8f8f2",textMuted:"#75715e",textDim:"#49483e",primary:"#66d9ef",secondary:"#ae81ff",success:"#a6e22e",error:"#f92672",warning:"#e6db74",info:"#66d9ef",border:"#49483e"}),light:_({bg:"#fafafa",bgSubtle:"#f0f0f0",text:"#272822",textMuted:"#75715e",textDim:"#b0b0b0",primary:"#0096d1",secondary:"#7c3aed",success:"#629e25",error:"#c4265e",warning:"#b5a21d",info:"#0096d1",border:"#d0d0d0"})},solarized:{name:"Solarized",dark:_({bg:"#002b36",bgSubtle:"#073642",text:"#839496",textMuted:"#657b83",textDim:"#586e75",primary:"#268bd2",secondary:"#6c71c4",success:"#859900",error:"#dc322f",warning:"#b58900",info:"#2aa198",border:"#073642"}),light:_({bg:"#fdf6e3",bgSubtle:"#eee8d5",text:"#657b83",textMuted:"#839496",textDim:"#93a1a1",primary:"#268bd2",secondary:"#6c71c4",success:"#859900",error:"#dc322f",warning:"#b58900",info:"#2aa198",border:"#eee8d5"})},amoled:{name:"AMOLED",dark:_({bg:"#000000",bgSubtle:"#0a0a0a",text:"#ffffff",textMuted:"#888888",textDim:"#555555",primary:"#00e5ff",secondary:"#e040fb",success:"#00e676",error:"#ff1744",warning:"#ffea00",info:"#40c4ff",border:"#222222"}),light:_({bg:"#ffffff",bgSubtle:"#f5f5f5",text:"#000000",textMuted:"#666666",textDim:"#aaaaaa",primary:"#0097a7",secondary:"#7b1fa2",success:"#2e7d32",error:"#c62828",warning:"#f9a825",info:"#0277bd",border:"#e0e0e0"})},github:{name:"GitHub",dark:_({bg:"#0d1117",bgSubtle:"#161b22",text:"#e6edf3",textMuted:"#8b949e",textDim:"#484f58",primary:"#58a6ff",secondary:"#bc8cff",success:"#3fb950",error:"#f85149",warning:"#d29922",info:"#58a6ff",border:"#30363d"}),light:_({bg:"#ffffff",bgSubtle:"#f6f8fa",text:"#1f2328",textMuted:"#656d76",textDim:"#8c959f",primary:"#0969da",secondary:"#8250df",success:"#1a7f37",error:"#cf222e",warning:"#9a6700",info:"#0969da",border:"#d0d7de"})},material:{name:"Material",dark:_({bg:"#263238",bgSubtle:"#37474f",text:"#eeffff",textMuted:"#b0bec5",textDim:"#546e7a",primary:"#82aaff",secondary:"#c792ea",success:"#c3e88d",error:"#ff5370",warning:"#ffcb6b",info:"#89ddff",border:"#37474f"}),light:_({bg:"#fafafa",bgSubtle:"#eeeeee",text:"#90a4ae",textMuted:"#546e7a",textDim:"#b0bec5",primary:"#6182b8",secondary:"#7c4dff",success:"#91b859",error:"#e53935",warning:"#f76d47",info:"#39adb5",border:"#d0d0d0"})},synthwave:{name:"Synthwave '84",dark:_({bg:"#262335",bgSubtle:"#34294f",text:"#ffffff",textMuted:"#bbbbbb",textDim:"#6d5da0",primary:"#ff7edb",secondary:"#36f9f6",success:"#72f1b8",error:"#fe4450",warning:"#fede5d",info:"#36f9f6",border:"#495495"}),light:_({bg:"#f5f0ff",bgSubtle:"#e8e0f0",text:"#262335",textMuted:"#6d5da0",textDim:"#a090c0",primary:"#b03090",secondary:"#108888",success:"#308050",error:"#c03030",warning:"#a08000",info:"#207080",border:"#d0c8e0"})},everforest:{name:"Everforest",dark:_({bg:"#2d353b",bgSubtle:"#343f44",text:"#d3c6aa",textMuted:"#859289",textDim:"#5c6a72",primary:"#a7c080",secondary:"#d699b6",success:"#a7c080",error:"#e67e80",warning:"#dbbc7f",info:"#7fbbb3",border:"#475258"}),light:_({bg:"#fdf6e3",bgSubtle:"#f3efda",text:"#5c6a72",textMuted:"#829181",textDim:"#a6b0a0",primary:"#8da101",secondary:"#df69ba",success:"#8da101",error:"#f85552",warning:"#dfa000",info:"#35a77c",border:"#e0dcc7"})},cobalt2:{name:"Cobalt2",dark:_({bg:"#193549",bgSubtle:"#1f4662",text:"#ffffff",textMuted:"#8db0cc",textDim:"#4d7ea0",primary:"#ffc600",secondary:"#ff9d00",success:"#3ad900",error:"#ff628c",warning:"#ffc600",info:"#80fcff",border:"#2a5a7a"}),light:_({bg:"#ffffff",bgSubtle:"#f0f0f0",text:"#193549",textMuted:"#4d7ea0",textDim:"#8db0cc",primary:"#b88d00",secondary:"#cc7a00",success:"#2ba600",error:"#cc4e70",warning:"#b88d00",info:"#0090a0",border:"#d0d0d0"})},kanagawa:{name:"Kanagawa",dark:_({bg:"#1F1F28",bgSubtle:"#2A2A37",text:"#DCD7BA",textMuted:"#727169",textDim:"#54546D",primary:"#7E9CD8",secondary:"#957FB8",success:"#98BB6C",error:"#E82424",warning:"#D7A657",info:"#76946A",border:"#54546D"}),light:_({bg:"#F2E9DE",bgSubtle:"#EAE4D7",text:"#54433A",textMuted:"#9E9389",textDim:"#B8AFA6",primary:"#2D4F67",secondary:"#957FB8",success:"#98BB6C",error:"#E82424",warning:"#D7A657",info:"#76946A",border:"#D4CBBF"})},nightowl:{name:"Night Owl",dark:_({bg:"#011627",bgSubtle:"#0b2942",text:"#d6deeb",textMuted:"#637777",textDim:"#44596b",primary:"#82aaff",secondary:"#c792ea",success:"#addb67",error:"#ef5350",warning:"#ffcb8b",info:"#7fdbca",border:"#1d3b53"}),light:_({bg:"#fbfbfb",bgSubtle:"#f0f0f0",text:"#403f53",textMuted:"#989fb1",textDim:"#c0c0c0",primary:"#4876d6",secondary:"#994cc3",success:"#4d804e",error:"#de3d3b",warning:"#e0af68",info:"#0c969b",border:"#d9d9d9"})},onedark:{name:"One Dark",dark:_({bg:"#282c34",bgSubtle:"#2c313c",text:"#abb2bf",textMuted:"#636d83",textDim:"#4b5263",primary:"#61afef",secondary:"#c678dd",success:"#98c379",error:"#e06c75",warning:"#e5c07b",info:"#56b6c2",border:"#3e4451"}),light:_({bg:"#fafafa",bgSubtle:"#f0f0f0",text:"#383a42",textMuted:"#a0a1a7",textDim:"#c0c0c0",primary:"#4078f2",secondary:"#a626a4",success:"#50a14f",error:"#e45649",warning:"#c18401",info:"#0184bc",border:"#d3d3d3"})},matrix:{name:"Matrix",dark:_({bg:"#0a0e0a",bgSubtle:"#0e130d",text:"#62ff94",textMuted:"#8ca391",textDim:"#3d4a44",primary:"#2eff6a",secondary:"#00efff",success:"#62ff94",error:"#ff4b4b",warning:"#e6ff57",info:"#30b3ff",border:"#1e2a1b"}),light:_({bg:"#eef3ea",bgSubtle:"#e4ebe1",text:"#203022",textMuted:"#748476",textDim:"#a0b0a5",primary:"#1cc24b",secondary:"#24f6d9",success:"#1cc24b",error:"#ff4b4b",warning:"#e6ff57",info:"#30b3ff",border:"#748476"})},flexoki:{name:"Flexoki",dark:_({bg:"#100f0f",bgSubtle:"#1c1b1a",text:"#cecdc3",textMuted:"#878580",textDim:"#575653",primary:"#4385be",secondary:"#8b7ec8",success:"#879a39",error:"#d14d41",warning:"#da702c",info:"#3aa99f",border:"#343331"}),light:_({bg:"#fffcf0",bgSubtle:"#f2f0e5",text:"#100f0f",textMuted:"#878580",textDim:"#b7b5ac",primary:"#205ea6",secondary:"#5e409d",success:"#66800b",error:"#af3029",warning:"#bc5215",info:"#24837b",border:"#e6e4d9"})},cursor:{name:"Cursor",dark:_({bg:"#1e1e1e",bgSubtle:"#252526",text:"#d4d4d4",textMuted:"#808080",textDim:"#5a5a5a",primary:"#007acc",secondary:"#c586c0",success:"#6a9955",error:"#f44747",warning:"#cca700",info:"#4ec9b0",border:"#333333"}),light:_({bg:"#ffffff",bgSubtle:"#f3f3f3",text:"#1e1e1e",textMuted:"#808080",textDim:"#b0b0b0",primary:"#007acc",secondary:"#af00db",success:"#388a34",error:"#cd3131",warning:"#bf8803",info:"#16825d",border:"#e5e5e5"})},vercel:{name:"Vercel",dark:_({bg:"#000000",bgSubtle:"#111111",text:"#ededed",textMuted:"#888888",textDim:"#444444",primary:"#ffffff",secondary:"#888888",success:"#0070f3",error:"#ee0000",warning:"#f5a623",info:"#0070f3",border:"#333333"}),light:_({bg:"#ffffff",bgSubtle:"#fafafa",text:"#000000",textMuted:"#666666",textDim:"#999999",primary:"#000000",secondary:"#666666",success:"#0070f3",error:"#ee0000",warning:"#f5a623",info:"#0070f3",border:"#eaeaea"})},"osaka-jade":{name:"Osaka Jade",dark:_({bg:"#111c18",bgSubtle:"#1a2520",text:"#C1C497",textMuted:"#53685B",textDim:"#3d4a44",primary:"#2DD5B7",secondary:"#D2689C",success:"#549e6a",error:"#FF5345",warning:"#E5C736",info:"#2DD5B7",border:"#3d4a44"}),light:_({bg:"#F6F5DD",bgSubtle:"#E8E7CC",text:"#111c18",textMuted:"#53685B",textDim:"#A8A78C",primary:"#1faa90",secondary:"#a8527a",success:"#3d7a52",error:"#c7392d",warning:"#b5a020",info:"#1faa90",border:"#A8A78C"})}};it=null;Pn=Cr(void 0)});import{createContext as Br,useContext as Er}from"react";import{jsx as _r}from"@opentui/react/jsx-runtime";function Bn(e){return _r(Rn.Provider,{value:e.value,children:e.children})}function kt(){let e=Er(Rn);if(!e)throw new Error("useSDK must be used within SDKProvider");return e}var Rn,Ct=K(()=>{"use strict";Rn=Br(void 0)});import{createContext as Lr,useContext as Nr,useState as jr,useEffect as Fr,useCallback as En,useRef as _n}from"react";import{jsx as Mt,jsxs as Nn}from"@opentui/react/jsx-runtime";function Ur(e,n){switch(e){case"info":return n.info;case"success":return n.success;case"warning":return n.warning;case"error":return n.error}}function Fn(e){let{theme:n}=G(),[o,t]=jr([]),i=_n(0),r=_n(new Map),c=En(l=>{t(b=>b.filter(d=>d.id!==l));let h=r.current.get(l);h&&(clearTimeout(h),r.current.delete(l))},[]),a=En((l,h,b)=>{let d=++i.current,D=b??Wr,y={id:d,type:l,message:h,duration:D};t(N=>{let f=[...N,y];if(f.length>Ln){let g=f.splice(0,f.length-Ln);for(let T of g){let I=r.current.get(T.id);I&&(clearTimeout(I),r.current.delete(T.id))}}return f});let k=setTimeout(()=>{c(d)},D);r.current.set(d,k)},[c]);return Fr(()=>()=>{for(let l of r.current.values())clearTimeout(l);r.current.clear()},[]),Nn(jn.Provider,{value:{toast:a},children:[e.children,o.length>0&&Mt("box",{flexDirection:"column",alignItems:"flex-end",children:o.map(l=>{let h=Ur(l.type,n),b=Gr[l.type];return Nn("box",{height:1,flexDirection:"row",justifyContent:"flex-end",children:[Mt("text",{fg:h,children:` ${b} `}),Mt("text",{fg:n.text,children:l.message}),Mt("text",{fg:n.textDim,children:" "})]},l.id)})})]})}function Gn(){let e=Nr(jn);if(!e)throw new Error("useToast must be used within ToastProvider");return e}var Gr,jn,Wr,Ln,Ht=K(()=>{"use strict";te();Gr={info:"\u2139",success:"\u2713",warning:"\u26A0",error:"\u2717"};jn=Lr(void 0),Wr=3e3,Ln=3});import*as je from"fs";import*as st from"path";function at(e,n){if(!e)return[];if(e.startsWith("/"))return Un.filter(t=>t.name.startsWith(e)).map(t=>({text:t.name,description:t.description,type:"command"}));if(e.startsWith("@")||e.includes(" @")){let t=e.lastIndexOf("@"),i=e.substring(t),r=[];for(let c of Wn)c.trigger.startsWith(i)&&r.push({text:c.trigger,description:c.description,type:"mention"});if(i==="@"||i.startsWith("@file ")||i.startsWith("@f")){let c=i.startsWith("@file ")?i.substring(6):"",a=Jr(n,c);for(let l of a.slice(0,10))r.push({text:`@file ${l}`,description:"",type:"file"})}return r}let o=e.split(" ");if(o.length>=1){let t=o[0],i=qr[t];if(i&&o.length<=2){let r=o[1]||"";return i.filter(c=>c.startsWith(r)).map(c=>({text:`${t} ${c}`,description:"",type:"subcommand"}))}}if(o.length>=2){let t=Kr(e,n);if(t.length>0){let i=o.slice(0,-1).join(" ")+" ";return t.map(r=>({text:i+r,description:r.endsWith("/")?"directory":"file",type:"file"}))}}return[]}function qn(e,n){if(!e)return"";if(e.startsWith("/")){let t=Un.find(i=>i.name.startsWith(e)&&i.name!==e);return t?t.name.substring(e.length):""}let o=e.lastIndexOf("@");if(o>=0&&o===e.length-e.substring(o).length){let t=e.substring(o),i=Wn.find(r=>r.trigger.startsWith(t)&&r.trigger!==t);return i?i.trigger.substring(t.length):""}return""}function Kr(e,n){let o=["cd","ls","cat","head","tail","less","more","vim","nano","code","open","rm","cp","mv","mkdir","touch","chmod"],t=e.split(" ");if(t.length<2)return[];let i=t[0];if(!o.includes(i))return[];let r=t[t.length-1]||"";return Hr(n,r)}function Hr(e,n){try{let o=n.includes("/")?st.resolve(e,n.substring(0,n.lastIndexOf("/")+1)):e,t=n.includes("/")?n.substring(n.lastIndexOf("/")+1):n;if(!je.existsSync(o)||!je.statSync(o).isDirectory())return[];let i=je.readdirSync(o,{withFileTypes:!0}),r=n.includes("/")?n.substring(0,n.lastIndexOf("/")+1):"";return i.filter(c=>!c.name.startsWith(".")||n.startsWith(".")).filter(c=>c.name.toLowerCase().startsWith(t.toLowerCase())).sort((c,a)=>c.isDirectory()!==a.isDirectory()?c.isDirectory()?-1:1:c.name.localeCompare(a.name)).slice(0,20).map(c=>r+c.name+(c.isDirectory()?"/":""))}catch{return[]}}function Jr(e,n){let o=[],t=n.toLowerCase(),i=new Set(["node_modules",".git","dist","build","__pycache__",".cache","coverage"]),r=(c,a,l)=>{if(!(l>3||o.length>=15))try{let h=je.readdirSync(st.join(e,c),{withFileTypes:!0});for(let b of h){if(b.name.startsWith(".")||i.has(b.name))continue;if(o.length>=15)break;let d=a?`${a}/${b.name}`:b.name;b.isDirectory()?((!n||d.toLowerCase().includes(t))&&o.push(d+"/"),r(st.join(c,b.name),d,l+1)):(!n||d.toLowerCase().includes(t))&&o.push(d)}}catch{}};return r("","",0),o}var Un,Wn,qr,Kn=K(()=>{"use strict";Un=[{name:"/help",description:"Show available commands"},{name:"/clear",description:"Clear chat history"},{name:"/new",description:"Start new conversation"},{name:"/model",description:"Show/change model"},{name:"/provider",description:"Show/change provider"},{name:"/mode",description:"Cycle permission mode"},{name:"/usage",description:"Show token usage & cost"},{name:"/compact",description:"Compress context"},{name:"/config",description:"Show/set configuration"},{name:"/dir",description:"Change working directory"},{name:"/history",description:"Browse past sessions"},{name:"/ls",description:"List conversations"},{name:"/resume",description:"Resume conversation by ID"},{name:"/view",description:"View a conversation"},{name:"/fork",description:"Fork current conversation"},{name:"/delete",description:"Delete a conversation"},{name:"/plan",description:"Plan mode (approve/reject/show/off)"},{name:"/plan approve",description:"Approve plan and start building"},{name:"/plan reject",description:"Reject plan"},{name:"/plan show",description:"Show current plan"},{name:"/plan off",description:"Cancel plan mode"},{name:"/tasks",description:"Show active tasks"},{name:"/memory",description:"Show agent memory"},{name:"/permissions",description:"Show permission rules"},{name:"/hooks",description:"Show configured hooks"},{name:"/rules",description:"Show project rules"},{name:"/mcp",description:"MCP server management"},{name:"/context",description:"Show context providers"},{name:"/effort",description:"Set effort level"},{name:"/theme",description:"Switch theme"},{name:"/bg",description:"Run in background"},{name:"/jobs",description:"Show background jobs"},{name:"/login",description:"OAuth login"},{name:"/logout",description:"OAuth logout"},{name:"/setup",description:"Run setup wizard"},{name:"/doctor",description:"Check system health"},{name:"/init",description:"Initialize project config"},{name:"/exit",description:"Quit the TUI"},{name:"/quit",description:"Quit the TUI"},{name:"/btw",description:"Ask without adding to history"},{name:"/auth-status",description:"Show authentication status"},{name:"/queue",description:"Show message queue"}],Wn=[{trigger:"@terminal",description:"Recent terminal output"},{trigger:"@url",description:"Fetch URL content"},{trigger:"@tree",description:"Project file tree"},{trigger:"@codebase",description:"Full codebase context"},{trigger:"@clip",description:"Clipboard content"},{trigger:"@file",description:"Include a file"}],qr={npm:["install","run","test","start","build","init","publish","uninstall","update","ls","audit","ci"],yarn:["install","add","remove","run","build","test","start","dev","upgrade","info","why"],pnpm:["install","add","remove","run","build","test","dev","update","store"],bun:["install","add","remove","run","build","test","dev","init","create"],git:["status","add","commit","push","pull","fetch","checkout","branch","merge","rebase","log","diff","stash","reset","clone","remote","tag","cherry-pick","bisect","show","blame","reflog"],docker:["build","run","exec","ps","images","pull","push","stop","rm","logs","compose"],python:["-m","-c","--version","manage.py"],python3:["-m","-c","--version","manage.py"],pip:["install","uninstall","freeze","list","show"],cargo:["build","run","test","check","clippy","fmt","new","init","add","publish"],go:["build","run","test","get","mod","fmt","vet","install","generate"],make:["build","test","clean","install","all"],kubectl:["get","describe","apply","delete","logs","exec","port-forward","scale"],gh:["pr","issue","repo","run","release","api","auth","browse"],turbo:["build","dev","test","lint","run"],npx:["tsc","ts-node","eslint","prettier","jest","vitest","playwright"]}});import{TextAttributes as ct,RGBA as Vr}from"@opentui/core";import{useState as Tt,useRef as Hn,useMemo as Jn}from"react";import{useKeyboard as Yr}from"@opentui/react";import{execSync as dt}from"child_process";import{Fragment as Vn,jsx as z,jsxs as Fe}from"@opentui/react/jsx-runtime";function zr(){try{if(process.platform==="darwin")return dt("pbpaste",{encoding:"utf-8"});try{return dt("xclip -selection clipboard -o",{encoding:"utf-8"})}catch{return dt("xsel --clipboard --output",{encoding:"utf-8"})}}catch{return""}}function Xr(){if(process.platform!=="darwin")return null;try{if(dt(`osascript -e 'clipboard info' 2>/dev/null | grep -q "TIFF\\|PNG\\|JPEG" && echo "yes" || echo "no"`,{encoding:"utf-8",timeout:1e3}).trim()!=="yes")return null;let n=dt("osascript -e 'set theImage to the clipboard as \xABclass PNGf\xBB' -e 'return theImage' 2>/dev/null | base64",{encoding:"utf-8",timeout:3e3,maxBuffer:20*1024*1024}).trim();if(n&&n.length>100)return{data:n,mimeType:"image/png"}}catch{}return null}function $t(e){let{theme:n,customBg:o}=G(),t=n,[i,r]=Tt(""),[c,a]=Tt([]),[l,h]=Tt(0),[b,d]=Tt(!1),D=Hn(i);D.current=i;let y=Hn(0),k=Jn(()=>{if(!i)return[];let v=at(i,e.workingDir);return v.length>0&&v[0].type==="file"?[{text:i,description:"submit as typed",type:"file"},...v]:v},[i,e.workingDir]),N=Jn(()=>b&&k.length>0?"":qn(i,e.workingDir),[i,e.workingDir,b,k.length]),f=b&&k.length>0;Yr(v=>{if(!e.suppressInput){if(v.name==="tab"&&e.onModeChange&&e.mode){e.onModeChange(e.mode==="build"?"plan":"build");return}if(f){if(v.name==="up"){h(M=>M<=0?k.length-1:M-1);return}if(v.name==="down"){h(M=>M>=k.length-1?0:M+1);return}if(v.name==="return"){let M=k[l];if(M){let U=M.text.trim();U&&(e.onSubmit(U,c.length>0?[...c]:void 0),r(""),a([])),d(!1),h(0)}return}if(v.name==="escape"){d(!1);return}if(v.name==="right"){let M=k[l];M&&(r(M.text+" "),d(!1),h(0));return}}if(N&&v.name==="right"){r(M=>M+N);return}if(v.ctrl&&v.name==="v"){let M=Xr();if(M){y.current+=1,a(H=>[...H,M]),r(H=>H+`[Image #${y.current}] `);return}let U=zr().trim();if(U){let H=U.split(`
3
- `)[0]||"";r($=>$+H)}return}if(v.ctrl&&v.name==="u"){r(""),a([]),d(!1);return}if(v.ctrl&&v.name==="w"){r(M=>M.replace(/\S+\s*$/,""));return}if(v.name==="return"&&!v.shift){let M=D.current.trim();(M||c.length>0)&&(e.onSubmit(M||"Describe this image.",c.length>0?[...c]:void 0),r(""),a([]),d(!1));return}if(v.name==="backspace"){r(M=>{let U=M.slice(0,-1);return U.startsWith("/")||U.includes("@")||at(U,e.workingDir).length>0?(d(!0),h(0)):d(!1),U});return}if(v.name==="escape"&&b){d(!1);return}if(v.name==="space"){r(M=>{let U=M+" ";return M.startsWith("/")?d(!1):at(U,e.workingDir).length>0&&(d(!0),h(0)),U});return}v.name&&v.name.length===1&&!v.ctrl&&!v.meta&&r(M=>{let U=M+v.name;return(U.startsWith("/")||U.includes("@")||at(U,e.workingDir).length>0)&&(d(!0),h(0)),U})}});let g=i.startsWith("/"),T=Math.max(0,Math.min(l-Math.floor(lt/2),k.length-lt)),I=k.slice(T,T+lt),R=T>0,F=T+lt<k.length,L=o?Vr.fromHex(o):t.bg;return Fe("box",{flexDirection:"column",flexShrink:0,backgroundColor:L,children:[f&&Fe("box",{flexDirection:"column",paddingX:1,backgroundColor:L,children:[R&&z("box",{children:z("text",{fg:t.textDim,children:` \u25B2 ${T} more`})}),I.map((v,M)=>{let H=T+M===l,$=v.type==="command"?t.warning:v.type==="mention"?t.info:v.type==="file"?t.success:t.textMuted;return Fe("box",{flexDirection:"row",children:[z("text",{fg:H?t.primary:$,attributes:H?ct.BOLD:void 0,children:H?" \u276F ":" "}),z("text",{fg:H?t.text:$,children:v.text}),v.description?z("text",{fg:t.textDim,children:` ${v.description}`}):null]},v.text)}),F&&z("box",{children:z("text",{fg:t.textDim,children:` \u25BC ${k.length-T-lt} more`})})]}),c.length>0&&z("box",{height:1,paddingX:1,children:z("text",{fg:t.primary,children:` \u{1F5BC} ${c.length} image${c.length>1?"s":""} attached`})}),Fe("box",{height:3,borderStyle:"single",borderColor:t.borderFocused,backgroundColor:L,flexDirection:"row",alignItems:"center",paddingX:1,children:[z("text",{fg:g?t.warning:t.primary,attributes:ct.BOLD,children:g?" / ":" > "}),i?Fe(Vn,{children:[z("text",{fg:t.text,children:i}),N?z("text",{fg:t.textDim,children:N}):z("text",{fg:t.primary,children:"\u258A"})]}):z("text",{fg:t.textDim,children:e.placeholder||"Type a message... (^V paste, / commands, @ context, \u2192 accept)"})]}),e.mode&&Fe("box",{height:1,flexDirection:"row",backgroundColor:L,paddingX:1,children:[z("box",{backgroundColor:e.mode==="build"?t.primary:void 0,children:z("text",{fg:e.mode==="build"?t.bg:t.textMuted,attributes:e.mode==="build"?ct.BOLD:void 0,children:" Build "})}),z("text",{fg:t.textDim,children:" "}),z("box",{backgroundColor:e.mode==="plan"?t.secondary:void 0,children:z("text",{fg:e.mode==="plan"?t.bg:t.textMuted,attributes:e.mode==="plan"?ct.BOLD:void 0,children:" Plan "})}),e.modelLabel&&Fe(Vn,{children:[z("text",{fg:t.textDim,children:" "}),z("text",{fg:t.textMuted,attributes:ct.ITALIC,children:e.modelLabel})]}),z("box",{flexGrow:1}),z("text",{fg:t.textDim,children:"tab mode "}),z("text",{fg:t.textDim,children:"ctrl+p commands"})]})]})}var lt,Jt=K(()=>{"use strict";te();Kn();lt=6});import{TextAttributes as Yn}from"@opentui/core";import{useTerminalDimensions as Qr}from"@opentui/react";import{jsx as Se,jsxs as zn}from"@opentui/react/jsx-runtime";function Xn(e){let{theme:n}=G(),o=n,t=Qr(),i=t.width||80,r=t.height||24,c=()=>{let f=process.env.HOME||"",g=e.workingDir;return f&&g.startsWith(f)?"~"+g.slice(f.length):g},a="Multi-provider AI coding assistant",l="v0.1.1",h=i<60||r<20,b=!h&&(i<80||r<30),d=h?null:b?ei:Zr,D=[["Provider",e.provider],["Model",e.model],["Theme",e.themeId],["Directory",c()]],y=Math.max(...D.map(([f])=>f.length)),k=[{key:"Enter",label:"Send message / start session",id:"start"},{key:"Ctrl+P",label:"Command palette",id:"commands"},{key:"Ctrl+O",label:"Switch model",id:"model"},{key:"Ctrl+T",label:"Change theme",id:"theme"},{key:"Ctrl+N",label:"New session",id:"new"},{key:"Ctrl+S",label:"Browse sessions",id:"sessions"},{key:"/setup",label:"Setup wizard",id:"setup"},{key:"Ctrl+C",label:"Quit",id:"quit"}],N=Math.max(...k.map(f=>f.key.length));return zn("box",{flexDirection:"column",flexGrow:1,flexShrink:1,overflow:"hidden",children:[zn("box",{flexDirection:"column",alignItems:"center",justifyContent:"center",flexGrow:1,children:[d&&d.map((f,g)=>Se("text",{fg:o.primary,attributes:Yn.BOLD,children:f},`logo-${g}`)),Se("text",{fg:o.textDim,children:a}),Se("text",{fg:o.textMuted,children:l}),Se("text",{children:""}),D.map(([f,g],T)=>{let I=`${f.padStart(y)} ${g}`;return Se("text",{fg:o.textDim,children:I},`info-${T}`)}),Se("text",{children:""}),Se("text",{fg:o.primary,attributes:Yn.BOLD,children:"Actions"}),k.map((f,g)=>{let T=`${f.key.padStart(N)} ${f.label}`;return Se("text",{fg:o.textMuted,children:T},`act-${g}`)}),Se("text",{children:""}),Se("text",{fg:o.textDim,children:"Powered by @opentui/react + @cdoing/ai"})]}),e.onSubmit&&Se($t,{onSubmit:e.onSubmit,workingDir:e.workingDir,placeholder:"Start typing to begin a session... (/ commands, @ context)"})]})}var Zr,ei,Qn=K(()=>{"use strict";te();Jt();Zr=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D ","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D "],ei=["\u250C\u2500\u2510\u250C\u2510 \u250C\u2500\u2510\u252C\u250C\u2510\u250C\u250C\u2500\u2510","\u2502 \u2502\u2502\u2502 \u2502\u2502\u2502\u2502\u2502\u2502\u2502\u2502 \u252C","\u2514\u2500\u2518\u2514\u2518\u2514\u2500\u2518\u2514\u2500\u2518\u2518\u2514\u2518\u2514\u2500\u2518"]});import{TextAttributes as Be}from"@opentui/core";import{Fragment as to,jsx as A,jsxs as ge}from"@opentui/react/jsx-runtime";function Ge(e){return e.replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/(?<!\w)\*([^*]+)\*(?!\w)/g,"$1")}function Zn(e){let n=e.theme,{syntaxStyle:o}=G(),t=e.text.split(`
4
- `),i=[],r=0;for(;r<t.length;){let c=t[r];if(c.startsWith("```")){let h=[c];for(r++;r<t.length;){if(h.push(t[r]),t[r].startsWith("```")){r++;break}r++}let b=h.join(`
5
- `);i.push(A("box",{marginY:0,children:A("markdown",{syntaxStyle:o,streaming:!1,content:b,conceal:!0})},`code-${r}`));continue}if(c.startsWith("### ")){i.push(A("text",{fg:n.info,attributes:Be.BOLD,children:` \u25B8 ${Ge(c.slice(4))}`},r)),r++;continue}if(c.startsWith("## ")){i.push(A("text",{fg:n.primary,attributes:Be.BOLD,children:` \u25B8\u25B8 ${Ge(c.slice(3))}`},r)),r++;continue}if(c.startsWith("# ")){i.push(A("text",{fg:n.primary,attributes:Be.BOLD,children:`\u25B8\u25B8\u25B8 ${Ge(c.slice(2))}`},r)),r++;continue}if(/^---+$/.test(c)||/^===+$/.test(c)||/^\*\*\*+$/.test(c)){i.push(A("text",{fg:n.textDim,children:"\u2500".repeat(40)},r)),r++;continue}let a=c.match(/^(\s*)[-*] (.*)/);if(a){let h=a[1]||"",b=Ge(a[2]);i.push(A("text",{children:`${h}\u25CF ${b}`},r)),r++;continue}let l=c.match(/^(\s*)(\d+)\. (.*)/);if(l){let h=Ge(l[3]);i.push(A("text",{children:`${l[1]}${l[2]}. ${h}`},r)),r++;continue}if(c.startsWith("> ")){i.push(A("text",{fg:n.textMuted,children:`\u2502 ${Ge(c.slice(2))}`},r)),r++;continue}if(!c.trim()){i.push(A("text",{children:" "},r)),r++;continue}i.push(A("text",{children:Ge(c)},r)),r++}return A("box",{flexDirection:"column",children:i})}function Vt(e){let n=new Date(e),o=n.getHours(),t=n.getMinutes(),i=o>=12?"PM":"AM";return o=o%12||12,`${o}:${t.toString().padStart(2,"0")} ${i}`}function eo(e){let{theme:n}=G(),o=n;return ge(to,{children:[e.messages.length===0&&!e.isStreaming&&A("box",{paddingX:2,paddingY:1,children:A("text",{fg:o.textMuted,children:"Type a message to start chatting. Use / for commands, @ for context."})}),e.messages.map(t=>t.role==="user"?ge("box",{paddingX:1,paddingY:0,flexDirection:"row",children:[A("text",{fg:o.userText,attributes:Be.BOLD,children:"\u276F "}),A("text",{fg:o.userText,flexGrow:1,children:t.content}),e.showTimestamps&&t.timestamp&&A("text",{fg:o.textDim,children:` ${Vt(t.timestamp)}`})]},t.id):t.role==="assistant"?ge("box",{paddingLeft:1,marginTop:1,flexShrink:0,flexDirection:"column",children:[ge("box",{flexDirection:"row",children:[A("text",{fg:o.primary,attributes:Be.BOLD,children:"\u25C6 "}),e.showTimestamps&&t.timestamp&&A("text",{fg:o.textDim,children:` ${Vt(t.timestamp)}`})]}),A("box",{paddingLeft:2,children:A(Zn,{text:t.content.trim(),theme:o})})]},t.id):t.role==="system"?ge("box",{paddingX:1,flexDirection:"row",children:[A("text",{fg:o.systemText,flexGrow:1,children:`\u26A1 ${t.content}`}),e.showTimestamps&&t.timestamp&&A("text",{fg:o.textDim,children:` ${Vt(t.timestamp)}`})]},t.id):t.role==="tool"?A(ii,{name:t.toolName||"unknown",content:t.content,status:t.toolStatus||(t.isError?"error":"done"),input:t.toolInput},t.id):null),e.isStreaming&&ge("box",{paddingLeft:1,marginTop:1,flexShrink:0,flexDirection:"column",children:[ge("box",{flexDirection:"row",children:[A("text",{fg:o.primary,attributes:Be.BOLD,children:"\u25C6 "}),A("text",{fg:o.primary,children:"\u258A"})]}),(e.streamingText||"").trim()&&A("box",{paddingLeft:2,children:A(Zn,{text:(e.streamingText||"").trim(),theme:o})})]})]})}function ne(e,n){let o=e.split(`
6
- `)[0]||"";return o.length>n?o.substring(0,n)+"\u2026":o}function Ue(e){let n=process.env.HOME||"",o=n&&e.startsWith(n)?"~"+e.slice(n.length):e;return o.length>50&&(o="\u2026/"+o.split("/").slice(-2).join("/")),o}function ni(e){return e?e.split(`
7
- `).length:0}function oi(e,n){if(!n)return"";switch(e){case"file_read":return n.file_path?Ue(n.file_path):"";case"file_write":return n.file_path?Ue(n.file_path):"";case"file_edit":case"multi_edit":case"apply_patch":return n.file_path?Ue(n.file_path):"";case"shell_exec":return n.command?ne(n.command,55):"";case"file_run":return n.file_path?Ue(n.file_path):"";case"glob_search":return n.pattern?`"${ne(n.pattern,40)}"`:"";case"grep_search":return n.pattern?`"${ne(n.pattern,30)}"${n.path?` in ${Ue(n.path)}`:""}`:"";case"codebase_search":return n.query?`"${ne(n.query,40)}"`:"";case"web_fetch":return n.url?ne(n.url,50):"";case"web_search":return n.query?`"${ne(n.query,40)}"`:"";case"sub_agent":return n.description?ne(n.description,50):"";case"list_dir":return n.path?Ue(n.path):"";default:return n.description||""}}function ri(e,n,o){if(!n)return"";if(o)return ne(n,50);let t=ni(n);switch(e){case"file_read":return`${t} lines`;case"shell_exec":case"file_run":return t>1?`${t} lines`:ne(n,40);case"grep_search":case"glob_search":case"codebase_search":{let i=n.split(`
8
- `).filter(r=>r.trim()).length;return`${i} result${i!==1?"s":""}`}case"file_write":case"file_edit":case"multi_edit":case"apply_patch":return n.includes("+")||n.includes("-")?ne(n,40):"done";default:return t>1?`${t} lines`:ne(n,40)}}function ii(e){let{theme:n}=G(),o=n,t=ti[e.name]||{label:e.name.replace(/_/g," "),icon:"\u2699",verb:"Running"},i=e.status==="running",r=e.status==="error",c=i?"\u27F3":r?"\u2717":"\u2713",a=i?o.toolRunning:r?o.toolError:o.toolDone,l=oi(e.name,e.input),h=i?"":ri(e.name,e.content,r),b=e.name==="shell_exec"||e.name==="file_run",d=b&&e.input?.command?ne(e.input.command,55):"",y=["file_read","file_write","file_edit","multi_edit","apply_patch"].includes(e.name)&&e.input?.file_path?Ue(e.input.file_path):"",k=["grep_search","glob_search","codebase_search"].includes(e.name),N=k&&(e.input?.pattern||e.input?.query)?ne(e.input?.pattern||e.input?.query,35):"",f=(e.name==="file_edit"||e.name==="multi_edit")&&e.input?.old_string&&e.input?.new_string,g=f?ne(e.input.old_string,50):"",T=f?ne(e.input.new_string,50):"",I=e.content?e.content.split(`
9
- `):[],R=6,F=I.slice(0,R),L=I.length>R;return ge("box",{flexDirection:"column",paddingLeft:2,paddingRight:1,children:[ge("box",{flexDirection:"row",height:1,children:[A("text",{fg:a,attributes:i?Be.BOLD:void 0,children:`${c} `}),A("text",{fg:o.textMuted,children:`${t.icon} `}),A("text",{fg:i?o.toolRunning:o.text,attributes:Be.BOLD,children:i?`${t.verb}...`:t.label}),y&&!i?A("text",{fg:o.info,children:` ${y}`}):d?A("text",{fg:i?o.textDim:o.textMuted,children:` $ ${d}`}):N?A("text",{fg:o.warning,children:` "${N}"`}):l&&!y&&!d?A("text",{fg:o.textDim,children:` ${l}`}):null,h&&!i?ge(to,{children:[A("text",{fg:o.textDim,children:" \u2192 "}),A("text",{fg:r?o.error:o.toolDone,children:h})]}):null]}),f&&!i&&ge("box",{flexDirection:"column",paddingLeft:3,children:[A("box",{flexDirection:"row",height:1,children:A("text",{fg:o.diffRemove,children:` - ${g}`})}),A("box",{flexDirection:"row",height:1,children:A("text",{fg:o.diffAdd,children:` + ${T}`})})]}),b&&!i&&F.length>0&&ge("box",{flexDirection:"column",paddingLeft:3,children:[A("box",{height:1,children:A("text",{fg:o.border,children:" \u250C"+"\u2500".repeat(40)})}),F.map((v,M)=>A("box",{height:1,children:A("text",{fg:o.textDim,children:` \u2502 ${ne(v,55)}`})},M)),L&&A("box",{height:1,children:A("text",{fg:o.textDim,children:` \u2502 \u2026 ${I.length-R} more lines`})}),A("box",{height:1,children:A("text",{fg:o.border,children:" \u2514"+"\u2500".repeat(40)})})]}),k&&!i&&F.length>0&&ge("box",{flexDirection:"column",paddingLeft:3,children:[F.slice(0,4).map((v,M)=>A("box",{height:1,children:A("text",{fg:o.textDim,children:` ${ne(v,60)}`})},M)),I.length>4&&A("box",{height:1,children:A("text",{fg:o.textDim,children:` \u2026 ${I.length-4} more`})})]}),r&&e.content&&A("box",{flexDirection:"column",paddingLeft:3,children:A("box",{height:1,children:A("text",{fg:o.error,children:` \u2717 ${ne(e.content,70)}`})})}),b&&i&&A("box",{paddingLeft:3,height:1,children:A("text",{fg:o.toolRunning,children:" \u258A Executing command..."})})]})}var ti,no=K(()=>{"use strict";te();ti={file_read:{label:"Read",icon:"\u25C7",verb:"Reading"},file_write:{label:"Write",icon:"\u25C8",verb:"Writing"},file_edit:{label:"Edit",icon:"\u25C8",verb:"Editing"},multi_edit:{label:"MultiEdit",icon:"\u25C8",verb:"Editing"},apply_patch:{label:"Patch",icon:"\u25C8",verb:"Patching"},shell_exec:{label:"Bash",icon:"$",verb:"Running"},file_run:{label:"Run",icon:"\u25B6",verb:"Running"},glob_search:{label:"Search files",icon:"\u25CE",verb:"Searching"},grep_search:{label:"Search",icon:"\u25CE",verb:"Searching"},codebase_search:{label:"Codebase",icon:"\u25CE",verb:"Searching"},web_fetch:{label:"Fetch",icon:"\u25CC",verb:"Fetching"},web_search:{label:"Web Search",icon:"\u25CC",verb:"Searching"},sub_agent:{label:"Agent",icon:"\u25C6",verb:"Running"},todo:{label:"Todo",icon:"\u2610",verb:"Updating"},list_dir:{label:"List Dir",icon:"\u251C",verb:"Listing"},view_diff:{label:"Diff",icon:"\xB1",verb:"Viewing"},view_repo_map:{label:"Repo Map",icon:"\u229E",verb:"Mapping"},code_verify:{label:"Verify",icon:"\u2713",verb:"Verifying"},system_info:{label:"System Info",icon:"i",verb:"Checking"},ast_edit:{label:"AST Edit",icon:"\u2325",verb:"Editing"},notebook_edit:{label:"Notebook",icon:"\u22A1",verb:"Editing"}}});import{TextAttributes as oo}from"@opentui/core";import{useState as si}from"react";import{useKeyboard as ai}from"@opentui/react";import{jsx as ze,jsxs as ci}from"@opentui/react/jsx-runtime";function ro(e){let{theme:n,customBg:o}=G(),t=n,[i,r]=si(0);return ai(c=>{c.name==="up"||c.name==="k"?r(a=>Math.max(0,a-1)):c.name==="down"||c.name==="j"?r(a=>Math.min(Yt.length-1,a+1)):c.name==="return"?e.onDecision(Yt[i].value):c.name==="1"?e.onDecision("allow"):c.name==="2"?e.onDecision("always"):c.name==="3"&&e.onDecision("deny")}),ci("box",{borderStyle:"single",borderColor:t.warning,backgroundColor:o||t.bg,paddingX:1,paddingY:0,flexDirection:"column",children:[ze("text",{fg:t.warning,attributes:oo.BOLD,children:"\u{1F510} Permission Required"}),ze("text",{fg:t.text,children:` ${e.toolName}: ${e.message}`}),ze("text",{fg:t.textDim,children:""}),Yt.map((c,a)=>ze("box",{children:ze("text",{fg:i===a?t.primary:t.textMuted,attributes:i===a?oo.BOLD:void 0,children:` ${i===a?"\u276F":" "} [${c.key}] ${c.label}`})},c.key)),ze("text",{fg:t.textDim,children:`
10
- \u2191\u2193 Navigate Enter Select 1-3 Quick pick`})]})}var Yt,io=K(()=>{"use strict";te();Yt=[{key:"1",label:"Allow once",value:"allow"},{key:"2",label:"Always allow",value:"always"},{key:"3",label:"Deny",value:"deny"}]});import{useState as li,useEffect as di}from"react";import{jsx as ao,jsxs as ui}from"@opentui/react/jsx-runtime";function co(e){let{theme:n}=G(),o=n,[t,i]=li(0);return di(()=>{let r=setInterval(()=>{i(c=>(c+1)%so.length)},80);return()=>clearInterval(r)},[]),ui("box",{paddingX:1,height:1,flexDirection:"row",children:[ao("text",{fg:o.primary,children:so[t]}),ao("text",{fg:o.textMuted,children:` ${e.label||"Thinking..."}`})]})}var so,lo=K(()=>{"use strict";te();so=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function At(e){process.stdout.isTTY&&process.stdout.write(`\x1B]0;${e}\x07`)}function uo(){process.stdout.isTTY&&process.stdout.write("\x1B]0;\x07")}var zt=K(()=>{"use strict"});import*as le from"fs";import*as Xe from"path";import*as mo from"os";function Qe(){le.existsSync(Ce)||le.mkdirSync(Ce,{recursive:!0})}function fo(){let e=Date.now().toString(36),n=Math.random().toString(36).slice(2,6);return`${e}-${n}`}function mi(e){let n=e.replace(/\n/g," ").trim();return n.length>60?n.substring(0,57)+"...":n}function Xt(e,n){return Qe(),{id:fo(),title:"New conversation",createdAt:Date.now(),updatedAt:Date.now(),provider:e,model:n,messages:[]}}function go(e,n,o,t){e.messages.push({role:n,content:o,timestamp:Date.now(),toolName:t}),e.updatedAt=Date.now(),n==="user"&&e.title==="New conversation"&&(e.title=mi(o)),xo(e)}function xo(e){Qe();let n=Xe.join(Ce,`${e.id}.json`);le.writeFileSync(n,JSON.stringify(e,null,2),"utf-8")}function ut(e){Qe();let o=le.readdirSync(Ce).filter(i=>i.endsWith(".json")).find(i=>i.startsWith(e)||i.replace(".json","")===e);if(!o)return null;let t=Xe.join(Ce,o);try{return JSON.parse(le.readFileSync(t,"utf-8"))}catch{return null}}function We(){Qe();let e=le.readdirSync(Ce).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let t=JSON.parse(le.readFileSync(Xe.join(Ce,o),"utf-8"));n.push(t)}catch{}return n.sort((o,t)=>t.updatedAt-o.updatedAt)}function Ot(e){Qe();let o=le.readdirSync(Ce).filter(t=>t.endsWith(".json")).find(t=>t.startsWith(e)||t.replace(".json","")===e);return o?(le.unlinkSync(Xe.join(Ce,o)),!0):!1}function Pt(e){let n=typeof e=="string"?ut(e):e;if(!n)return null;Qe();let o={...n,id:fo(),title:`Fork of: ${n.title}`,createdAt:Date.now(),updatedAt:Date.now(),messages:n.messages.map(t=>({...t}))};return xo(o),o}function It(e){let n=Date.now()-e,o=Math.floor(n/1e3);if(o<60)return"just now";let t=Math.floor(o/60);if(t<60)return`${t}m ago`;let i=Math.floor(t/60);if(i<24)return`${i}h ago`;let r=Math.floor(i/24);return r<30?`${r}d ago`:new Date(e).toLocaleDateString()}var Ce,Qt=K(()=>{"use strict";Ce=Xe.join(mo.homedir(),".cdoing","conversations")});import{ContextProviderRegistry as fi,TerminalContextProvider as gi,UrlContextProvider as xi,TreeContextProvider as hi,CodebaseContextProvider as bi,ClipboardContextProvider as pi,FileIncludeContextProvider as yi}from"@cdoing/core";function ho(){return Me||(Me=new fi,mt=new gi,Me.register(mt),Me.register(new xi),Me.register(new hi),Me.register(new bi),Me.register(new pi),Me.register(new yi)),Me}function bo(e){ho(),mt&&typeof mt.push=="function"&&mt.push(e)}async function yo(e,n){let o=ho(),t=e,i=[];for(let r of po){let c=t.indexOf(r);if(c===-1)continue;let a=t.substring(c+r.length),l=a.search(/\s@|\n|$/),h=a.substring(0,l===-1?a.length:l).trim(),b=r+(h?" "+h:"");t=t.replace(b,"").trim();let d=r.substring(1),D=o.get(d);if(D)try{let y=await D.resolve(h,{workingDir:n});y&&i.push(`--- ${r} ---
11
- ${y}`)}catch{}}return i.length>0&&(t=t+`
12
-
13
- `+i.join(`
14
-
15
- `)),t}function So(e){return po.some(n=>e.includes(n))}var Me,mt,po,vo=K(()=>{"use strict";Me=null,mt=null;po=["@terminal","@url","@tree","@codebase","@clip","@file"]});import{useState as Ee,useRef as ve,useEffect as Si}from"react";import{TextAttributes as wo}from"@opentui/core";import{useKeyboard as vi}from"@opentui/react";import*as q from"fs";import*as ae from"path";import*as Zt from"os";import{execSync as wi}from"child_process";import{jsx as we,jsxs as en}from"@opentui/react/jsx-runtime";function ki(e){let n=e.trim(),o=n.split(/\s+/)[0].toLowerCase();return Di.has(o)?n:null}function Ci(e){let{theme:n}=G(),o=n,[t,i]=Ee(0),r=[{label:"Interrupt \u2014 stop current response and send new message",action:e.onInterrupt},{label:"Queue \u2014 wait for current response, then send",action:e.onQueue},{label:"Cancel \u2014 discard new message",action:e.onCancel}];vi(a=>{if(a.name==="escape"){e.onCancel();return}if(a.name==="up"||a.name==="k"){i(l=>Math.max(0,l-1));return}if(a.name==="down"||a.name==="j"){i(l=>Math.min(r.length-1,l+1));return}if(a.name==="return"){r[t].action();return}if(a.sequence==="1"||a.sequence==="i"){e.onInterrupt();return}if(a.sequence==="2"||a.sequence==="q"){e.onQueue();return}if(a.sequence==="3"){e.onCancel();return}});let c=e.message.length>50?e.message.slice(0,47)+"...":e.message;return en("box",{flexDirection:"column",flexShrink:0,paddingX:1,children:[we("text",{fg:o.warning,attributes:wo.BOLD,children:" Agent is streaming. What to do with your message?"}),we("text",{fg:o.textDim,children:` "${c}"`}),we("text",{children:""}),r.map((a,l)=>we("text",{fg:l===t?o.primary:o.textMuted,attributes:l===t?wo.BOLD:void 0,children:` ${l===t?"\u276F":" "} ${l+1}. ${a.label}`},l)),we("text",{fg:o.textDim,children:" \u2191\u2193 Navigate Enter Select i/q/Esc Quick keys"})]})}function Do(e){let n=kt(),{setMode:o}=G(),{toast:t}=Gn();At("cdoing - session");let[i,r]=Ee([]),[c,a]=Ee(""),l=ve(c);l.current=c;let[h,b]=Ee(!1),[d,D]=Ee("build"),y=S=>{D(S),n.permissionManager.setAgentType(S)},[k,N]=Ee(),[f,g]=Ee(null),[T,I]=Ee(null),R=ve([]),F=ve(0),L=ve(0),v=ve(0),M=ve(null),U=ve([]),H=ve(0),$=ve(!1),B=ve("");M.current||(M.current=Xt(n.provider,n.model));let m=(S,O,W)=>{let w={id:`msg-${++v.current}`,role:S,content:O,timestamp:Date.now(),...W};return r(u=>[...u,w]),M.current&&(S==="user"||S==="assistant")&&go(M.current,S,O),w.id},Q=(S,O)=>{r(W=>W.map(w=>w.id===S?{...w,...O}:w))},ue=()=>{try{let S=ae.join(Zt.homedir(),".cdoing","config.json");if(q.existsSync(S))return JSON.parse(q.readFileSync(S,"utf-8"))}catch{}return{}},xe=(S,O)=>{let W=ae.join(Zt.homedir(),".cdoing"),w=ae.join(W,"config.json"),u={};try{q.existsSync(w)&&(u=JSON.parse(q.readFileSync(w,"utf-8")))}catch{}u[S]=O,q.existsSync(W)||q.mkdirSync(W,{recursive:!0}),q.writeFileSync(w,JSON.stringify(u,null,2),"utf-8")},Oe=()=>{try{let S=ae.join(n.workingDir,".cdoing","settings.json");if(q.existsSync(S))return JSON.parse(q.readFileSync(S,"utf-8"));let O=ae.join(n.workingDir,".claude","settings.json");if(q.existsSync(O))return JSON.parse(q.readFileSync(O,"utf-8"))}catch{}return{}},Ke=S=>{let O={id:`bg-${++H.current}`,prompt:S,status:"running",startedAt:Date.now()};U.current=[...U.current,O],m("system",`Background job ${O.id} started: ${S.substring(0,60)}${S.length>60?"...":""}`);let W="",w={onToken:u=>{W+=u},onToolCall:()=>{},onToolResult:()=>{},onComplete:()=>{O.status="done",O.result=W.trim(),O.completedAt=Date.now(),U.current=[...U.current],m("system",`Background job ${O.id} completed. Use /jobs ${O.id} to see results.`)},onError:u=>{O.status="error",O.error=u.message,O.completedAt=Date.now(),U.current=[...U.current],m("system",`Background job ${O.id} failed: ${u.message}`)}};n.agent.run(S,w).catch(u=>{O.status="error",O.error=u instanceof Error?u.message:String(u),O.completedAt=Date.now()})},Ne=S=>{let[O,...W]=S.split(" "),w=W.join(" ").trim();switch(O){case"/clear":r([]),n.agent.clearHistory(),m("system","Chat cleared."),t("success","Chat cleared");break;case"/new":r([]),n.agent.clearHistory(),F.current=0,L.current=0,e.onTokens(0,0),e.onContextPercent(0),M.current=Xt(n.provider,n.model),m("system","New conversation started."),t("success","New conversation started");break;case"/model":{w&&n.rebuildAgent?(n.rebuildAgent(n.provider,w),m("system",`Model switched to: ${w}`),t("info",`Model: ${w}`)):w?(m("system","Model switching not available."),t("warning","Model switching not available")):m("system",`Current model: ${n.model}`);break}case"/provider":{if(w&&n.rebuildAgent){let{getDefaultModel:u}=Je("@cdoing/ai"),s=u(w)||n.model;n.rebuildAgent(w,s),m("system",`Provider switched to: ${w} (model: ${s})`),t("info",`Provider: ${w} (${s})`)}else w?(m("system","Provider switching not available."),t("warning","Provider switching not available")):m("system",`Current provider: ${n.provider}`);break}case"/mode":{let u=n.permissionManager?.mode||"ask";m("system",`Permission mode: ${u}
16
- Available: ask, auto-edit, auto`);break}case"/dir":{if(w){let u=ae.resolve(n.workingDir,w);q.existsSync(u)&&q.statSync(u).isDirectory()?(n.setWorkingDir&&n.setWorkingDir(u),m("system",`Working directory changed to: ${u}`)):m("system",`Directory not found: ${u}`)}else m("system",`Working directory: ${n.workingDir}`);break}case"/config":{if(w.startsWith("set ")){let u=w.substring(4).trim().split(/\s+/);if(u.length>=2){let[s,...x]=u,p=x.join(" ");if(s==="api-key"){let P=ue();P.apiKeys||(P.apiKeys={}),P.apiKeys[n.provider]=p,xe("apiKeys",P.apiKeys),m("system",`API key saved for ${n.provider}.`)}else s==="api-key-helper"?(xe("apiKeyHelper",p),m("system",`API key helper set to: ${p}`)):(xe(s,p),m("system",`Config ${s} set to: ${p}`))}else m("system","Usage: /config set <key> <value>")}else if(w==="show"||!w){let u=ue(),s=Object.entries(u).filter(([x])=>x!=="apiKeys").map(([x,p])=>` ${x}: ${typeof p=="object"?JSON.stringify(p):p}`);m("system",s.length>0?`Configuration:
17
- `+s.join(`
18
- `):"No configuration found. Run /setup to configure.")}else m("system","Usage: /config [show | set <key> <value>]");break}case"/theme":{w&&["dark","light"].includes(w)?(o(w),m("system",`Theme mode switched to: ${w}`),t("success",`Mode: ${w}`)):(m("system","Usage: /theme dark | light (or Ctrl+T for theme picker)"),t("warning","Usage: /theme dark | light"));break}case"/compact":n.agent.compressContext?(n.agent.compressContext(),m("system","Context compressed."),t("success","Context compressed")):(m("system","Context compression not available."),t("warning","Context compression not available"));break;case"/effort":{let u=["low","medium","high","max"];w&&u.includes(w)?(m("system",`Effort level set to: ${w}`),t("info",`Effort: ${w}`)):m("system",`Usage: /effort <${u.join("|")}>`);break}case"/plan":{let u=()=>{if(n.rebuildAgent){let s=n.agent.getHistory();n.rebuildAgent(n.provider,n.model),s.length>0&&n.agent.setHistory(s)}};if(w==="off"||w==="cancel")$.current=!1,n.permissionManager.setMode("default"),u(),m("system","Plan mode cancelled. Switched to build mode.");else if(w==="show")m("system",B.current||"No active plan.");else if(w==="approve"||w==="yes"){if(!$.current){m("system","No plan to approve. Use /plan <request> to create one.");break}$.current=!1,n.permissionManager.setMode("default"),u(),m("system","Plan approved! Switched to build mode. Executing...");let s=["[MODE SWITCH: Plan \u2192 Build]","Your operational mode has changed from plan to build.","You now have full access to write files, run commands, and execute tools.","","## Approved Plan",B.current||"Execute the plan you created.","","## Instructions","Execute the plan step by step. If a step fails, explain why and suggest alternatives."].join(`
19
- `);ce(s)}else if(w==="reject"||w==="no")$.current=!1,n.permissionManager.setMode("default"),u(),m("system","Plan rejected. Switched to build mode.");else if(!w)$.current?($.current=!1,n.permissionManager.setMode("default"),u(),m("system","Plan mode OFF. Switched to build mode.")):(n.permissionManager.setMode("plan"),u(),m("system",`Plan mode ON (read-only). Send a message to start planning.
20
- Use /plan approve to execute, /plan reject to cancel.`));else{n.permissionManager.setMode("plan"),u(),$.current=!0,m("system",`Plan mode ON (read-only). Generating plan...
21
- Use /plan approve when ready, /plan reject to cancel.`);let s=["[PLAN MODE \u2014 Read-only]","Analyze this request and create a detailed step-by-step implementation plan.","You are in read-only mode \u2014 you can read files, search code, and explore, but CANNOT write or execute.","When your plan is complete, call plan_exit with a summary.","",`Request: ${w}`].join(`
22
- `);ce(s)}break}case"/permissions":{let u=Oe(),s=u?.allow||[],x=u?.deny||[],p=["Permission rules:"];x.length>0&&p.push(" Deny: "+x.join(", ")),s.length>0&&p.push(" Allow: "+s.join(", ")),x.length===0&&s.length===0&&p.push(" No custom rules configured."),m("system",p.join(`
23
- `));break}case"/hooks":{try{let u=ae.join(n.workingDir,".cdoing","hooks.json");if(q.existsSync(u)){let s=JSON.parse(q.readFileSync(u,"utf-8")),x=Object.keys(s);m("system",x.length>0?`Configured hooks:
24
- `+x.map(p=>` ${p}: ${JSON.stringify(s[p])}`).join(`
25
- `):"No hooks configured.")}else m("system","No hooks file found (.cdoing/hooks.json).")}catch{m("system","No hooks configured.")}break}case"/rules":{try{let u=ae.join(n.workingDir,".cdoing","rules");if(q.existsSync(u)){let s=q.readdirSync(u).filter(x=>x.endsWith(".md"));m("system",s.length>0?`Project rules:
26
- `+s.map(x=>` ${x}`).join(`
27
- `):"No rules found in .cdoing/rules/.")}else m("system","No rules directory found (.cdoing/rules/).")}catch{m("system","No rules configured.")}break}case"/memory":m("system","Memory store: not yet implemented in TUI. Coming soon.");break;case"/tasks":m("system","Task list: not yet implemented in TUI. Coming soon.");break;case"/context":m("system",["Context providers (use @ to invoke):"," @terminal \u2014 Recent terminal output"," @url \u2014 Fetch URL content"," @tree \u2014 Project file tree"," @codebase \u2014 Full codebase context"," @clip \u2014 Clipboard content"," @file \u2014 Include a file"].join(`
28
- `));break;case"/mcp":m("system","MCP server management: not yet implemented in TUI. Coming soon.");break;case"/history":case"/ls":{let u=We().slice(0,20);if(u.length>0){let s=u.map(x=>{let p=x.id.substring(0,12),P=It(x.updatedAt),Y=x.messages.filter(J=>J.role==="user").length;return` ${p} ${P.padEnd(10)} (${Y} msgs) ${x.title}`});m("system",`Conversations:
29
- `+s.join(`
30
- `)+`
31
-
32
- Use /resume <id> to continue. Ctrl+S for interactive browser.`)}else m("system","No saved conversations found.");break}case"/resume":{if(!w){m("system","Usage: /resume <conversation-id>");break}let u=ut(w);if(!u){m("system",`Conversation not found: ${w}`);break}M.current=u,r([]),n.agent.clearHistory(),F.current=0,L.current=0;for(let s of u.messages)if(s.role==="user"||s.role==="assistant"){let x={id:`msg-${++v.current}`,role:s.role,content:s.content,timestamp:s.timestamp};r(p=>[...p,x])}m("system",`Resumed conversation: ${u.title}`);break}case"/view":{if(!w){m("system","Usage: /view <conversation-id>");break}let u=ut(w);if(!u){m("system",`Conversation not found: ${w}`);break}let s=u.messages.filter(x=>x.role!=="tool").slice(-20).map(x=>{let p=x.role==="user"?"\u276F":"\u25C6",P=x.content.length>100?x.content.substring(0,97)+"...":x.content;return` ${p} ${P.replace(/\n/g," ")}`});m("system",`Conversation: ${u.title}
33
-
34
- ${s.join(`
35
- `)}`);break}case"/fork":{let u=w?ut(w):M.current;if(!u){m("system",w?`Conversation not found: ${w}`:"No active conversation to fork.");break}let s=Pt(u);s?m("system",`Forked conversation: ${s.id.substring(0,12)} \u2014 "${s.title}"`):m("system","Failed to fork conversation.");break}case"/delete":{if(!w){m("system","Usage: /delete <conversation-id>");break}Ot(w)?m("system",`Conversation deleted: ${w}`):m("system",`Conversation not found: ${w}`);break}case"/bg":{if(!w){m("system","Usage: /bg <prompt>");break}Ke(w);break}case"/jobs":{let u=U.current;if(w){let s=u.find(x=>x.id===w);if(s){let x=s.completedAt?`${((s.completedAt-s.startedAt)/1e3).toFixed(1)}s`:`${((Date.now()-s.startedAt)/1e3).toFixed(1)}s (running)`,p=s.result?s.result.length>500?s.result.substring(0,497)+"...":s.result:s.error||"(no output)";m("system",`Job ${s.id} [${s.status}] (${x}):
36
- Prompt: ${s.prompt}
37
- Result: ${p}`)}else m("system",`Job not found: ${w}`)}else if(u.length>0){let s=u.map(x=>` ${x.status==="running"?"\u23F3":x.status==="done"?"\u2713":"\u2717"} ${x.id} ${x.status} ${x.prompt.substring(0,50)}${x.prompt.length>50?"...":""}`);m("system",`Background jobs:
38
- `+s.join(`
39
- `))}else m("system","No background jobs.");break}case"/btw":{if(!w){m("system","Usage: /btw <question>");break}let u={id:`msg-${++v.current}`,role:"user",content:`(btw) ${w}`,timestamp:Date.now()};r(p=>[...p,u]),b(!0),a(""),e.onStatus("Processing...");let s="",x={onToken:p=>{s+=p,a(P=>P+p)},onToolCall:()=>{},onToolResult:()=>{},onComplete:()=>{if(s.trim()){let p={id:`msg-${++v.current}`,role:"assistant",content:s.trim(),timestamp:Date.now()};r(P=>[...P,p]),a("")}b(!1),e.onStatus("Ready")},onError:p=>{m("system",`Error: ${p.message}`),b(!1),e.onStatus("Error")}};n.agent.run(w,x).catch(p=>{m("system",`Error: ${p instanceof Error?p.message:String(p)}`),b(!1),e.onStatus("Error")});break}case"/login":case"/setup":e.onOpenDialog?e.onOpenDialog("setup"):m("system","Setup wizard: configure via ~/.cdoing/config.json or run the base CLI with --login.");break;case"/logout":{try{let{fullLogout:u}=Je("@cdoing/core"),s=u(n.provider);n.agent.invalidate(),m("system",s)}catch{m("system","OAuth logout not available.")}break}case"/auth-status":{let u=ue(),s=["Authentication Status:",""];try{let{getAllOAuthStatuses:P}=Je("@cdoing/core"),Y=P();s.push("OAuth:");let J=!1;for(let me of Y){if(me.status==="none")continue;J=!0;let ot=me.status==="active"?"\u2713":"\u2717",xr=me.status==="active"?"active":"expired",hr=me.expiresAt?new Date(me.expiresAt).toLocaleString():"unknown";s.push(` ${ot} ${me.name}: ${xr}`),me.expiresAt&&s.push(` Expires: ${hr}`)}J||s.push(" None")}catch{s.push("OAuth: unavailable")}if(s.push(""),s.push("Stored API keys:"),u.apiKeys&&Object.keys(u.apiKeys).length>0)for(let[P,Y]of Object.entries(u.apiKeys)){let J=String(Y),me=J.slice(0,8)+"..."+J.slice(-4);s.push(` \u2713 ${P}: ${me}`)}else s.push(" None");s.push(""),s.push("Environment variables:");let x=[["ANTHROPIC_API_KEY",process.env.ANTHROPIC_API_KEY],["OPENAI_API_KEY",process.env.OPENAI_API_KEY],["GOOGLE_API_KEY",process.env.GOOGLE_API_KEY]],p=!1;for(let[P,Y]of x)if(Y){p=!0;let J=Y.slice(0,8)+"..."+Y.slice(-4);s.push(` \u2713 ${P}: ${J}`)}p||s.push(" None"),m("system",s.join(`
40
- `));break}case"/doctor":{let u=["System health check:"],s=ue(),x=process.env[`${n.provider.toUpperCase()}_API_KEY`],p=!!(s.apiKeys?.[n.provider]||x);if(!p)try{let{getOAuthStatus:ot}=Je("@cdoing/core");p=ot(n.provider).status==="active"}catch{}u.push(` Provider: ${n.provider} ${p?"\u2713 Authenticated":"\u2717 No API key or OAuth token"}`),u.push(` Model: ${n.model}`),u.push(` Working dir: ${n.workingDir} ${q.existsSync(n.workingDir)?"\u2713":"\u2717"}`);let P=q.existsSync(ae.join(n.workingDir,".cdoing")),Y=q.existsSync(ae.join(n.workingDir,".claude"));u.push(` Project config: ${P?".cdoing/ \u2713":Y?".claude/ \u2713":"\u2717 none"}`),u.push(` Node: ${process.version}`),u.push(` Platform: ${process.platform} ${process.arch}`);let J=We();u.push(` Conversations: ${J.length} saved`);let me=U.current.filter(ot=>ot.status==="running");me.length>0&&u.push(` Background jobs: ${me.length} running`),m("system",u.join(`
41
- `));break}case"/init":{let u=ae.join(n.workingDir,".cdoing");if(q.existsSync(u))m("system","Project already initialized (.cdoing/ exists).");else try{q.mkdirSync(u,{recursive:!0}),q.mkdirSync(ae.join(u,"rules"),{recursive:!0}),q.writeFileSync(ae.join(u,"config.md"),`# Project Configuration
42
-
43
- Describe your project here for the AI assistant.
44
- `,"utf-8"),m("system","Project initialized. Created .cdoing/ with config.md and rules/.")}catch(s){m("system",`Failed to initialize: ${s instanceof Error?s.message:String(s)}`)}break}case"/queue":m("system","Message queue is empty.");break;case"/help":m("system",["Available commands:",""," Session"," /clear Clear chat history"," /new Start new conversation"," /compact Compress context window"," /btw <question> Ask without adding to history",""," Configuration"," /model [name] Show/change model"," /provider [name] Show/change provider"," /mode Show permission mode"," /dir [path] Show/change working directory"," /config Show configuration"," /config set k v Set a config value"," /theme <mode> Switch theme (dark/light/auto)"," /effort <level> Set effort (low/medium/high/max)"," /plan <on|off> Toggle plan mode",""," History"," /history, /ls List saved conversations"," /resume <id> Resume conversation"," /view <id> View conversation messages"," /fork [id] Fork current/specified conversation"," /delete <id> Delete conversation",""," Background"," /bg <prompt> Run prompt in background"," /jobs [id] List/inspect background jobs",""," System"," /permissions Show permission rules"," /hooks Show configured hooks"," /rules Show project rules"," /context Show context providers"," /mcp MCP server management"," /doctor System health check"," /usage Show token usage"," /auth-status Show authentication status",""," /setup Run setup wizard"," /login Open setup wizard"," /logout Clear OAuth tokens"," /init Initialize project config"," /exit Quit","","Keyboard shortcuts:"," Ctrl+V Paste text or image"," Ctrl+U Clear input line"," Ctrl+W Delete last word"," Ctrl+P Command palette"," Ctrl+O Model picker"," Ctrl+N New session"," Ctrl+S Session browser"," Tab Switch mode (Build/Plan)"," \u2192 Accept autocomplete"," \u2191/\u2193 Navigate suggestions"," Escape Close dropdown","","Shell: prefix with ! or type commands directly (ls, git, npm, etc.)","Context: use @terminal, @url, @tree, @codebase, @clip, @file in messages"].join(`
45
- `));break;case"/usage":m("system",`Tokens: ${F.current.toLocaleString()}\u2192${L.current.toLocaleString()} (${(F.current+L.current).toLocaleString()} total)`);break;case"/exit":case"/quit":process.exit(0);break;default:m("system",`Unknown command: ${O}. Type /help for available commands.`),t("error",`Unknown command: ${O}`)}},Pe=S=>{m("user",`!${S}`);let O="",W="";try{O=wi(S,{cwd:n.workingDir,env:{...process.env},encoding:"utf-8",timeout:12e4,maxBuffer:10*1024*1024})}catch(u){u.stdout&&(O=String(u.stdout)),u.stderr&&(W=String(u.stderr)),u.status!==void 0&&u.status!==0?W+=`
46
- [exited with code ${u.status}]`:!u.stdout&&!u.stderr&&u.message&&(W=u.message)}let w=(O+(W?`
47
- ${W}`:"")).trim();m("system",`$ ${S}
48
- ${w||"(no output)"}`),bo(`$ ${S}
49
- ${w}`)},nt=(S,O)=>{let W=l.current.trim();n.agent.interrupt(W),W&&(m("assistant",W+`
50
-
51
- *(interrupted)*`),a("")),b(!1),e.onStatus("Ready"),N(void 0),e.onActiveTool(void 0),I(null),setTimeout(()=>{C(S,O)},100)},He=S=>{R.current.push(S),m("system",`\u{1F4EC} Queued message (${R.current.length} in queue)`),I(null)},Ie=()=>{if(R.current.length>0){let S=R.current.shift();setTimeout(()=>C(S),100)}},ce=async(S,O)=>{if(S.startsWith("/")){Ne(S);return}let W=S.startsWith("!")?S.slice(1).trim():ki(S);if(W){let w=W.trim().split(/\s+/);if(w[0]==="cd"){let u=w.slice(1).join(" ")||process.env.HOME||"/",s=ae.resolve(n.workingDir,u);q.existsSync(s)&&q.statSync(s).isDirectory()?(n.setWorkingDir&&n.setWorkingDir(s),m("system",`Working directory changed to: ${s}`)):m("system",`cd: no such directory: ${s}`);return}Pe(W);return}if(h){I({text:S,images:O});return}await C(S,O)},ye=ve(!1);Si(()=>{e.initialMessage&&!ye.current&&(ye.current=!0,ce(e.initialMessage.text,e.initialMessage.images))},[]);let C=async(S,O)=>{let W=S;($.current||n.permissionManager.getMode()==="plan")&&(W=`[PLAN MODE \u2014 Read-only] You are in plan mode. Do NOT write files, run commands, or modify anything. Only read, search, analyze, and create a plan using the todo tool. When your plan is ready, call plan_exit.
52
-
53
- ${S}`);let w=W;if(So(W))try{w=await yo(S,n.workingDir)}catch{}m("user",S+(O&&O.length>0?` [${O.length} image${O.length>1?"s":""}]`:"")),b(!0),a(""),e.onStatus("Processing...");let u,s=0,x={onToken:p=>{a(P=>P+p)},onToolCall:(p,P)=>{let Y=l.current.trim();Y&&(m("assistant",Y),a(""));let J=typeof P=="object"&&P?P:{},me=J.description||"";u=m("tool",me,{toolName:p,toolStatus:"running",toolInput:J}),N(p),e.onActiveTool(p)},onToolResult:(p,P,Y)=>{if(u){let J=P.length>80?P.substring(0,77)+"...":P;Q(u,{content:J,toolStatus:Y?"error":"done",isError:Y}),u=void 0}N(void 0),e.onActiveTool(void 0)},onCompactStart:p=>{try{m("system",`\u27F3 Compacting context (${p}% used)...`)}catch{}},onCompactEnd:(p,P)=>{try{m("system",`\u2713 Context compacted \u2014 saved ${p.toLocaleString()} tokens (now ${P}%)`)}catch{}},onComplete:()=>{let p=l.current.trim();p&&(m("assistant",p),a("")),b(!1),e.onStatus("Ready"),N(void 0),e.onActiveTool(void 0),e.onTokens(F.current,L.current),Ie()},onError:p=>{let P=l.current.trim();P&&(m("assistant",P),a("")),m("system",`Error: ${p.message}`),t("error",p.message),b(!1),e.onStatus("Error"),N(void 0),e.onActiveTool(void 0)},onUsage:p=>{s+=p.inputTokens,F.current+=p.inputTokens,L.current+=p.outputTokens,e.onTokens(F.current,L.current);let P=Math.min(100,s/2e5*100);e.onContextPercent(P)}};try{await n.agent.run(w,x,O)}catch(p){let P=p instanceof Error?p.message:String(p);m("system",`Error: ${P}`),t("error",P),b(!1),e.onStatus("Error")}};return en("box",{flexDirection:"column",flexGrow:1,paddingLeft:2,paddingRight:2,paddingTop:1,paddingBottom:1,gap:1,children:[we("scrollbox",{stickyScroll:!0,stickyStart:"bottom",flexGrow:1,scrollY:!0,children:we(eo,{messages:i,streamingText:c,isStreaming:h})}),en("box",{flexDirection:"column",flexShrink:0,children:[f&&we(ro,{toolName:f.toolName,message:f.message,onDecision:S=>{f.resolve(S),g(null)}}),T&&we(Ci,{message:T.text,onInterrupt:()=>nt(T.text,T.images),onQueue:()=>He(T.text),onCancel:()=>I(null)}),h&&!c&&!T&&we(co,{label:k||"Thinking..."}),we($t,{onSubmit:ce,disabled:!1,suppressInput:e.dialogOpen,placeholder:h?"Type to interrupt or queue...":void 0,workingDir:n.workingDir,mode:d,onModeChange:y,modelLabel:n.model})]})]})}var Di,ko=K(()=>{"use strict";no();Jt();io();lo();Ct();te();Ht();zt();Qt();vo();Di=new Set(["ls","ll","la","pwd","cd","mkdir","rmdir","rm","cp","mv","cat","head","tail","touch","echo","env","git","npm","yarn","pnpm","npx","node","ts-node","python","python3","pip","pip3","docker","docker-compose","grep","find","which","whereis","curl","wget","chmod","chown","ln","ps","kill","df","du","open","code","vim","vi","nano","less","more","man","top","htop"])});import{TextAttributes as Mi}from"@opentui/core";import{Fragment as Rt,jsx as de,jsxs as qe}from"@opentui/react/jsx-runtime";function Co(e){let{theme:n}=G(),o=n,t=process.env.HOME||"",i=t&&e.workingDir.startsWith(t)?"~"+e.workingDir.slice(t.length):e.workingDir,r=e.tokens?` ${e.tokens.input.toLocaleString()}\u2192${e.tokens.output.toLocaleString()}`:"",c=e.contextPercent?Math.round(e.contextPercent):0,a=c>0?` ctx:${c}%`:"";return qe("box",{height:1,flexDirection:"row",justifyContent:"space-between",backgroundColor:o.bgSubtle,children:[qe("box",{flexDirection:"row",children:[de("text",{fg:o.primary,attributes:Mi.BOLD,children:` ${e.provider}`}),de("text",{fg:o.textMuted,children:`/${e.model}`}),de("text",{fg:o.textDim,children:" \u2502 "}),de("text",{fg:o.warning,children:e.mode}),r&&qe(Rt,{children:[de("text",{fg:o.textDim,children:" \u2502"}),de("text",{fg:o.textMuted,children:r})]}),a&&qe(Rt,{children:[de("text",{fg:o.textDim,children:" \u2502"}),de("text",{fg:c>75?o.warning:o.textMuted,children:a})]}),e.activeTool&&qe(Rt,{children:[de("text",{fg:o.textDim,children:" \u2502 "}),de("text",{fg:o.toolRunning,children:`\u23F3 ${e.activeTool}`})]}),e.isProcessing&&!e.activeTool&&qe(Rt,{children:[de("text",{fg:o.textDim,children:" \u2502 "}),de("text",{fg:o.primary,children:"thinking..."})]})]}),qe("box",{flexDirection:"row",children:[de("text",{fg:o.textDim,children:i}),de("text",{fg:o.textDim,children:" \u2502 "}),de("text",{fg:o.textMuted,children:"^P:Commands ^O:Model ^C:Quit"})]})]})}var Mo=K(()=>{"use strict";te()});import{TextAttributes as Ti}from"@opentui/core";import{jsx as ft,jsxs as $i}from"@opentui/react/jsx-runtime";function To(e){let{theme:n}=G(),o=n,t=e.tokens?e.tokens.input.toLocaleString():"0",i=e.tokens?e.tokens.output.toLocaleString():"0",r=e.contextPercent?Math.round(e.contextPercent):0,c=r>75?o.error:r>50?o.warning:o.success,a=e.status==="Error"?o.error:e.status==="Processing..."?o.warning:o.success,l=` \u25C6 ${e.title||"Session"} \u2502 ${e.provider}/${e.model} \u2502 ${t}\u2192${i} tokens`;return $i("box",{height:1,flexDirection:"row",backgroundColor:o.bgSubtle,children:[ft("text",{fg:o.primary,attributes:Ti.BOLD,children:l}),ft("text",{fg:o.border,children:" \u2502 "}),ft("text",{fg:c,children:`${r}%`}),ft("box",{flexGrow:1}),ft("text",{fg:a,children:`${e.status} `})]})}var $o=K(()=>{"use strict";te()});import{jsx as tn,jsxs as Ai}from"@opentui/react/jsx-runtime";function Ao(e){let{theme:n}=G(),o=n,t=process.env.HOME||"",i=t&&e.workingDir.startsWith(t)?"~"+e.workingDir.slice(t.length):e.workingDir;return Ai("box",{height:1,flexDirection:"row",backgroundColor:o.bgSubtle,children:[tn("text",{fg:o.textDim,children:` ${i}`}),tn("box",{flexGrow:1}),tn("text",{fg:o.textMuted,children:"^P:Commands ^O:Model ^T:Theme ^S:Sessions ^B:Sidebar "})]})}var Oo=K(()=>{"use strict";te()});import{TextAttributes as nn}from"@opentui/core";import{jsx as ie,jsxs as Bt}from"@opentui/react/jsx-runtime";function Ze(e,n){return e.length>n?e.slice(0,n-1)+"\u2026":e}function Oi(e,n){let o=Math.round(e/100*n);return"\u2588".repeat(o)+"\u2591".repeat(n-o)}function Po(e){let{theme:n}=G(),o=n,t=process.env.HOME||"",i=t&&e.workingDir.startsWith(t)?"~"+e.workingDir.slice(t.length):e.workingDir,r=e.contextPercent?Math.round(e.contextPercent):0,c=r>75?o.error:r>50?o.warning:o.success,a=e.tokens?e.tokens.input.toLocaleString():"0",l=e.tokens?e.tokens.output.toLocaleString():"0",h=e.status==="Error"?o.error:e.status==="Processing..."?o.warning:o.success,b=[],d=()=>b.push({text:"\u2502",fg:o.border}),D=g=>{b.push({text:`\u2502 ${g}`,fg:o.primary,bold:!0})},y=(g,T,I)=>{let R=g?`\u2502 ${g.padEnd(10)} ${Ze(T,_e-14)}`:`\u2502 ${Ze(T,_e-4)}`;b.push({text:R,fg:I||o.text})},k=(g,T)=>{b.push({text:`\u2502 ${g.padEnd(10)} ${T}`,fg:o.textDim})};if(D("Session"),y("",e.sessionTitle||"New Session"),y("Dir",Ze(i,_e-14)),y("Provider",e.provider),y("Model",e.model),e.themeId&&y("Theme",e.themeId),d(),D("Context"),y("Input",`${a} tokens`),y("Output",`${l} tokens`),b.push({text:`\u2502 ${Oi(r,16)} ${r}%`,fg:c}),d(),D("Activity"),b.push({text:`\u2502 Status ${e.status}`,fg:h}),e.activeTool&&b.push({text:`\u2502 Tool ${Ze(e.activeTool,_e-14)}`,fg:o.toolRunning}),d(),e.modifiedFiles&&e.modifiedFiles.length>0){D(`Files (${e.modifiedFiles.length})`);for(let g of e.modifiedFiles.slice(0,6)){let T=g.path.split("/").pop()||g.path,I=(g.additions>0?` +${g.additions}`:"")+(g.deletions>0?` -${g.deletions}`:"");b.push({text:`\u2502 ${Ze(T,_e-12)}${I}`,fg:o.text})}e.modifiedFiles.length>6&&b.push({text:`\u2502 \u2026 ${e.modifiedFiles.length-6} more`,fg:o.textDim}),d()}D("LSP"),y("","LSPs will activate as files are read"),d(),D("Shortcuts"),k("Ctrl+P","Commands"),k("Ctrl+O","Model"),k("Ctrl+T","Theme"),k("Ctrl+N","New session"),k("Ctrl+S","Sessions"),k("Ctrl+B","Sidebar"),k("F1","Help");let N=_e-2,f=[];return f.push({text:" \u25C6 Getting started",fg:o.primary,bold:!0}),f.push({text:"",fg:o.textDim}),f.push({text:" Cdoing includes free models",fg:o.textMuted}),f.push({text:" so you can start immediately.",fg:o.textMuted}),f.push({text:"",fg:o.textDim}),f.push({text:" Connect from 75+ providers to",fg:o.textMuted}),f.push({text:" use other models, including",fg:o.textMuted}),f.push({text:" Claude, GPT, Gemini etc",fg:o.textMuted}),f.push({text:"",fg:o.textDim}),f.push({text:" Connect provider /setup",fg:o.text,bold:!0}),ie("box",{width:_e+2,flexDirection:"column",backgroundColor:o.bgSubtle,children:Bt("box",{flexDirection:"column",flexGrow:1,children:[b.map((g,T)=>ie("box",{height:1,children:ie("text",{fg:g.fg,attributes:g.bold?nn.BOLD:void 0,children:g.text})},T)),ie("box",{flexGrow:1,children:ie("text",{fg:o.border,children:"\u2502"})}),Bt("box",{flexDirection:"column",paddingX:1,children:[ie("box",{height:1,children:ie("text",{fg:o.border,children:"\u250C"+"\u2500".repeat(N)+"\u2510"})}),f.map((g,T)=>Bt("box",{height:1,children:[ie("text",{fg:o.border,children:"\u2502"}),ie("text",{fg:g.fg,attributes:g.bold?nn.BOLD:void 0,children:g.text.padEnd(N)}),ie("text",{fg:o.border,children:"\u2502"})]},`card-${T}`)),ie("box",{height:1,children:ie("text",{fg:o.border,children:"\u2514"+"\u2500".repeat(N)+"\u2518"})})]}),ie("box",{height:1,paddingX:1,children:ie("text",{fg:o.textDim,children:Ze((()=>{let g=process.env.HOME||"";return g&&e.workingDir.startsWith(g)?"~"+e.workingDir.slice(g.length):e.workingDir})(),_e-2)})}),Bt("box",{height:1,paddingX:1,children:[ie("text",{fg:o.success,children:"\u25CF "}),ie("text",{fg:o.text,attributes:nn.BOLD,children:"Cdoing"}),ie("text",{fg:o.textDim,children:" Agent"})]})]})})}var _e,Io=K(()=>{"use strict";te();_e=34});import{TextAttributes as Ro}from"@opentui/core";import{useState as Bo,useMemo as Pi}from"react";import{useKeyboard as Ii,useTerminalDimensions as Ri}from"@opentui/react";import{getProviders as Bi}from"@cdoing/ai";import{Fragment as Eo,jsx as he,jsxs as Et}from"@opentui/react/jsx-runtime";function Lo(e){let{theme:n,customBg:o}=G(),t=n,i=Ri(),r=_o[e.provider]||[],[c,a]=Bo(!1),[l,h]=Bo(""),b=Pi(()=>{let D=r.map(y=>({name:y.name,description:[y.hint||"",y.id===e.currentModel?"\u25CF current":""].filter(Boolean).join(" "),value:y.id}));return D.push({name:"Custom model...",description:"type any model name",value:"__custom__"}),D},[r,e.currentModel]),d=Math.max(0,r.findIndex(D=>D.id===e.currentModel));return Ii(D=>{if(D.name==="escape"||D.ctrl&&D.name==="c"){if(c){a(!1);return}e.onClose();return}if(c)if(D.name==="return"){let y=l.trim();y&&e.onSelect(y)}else D.name==="backspace"?h(y=>y.slice(0,-1)):D.ctrl&&D.name==="u"?h(""):D.sequence&&D.sequence.length===1&&!D.ctrl&&!D.meta&&h(y=>y+D.sequence)}),Et("box",{borderStyle:"double",borderColor:t.primary,backgroundColor:o||t.bg,paddingX:1,paddingY:1,flexDirection:"column",position:"absolute",top:Math.max(2,Math.floor((i.height||24)*.25)),left:Math.max(1,Math.floor(((i.width||80)-Math.min(60,(i.width||80)-4))/2)),width:Math.min(60,(i.width||80)-4),children:[he("text",{fg:t.primary,attributes:Ro.BOLD,children:" Select Model"}),he("text",{fg:t.textDim,children:` Provider: ${e.provider}`}),he("text",{children:""}),c?Et(Eo,{children:[he("text",{fg:t.text,children:" Enter custom model ID:"}),Et("box",{flexDirection:"row",children:[he("text",{fg:t.primary,children:" > "}),he("text",{fg:t.text,children:l}),he("text",{fg:t.primary,attributes:Ro.BOLD,children:"_"})]}),he("text",{children:""}),he("text",{fg:t.textDim,children:" Enter Confirm Ctrl+U Clear Esc Back"})]}):Et(Eo,{children:[he("select",{options:b,focused:!c,selectedIndex:d,height:Math.min(b.length,10),showDescription:!0,backgroundColor:o||void 0,focusedBackgroundColor:o||void 0,textColor:t.text,focusedTextColor:t.text,selectedBackgroundColor:t.primary,selectedTextColor:t.bg,descriptionColor:t.textDim,selectedDescriptionColor:t.bg,showScrollIndicator:b.length>10,onSelect:(D,y)=>{y&&(y.value==="__custom__"?(a(!0),h("")):e.onSelect(y.value))}}),he("text",{children:""}),he("text",{fg:t.textDim,children:" \u2191\u2193 Navigate Enter Select Esc Close"})]})]})}var _o,No=K(()=>{"use strict";te();_o={};for(let e of Bi())_o[e.id]=e.models.map(n=>({id:n.id,name:n.label,hint:n.hint}))});import{TextAttributes as jo}from"@opentui/core";import{useState as Ei,useMemo as Fo}from"react";import{useKeyboard as _i,useTerminalDimensions as Li}from"@opentui/react";import{jsx as oe,jsxs as _t}from"@opentui/react/jsx-runtime";function on(e,n){if(!e)return!0;let o=n.toLowerCase(),t=e.toLowerCase(),i=0;for(let r=0;r<o.length&&i<t.length;r++)o[r]===t[i]&&i++;return i===t.length}function Go(e){let{theme:n,customBg:o}=G(),t=n,i=Li(),[r,c]=Ei(""),a=Math.min(64,(i.width||80)-4),l=Math.max(8,Math.floor((i.height||24)*.6)),h=Fo(()=>Ni.filter(d=>on(r,d.label)||on(r,d.category)||on(r,d.id)),[r]),b=Fo(()=>{let d=[],D="";for(let y of h){y.category!==D&&(D=y.category);let k=y.shortcut||"";d.push({name:`${y.icon||" "} ${y.label}`,description:[y.category,k].filter(Boolean).join(" "),value:y.id})}return d},[h]);return _i(d=>{if(d.name==="escape"||d.ctrl&&d.name==="p"){e.onClose();return}if(!(d.name==="up"||d.name==="down"||d.name==="return")){if(d.name==="backspace"){c(D=>D.slice(0,-1));return}if(d.ctrl&&d.name==="u"){c("");return}d.sequence&&d.sequence.length===1&&!d.ctrl&&!d.meta&&c(D=>D+d.sequence)}}),_t("box",{borderStyle:"double",borderColor:t.primary,backgroundColor:o||t.bg,paddingX:1,paddingY:0,flexDirection:"column",position:"absolute",top:Math.max(1,Math.floor((i.height||24)*.1)),left:Math.max(1,Math.floor(((i.width||80)-a)/2)),width:a,children:[_t("box",{flexDirection:"row",flexShrink:0,height:1,children:[oe("text",{fg:t.primary,attributes:jo.BOLD,flexGrow:1,children:" Commands"}),oe("text",{fg:t.textDim,children:"Ctrl+P "})]}),oe("box",{height:1,flexShrink:0,children:oe("text",{fg:t.border,children:"\u2500".repeat(a-4)})}),_t("box",{flexDirection:"row",flexShrink:0,height:1,children:[oe("text",{fg:t.textMuted,children:" > "}),oe("text",{fg:t.text,children:r||""}),oe("text",{fg:t.primary,attributes:jo.BOLD,children:"\u2588"})]}),oe("box",{height:1,flexShrink:0,children:oe("text",{fg:t.border,children:"\u2500".repeat(a-4)})}),b.length>0?oe("select",{options:b,focused:!0,height:Math.min(l,b.length),showDescription:!0,backgroundColor:o||void 0,focusedBackgroundColor:o||void 0,textColor:t.text,focusedTextColor:t.text,selectedBackgroundColor:t.primary,selectedTextColor:t.bg,descriptionColor:t.textDim,selectedDescriptionColor:t.bg,showScrollIndicator:b.length>l,onSelect:(d,D)=>{D?.value&&e.onSelect(D.value)}}):oe("box",{height:1,children:oe("text",{fg:t.textDim,children:" No matching commands"})}),oe("box",{height:1,flexShrink:0,children:oe("text",{fg:t.border,children:"\u2500".repeat(a-4)})}),_t("box",{flexDirection:"row",height:1,flexShrink:0,children:[oe("text",{fg:t.textDim,children:" \u2191\u2193 navigate "}),oe("text",{fg:t.textDim,children:"enter select "}),oe("text",{fg:t.textDim,children:"type to filter "}),oe("text",{fg:t.textDim,children:"esc close"})]})]})}var Ni,Uo=K(()=>{"use strict";te();Ni=[{id:"session:new",label:"New Session",shortcut:"Ctrl+N",category:"Session",icon:"+"},{id:"session:browse",label:"Browse Sessions",shortcut:"Ctrl+S",category:"Session",icon:"\u25E6"},{id:"session:clear",label:"Clear History",shortcut:"",category:"Session",icon:"\u2715"},{id:"model:switch",label:"Switch Model",shortcut:"Ctrl+O",category:"Model",icon:"\u25C6"},{id:"model:provider",label:"Switch Provider",shortcut:"",category:"Model",icon:"\u25C6"},{id:"theme:picker",label:"Browse Themes",shortcut:"Ctrl+T",category:"Appearance",icon:"\u25C8"},{id:"theme:dark",label:"Dark Mode",shortcut:"",category:"Appearance",icon:"\u25CF"},{id:"theme:light",label:"Light Mode",shortcut:"",category:"Appearance",icon:"\u25CB"},{id:"display:sidebar",label:"Toggle Sidebar",shortcut:"Ctrl+B",category:"Appearance",icon:"\u2590"},{id:"tool:shell",label:"Run Shell Command",shortcut:"",category:"Tools",icon:"$"},{id:"tool:search",label:"Search Codebase",shortcut:"",category:"Tools",icon:"?"},{id:"tool:tree",label:"File Tree",shortcut:"",category:"Tools",icon:"\u251C"},{id:"system:status",label:"System Status",shortcut:"",category:"System",icon:"i"},{id:"system:help",label:"Help",shortcut:"F1",category:"System",icon:"?"},{id:"system:doctor",label:"Doctor (Diagnostics)",shortcut:"",category:"System",icon:"+"},{id:"system:setup",label:"Setup Wizard (Connect Provider)",shortcut:"",category:"System",icon:"\u2699"},{id:"system:exit",label:"Exit",shortcut:"Ctrl+C",category:"System",icon:"\u23FB"}]});import{TextAttributes as Wo}from"@opentui/core";import{useKeyboard as ji,useTerminalDimensions as Fi}from"@opentui/react";import{jsx as be,jsxs as gt}from"@opentui/react/jsx-runtime";function rn(e){let n=e.theme;return gt("box",{flexDirection:"column",flexShrink:0,children:[be("text",{fg:n.primary,attributes:Wo.BOLD,children:` ${e.title}`}),be("text",{children:""}),e.entries.map(o=>gt("box",{flexDirection:"row",children:[be("text",{fg:n.secondary,children:` ${o.key.padEnd(qi)}`}),be("text",{fg:n.textMuted,children:o.description})]},o.key)),be("text",{children:""})]})}function qo(e){let{theme:n,customBg:o}=G(),t=n,i=Fi(),r=Math.min(70,(i.width||80)-4),c=Math.max(10,(i.height||24)-6);return ji(a=>{(a.name==="escape"||a.name==="q")&&e.onClose()}),gt("box",{borderStyle:"double",borderColor:t.primary,backgroundColor:o||t.bg,paddingX:2,paddingY:1,flexDirection:"column",position:"absolute",top:Math.max(1,Math.floor((i.height||24)*.05)),left:Math.max(1,Math.floor(((i.width||80)-r)/2)),width:r,height:c,children:[gt("box",{flexDirection:"row",flexShrink:0,children:[be("text",{fg:t.primary,attributes:Wo.BOLD,flexGrow:1,children:" Help"}),be("text",{fg:t.textDim,children:"esc"})]}),be("text",{flexShrink:0,children:""}),be("scrollbox",{flexGrow:1,children:gt("box",{flexShrink:0,children:[be(rn,{title:"Keyboard Shortcuts",entries:Gi,theme:t}),be(rn,{title:"Slash Commands",entries:Ui,theme:t}),be(rn,{title:"@Mentions",entries:Wi,theme:t})]})})]})}var Gi,Ui,Wi,qi,Ko=K(()=>{"use strict";te();Gi=[{key:"Ctrl+P",description:"Command palette"},{key:"Ctrl+O",description:"Switch model"},{key:"Ctrl+N",description:"New session"},{key:"Ctrl+S",description:"Browse sessions"},{key:"F1",description:"Show this help"},{key:"Ctrl+V",description:"Paste text or image"},{key:"Ctrl+U",description:"Clear input line"},{key:"Ctrl+W",description:"Delete last word"},{key:"Tab",description:"Switch mode (Build / Plan)"},{key:"\u2192 (Right)",description:"Accept autocomplete"},{key:"Up / Down",description:"Navigate suggestions"},{key:"Escape",description:"Close dialog / dropdown"},{key:"Ctrl+C",description:"Quit"}],Ui=[{key:"/help",description:"Show help"},{key:"/clear",description:"Clear chat history"},{key:"/new",description:"Start new conversation"},{key:"/compact",description:"Compress context window"},{key:"/btw <question>",description:"Ask without adding to history"},{key:"/model [name]",description:"Show/change model"},{key:"/provider [name]",description:"Show/change provider"},{key:"/mode",description:"Show permission mode"},{key:"/dir [path]",description:"Show/change working directory"},{key:"/config",description:"Show configuration"},{key:"/config set k v",description:"Set a config value"},{key:"/theme <mode>",description:"Switch theme (dark/light/auto)"},{key:"/effort <level>",description:"Set effort level"},{key:"/plan <on|off>",description:"Toggle plan mode"},{key:"/history",description:"List saved conversations"},{key:"/resume <id>",description:"Resume conversation"},{key:"/view <id>",description:"View conversation messages"},{key:"/fork [id]",description:"Fork conversation"},{key:"/delete <id>",description:"Delete conversation"},{key:"/bg <prompt>",description:"Run prompt in background"},{key:"/jobs [id]",description:"List/inspect background jobs"},{key:"/permissions",description:"Show permission rules"},{key:"/hooks",description:"Show configured hooks"},{key:"/rules",description:"Show project rules"},{key:"/context",description:"Show context providers"},{key:"/mcp",description:"MCP server management"},{key:"/doctor",description:"System health check"},{key:"/usage",description:"Show token usage"},{key:"/auth-status",description:"Show authentication status"},{key:"/setup",description:"Run setup wizard"},{key:"/login",description:"Open setup wizard"},{key:"/logout",description:"Clear OAuth tokens"},{key:"/init",description:"Initialize project config"},{key:"/exit",description:"Quit"}],Wi=[{key:"@terminal",description:"Recent terminal output"},{key:"@url",description:"Fetch URL content"},{key:"@tree",description:"Directory tree"},{key:"@codebase",description:"Search codebase"},{key:"@clip",description:"Clipboard contents"},{key:"@file",description:"Include file"}],qi=20});import{TextAttributes as et}from"@opentui/core";import{useState as sn,useMemo as an}from"react";import{useKeyboard as Ki,useTerminalDimensions as Hi}from"@opentui/react";import{Fragment as Jo,jsx as ee,jsxs as xt}from"@opentui/react/jsx-runtime";function Vo(e){let{theme:n,themeId:o,mode:t,customBg:i,setThemeId:r,setMode:c,setCustomBg:a}=G(),l=n,h=Hi(),b=o,d=t,D=i,y=An(),[k,N]=sn("mode"),[f,g]=sn(i||""),[T,I]=sn(""),R=an(()=>[{name:"Dark Mode",description:t==="dark"?"active":"",value:"dark"},{name:"Light Mode",description:t==="light"?"active":"",value:"light"}],[t]),F=an(()=>{if(!f)return Ho;let $=f.toLowerCase();return Ho.filter(B=>B.value.toLowerCase().startsWith($)||B.name.toLowerCase().includes($))},[f]),L=an(()=>(T?y.filter(B=>{let m=Ye[B],Q=T.toLowerCase();return B.toLowerCase().includes(Q)||m.name.toLowerCase().includes(Q)}):y).map(B=>({name:Ye[B].name,description:B===o?"* current":B,value:B})),[T,y,o]),v=()=>{N($=>{let B=cn.indexOf($);return cn[(B+1)%cn.length]})},M=$=>/^#[0-9a-fA-F]{6}$/.test($);Ki($=>{if($.name==="escape"){r(b),c(d),a(D),e.onClose();return}if($.name==="tab"){v();return}if(k==="custombg"){if($.name==="up"||$.name==="down"||$.name==="return")return;if($.name==="backspace"){g(B=>B.slice(0,-1));return}if($.ctrl&&$.name==="u"){g(""),a(null);return}if($.sequence&&$.sequence.length===1&&!$.ctrl&&!$.meta){g(B=>{let m=B+$.sequence;return M(m)&&a(m),m});return}return}if(k==="themes"){if($.name==="up"||$.name==="down"||$.name==="return")return;if($.name==="backspace"){I(B=>B.slice(0,-1));return}if($.sequence&&$.sequence.length===1&&!$.ctrl&&!$.meta){I(B=>B+$.sequence);return}return}});let U=Math.min(60,(h.width||80)-4),H=Math.max(3,Math.floor((h.height||24)*.2));return xt("box",{borderStyle:"double",borderColor:l.primary,backgroundColor:l.bg,paddingX:1,paddingY:1,flexDirection:"column",position:"absolute",top:Math.max(1,Math.floor((h.height||24)*.1)),left:Math.max(1,Math.floor(((h.width||80)-U)/2)),width:U,children:[ee("text",{fg:l.primary,attributes:et.BOLD,children:" Themes"}),ee("text",{fg:l.textDim,children:` Mode: ${t} \u2022 ${L.length} themes${i?` \u2022 BG: ${i}`:""}`}),ee("text",{children:""}),ee("text",{fg:k==="mode"?l.primary:l.textDim,attributes:k==="mode"?et.BOLD:void 0,children:" Appearance"}),ee("select",{options:R,focused:k==="mode",selectedIndex:t==="dark"?0:1,height:2,showDescription:!1,backgroundColor:i||void 0,focusedBackgroundColor:i||void 0,textColor:l.textMuted,focusedTextColor:l.text,selectedBackgroundColor:l.primary,selectedTextColor:l.bg,onSelect:($,B)=>{B?.value&&(c(B.value),v())}}),ee("text",{children:""}),ee("text",{fg:k==="themes"?l.primary:l.textDim,attributes:k==="themes"?et.BOLD:void 0,children:" Color Themes"}),k==="themes"&&xt("box",{flexDirection:"row",children:[ee("text",{fg:l.textMuted,children:" Search: "}),ee("text",{fg:l.text,children:T||""}),ee("text",{fg:l.primary,attributes:et.BOLD,children:"_"})]}),ee("select",{options:L,focused:k==="themes",height:H,showDescription:!0,backgroundColor:i||void 0,focusedBackgroundColor:i||void 0,textColor:l.text,focusedTextColor:l.text,selectedBackgroundColor:l.primary,selectedTextColor:l.bg,descriptionColor:l.textDim,selectedDescriptionColor:l.bg,showScrollIndicator:L.length>H,onChange:($,B)=>{B?.value&&(r(B.value),a(null),g(""))},onSelect:($,B)=>{e.onClose()}}),ee("text",{children:""}),ee("text",{fg:k==="custombg"?l.primary:l.textDim,attributes:k==="custombg"?et.BOLD:void 0,children:" Custom Background Override"}),xt("box",{flexDirection:"row",children:[ee("text",{fg:l.textMuted,children:" Hex: "}),k==="custombg"?xt(Jo,{children:[ee("text",{fg:M(f)?l.success:l.text,children:f||""}),ee("text",{fg:l.primary,attributes:et.BOLD,children:"_"})]}):ee("text",{fg:i?l.success:l.textDim,children:i||"(using theme default)"})]}),k==="custombg"&&xt(Jo,{children:[ee("text",{fg:l.textDim,children:" Type #hex, Ctrl+U clear, \u2191\u2193 presets, Enter apply"}),ee("select",{options:F,focused:k==="custombg",height:Math.min(6,F.length),showDescription:!1,backgroundColor:i||void 0,focusedBackgroundColor:i||void 0,textColor:l.textMuted,focusedTextColor:l.text,selectedBackgroundColor:l.primary,selectedTextColor:l.bg,showScrollIndicator:F.length>6,onChange:($,B)=>{B?.value&&(g(B.value),a(B.value))},onSelect:($,B)=>{B?.value&&(g(B.value),a(B.value)),e.onClose()}})]}),ee("text",{children:""}),ee("text",{fg:l.textDim,children:" Tab Section \u2191\u2193 Navigate Enter Select Esc Cancel"})]})}var cn,Ji,Ho,Yo=K(()=>{"use strict";te();cn=["mode","themes","custombg"],Ji=[{hex:"#000000",name:"Black"},{hex:"#0a0a0a",name:"AMOLED Black"},{hex:"#0d1117",name:"GitHub Dark"},{hex:"#1a1b26",name:"Tokyo Night"},{hex:"#1e1e2e",name:"Catppuccin"},{hex:"#191724",name:"Ros\xE9 Pine"},{hex:"#282828",name:"Gruvbox"},{hex:"#282a36",name:"Dracula"},{hex:"#263238",name:"Material"},{hex:"#262335",name:"Synthwave"},{hex:"#272822",name:"Monokai"},{hex:"#2d353b",name:"Everforest"},{hex:"#2e3440",name:"Nord"},{hex:"#002b36",name:"Solarized Dark"},{hex:"#193549",name:"Cobalt2"},{hex:"#032424",name:"Dark Teal"},{hex:"#1a1a2e",name:"Midnight Blue"},{hex:"#0f0f23",name:"Deep Space"},{hex:"#1b2838",name:"Steam"},{hex:"#2b2b2b",name:"VS Code Dark"},{hex:"#fdf6e3",name:"Solarized Light"},{hex:"#ffffff",name:"White"},{hex:"#f5f5f5",name:"Light Gray"},{hex:"#eff1f5",name:"Catppuccin Latte"}],Ho=Ji.map(e=>({name:`${e.hex} ${e.name}`,description:"",value:e.hex}))});import{TextAttributes as ht}from"@opentui/core";import{useState as bt}from"react";import{useKeyboard as Vi,useTerminalDimensions as Yi}from"@opentui/react";import{jsx as X,jsxs as Le}from"@opentui/react/jsx-runtime";function zo(e){let{theme:n,customBg:o}=G(),t=n,i=Yi(),[r,c]=bt(()=>We()),[a,l]=bt(0),[h,b]=bt(!1),[d,D]=bt(!1),[y,k]=bt(0),N=Math.max(5,Math.floor((i.height||20)-10));if(Vi(f=>{if(d){if(f.name==="escape"||f.name==="q")D(!1),k(0);else if(f.name==="up"||f.name==="k")k(g=>Math.max(0,g-1));else if(f.name==="down"||f.name==="j"){let g=r[a];if(g){let T=g.messages.filter(I=>I.role!=="tool");k(I=>Math.min(T.length-1,I+1))}}else if(f.name==="return"){let g=r[a];g&&e.onResume(g)}return}if(h){if(f.name==="y"){let g=r[a];if(g){Ot(g.id);let T=We();c(T),l(I=>Math.min(I,T.length-1))}b(!1)}else b(!1);return}if(f.name==="escape"||f.name==="q")e.onClose();else if(f.name==="up"||f.name==="k")l(g=>Math.max(0,g-1));else if(f.name==="down"||f.name==="j")l(g=>Math.min(r.length-1,g+1));else if(f.name==="return"){let g=r[a];g&&e.onResume(g)}else if(f.name==="d")r.length>0&&b(!0);else if(f.name==="f"){let g=r[a];g&&Pt(g)&&c(We())}else f.name==="v"&&r.length>0&&(D(!0),k(0))}),r.length===0)return Le("box",{borderStyle:"single",borderColor:t.primary,backgroundColor:o||t.bg,paddingX:2,paddingY:1,flexDirection:"column",flexGrow:1,children:[Le("box",{flexDirection:"row",flexShrink:0,children:[X("text",{fg:t.primary,attributes:ht.BOLD,flexGrow:1,children:"Sessions"}),X("text",{fg:t.textDim,children:"esc"})]}),X("text",{fg:t.textDim,children:`
54
- No saved conversations.
55
- `})]});if(d){let f=r[a],g=f?f.messages.filter(R=>R.role!=="tool"):[],T=g.slice(y,y+N),I=g.length;return Le("box",{borderStyle:"single",borderColor:t.primary,paddingX:1,paddingY:1,flexDirection:"column",flexGrow:1,children:[Le("box",{flexDirection:"row",flexShrink:0,children:[X("text",{fg:t.primary,attributes:ht.BOLD,flexGrow:1,children:`Viewing: ${f?.title||"Untitled"}`}),X("text",{fg:t.textDim,children:"esc"})]}),X("text",{fg:t.textDim,flexShrink:0,children:`${y+1}\u2013${Math.min(y+N,I)} of ${I} messages`}),X("text",{flexShrink:0,children:""}),X("scrollbox",{flexGrow:1,children:X("box",{flexShrink:0,children:T.map((R,F)=>{let L=R.role==="user"?"\u276F":"\u25C6",v=R.role==="user"?t.success:t.text,M=R.content.length>120?R.content.substring(0,117)+"...":R.content;return X("text",{fg:v,children:` ${L} ${M.replace(/\n/g," ")}`},`view-${y+F}`)})})}),X("text",{flexShrink:0,children:""}),X("text",{fg:t.textMuted,flexShrink:0,children:" \u2191\u2193 Scroll Enter Resume Esc Back"})]})}return Le("box",{borderStyle:"single",borderColor:t.primary,backgroundColor:o||t.bg,paddingX:1,paddingY:1,flexDirection:"column",flexGrow:1,children:[Le("box",{flexDirection:"row",flexShrink:0,children:[X("text",{fg:t.primary,attributes:ht.BOLD,flexGrow:1,children:"Sessions"}),X("text",{fg:t.textDim,children:"esc"})]}),X("text",{fg:t.textDim,flexShrink:0,children:`${r.length} conversation${r.length!==1?"s":""}`}),X("text",{flexShrink:0,children:""}),X("scrollbox",{flexGrow:1,children:X("box",{flexShrink:0,children:r.map((f,g)=>{let T=g===a,I=It(f.updatedAt),R=f.messages.filter(L=>L.role==="user").length,F=f.title.length>40?f.title.substring(0,37)+"...":f.title;return Le("box",{flexDirection:"row",children:[X("text",{fg:T?t.primary:t.textMuted,attributes:T?ht.BOLD:void 0,children:` ${T?"\u276F":" "} ${F}`}),X("text",{fg:t.textDim,children:` ${I} (${R} msgs)`})]},f.id)})})}),h&&Le("box",{flexShrink:0,children:[X("text",{children:""}),X("text",{fg:t.warning,attributes:ht.BOLD,children:` Delete "${r[a]?.title}"? (y/n)`})]}),X("text",{flexShrink:0,children:""}),X("text",{fg:t.textMuted,flexShrink:0,children:" \u2191\u2193 Navigate Enter Resume v View d Delete f Fork Esc Close"})]})}var Xo=K(()=>{"use strict";te();Qt()});import*as $e from"fs";import*as un from"path";import*as Zo from"os";import{execSync as Nt}from"child_process";import{TextAttributes as pe}from"@opentui/core";import{useState as re,useRef as Qo,useEffect as zi}from"react";import{useKeyboard as Xi}from"@opentui/react";import{getProviders as Qi}from"@cdoing/ai";import{getOAuthProvider as Zi,supportsOAuth as es}from"@cdoing/core";import{Fragment as rs,jsx as E,jsxs as Te}from"@opentui/react/jsx-runtime";function ts(e){let n=Zi(e);return!n?.models||n.models.length===0?n?.defaultModel?[{id:n.defaultModel,name:n.defaultModel,hint:"OAuth"}]:[]:n.models.map(o=>({id:o.id,name:o.name,hint:o.hint||"OAuth"}))}function ns(e){return es(e)}function dn(){try{if(process.platform==="darwin")return Nt("pbpaste",{encoding:"utf-8"});try{return Nt("xclip -selection clipboard -o",{encoding:"utf-8"})}catch{return Nt("xsel --clipboard --output",{encoding:"utf-8"})}}catch{return""}}function os(e){try{let n=process.platform==="darwin"?`open "${e}"`:process.platform==="win32"?`start "" "${e}"`:`xdg-open "${e}"`;Nt(n,{stdio:"ignore",timeout:3e3})}catch{}}function nr(e){let{theme:n,customBg:o}=G(),t=n,i=Qo(!1),[r,c]=re(!1),[a,l]=re("provider"),[h,b]=re(0),[d,D]=re(0),[y,k]=re(0),[N,f]=re("apikey"),[g,T]=re("anthropic"),[I,R]=re(""),[F,L]=re(""),[v,M]=re(!1),[U,H]=re(""),[$,B]=re(""),[m,Q]=re(!1),[ue,xe]=re(""),[Oe,Ke]=re(""),[Ne,Pe]=re(""),[nt,He]=re(!1),[Ie,ce]=re(""),ye=Qo(!1),C=Lt[h],S=N==="oauth"?ts(g):er[g]||[];zi(()=>{if(a==="oauth-paste")try{let{generateOAuthUrl:s}=Je("@cdoing/core"),{url:x,codeVerifier:p}=s(g);xe(x),Ke(p),Pe(""),ce(""),os(x)}catch{ce("OAuth not available. Install @cdoing/core with OAuth support.")}},[a,g]),Xi(s=>{if(!i.current){if(s.name==="escape"){i.current=!0,c(!0),e.onClose();return}if(s.ctrl&&s.name==="c"){i.current=!0,c(!0),e.onClose();return}if(a==="provider"){if(s.name==="up"||s.name==="k")b(x=>Math.max(0,x-1));else if(s.name==="down"||s.name==="j")b(x=>Math.min(Lt.length-1,x+1));else if(s.name==="return"){let x=Lt[h];T(x.id),k(0),ns(x.id)?(D(0),l("auth-method")):(f("apikey"),l("model"))}return}if(a==="auth-method"){if(s.name==="up"||s.name==="k")D(x=>Math.max(0,x-1));else if(s.name==="down"||s.name==="j")D(x=>Math.min(ln.length-1,x+1));else if(s.name==="return"){let x=ln[d].id;f(x),k(0),l("model")}return}if(a==="model"){if(m){if(s.name==="return"){let p=$.trim();if(!p)return;R(p),g==="ollama"?O(g,p,void 0):N==="oauth"?(ye.current=!1,l("oauth-paste")):(l("apikey"),L(""),H(""))}else if((s.ctrl||s.meta)&&s.name==="v"){let p=dn().trim();p&&B(P=>P+p)}else s.name==="backspace"?B(p=>p.slice(0,-1)):s.ctrl&&s.name==="u"?B(""):s.sequence&&!s.ctrl&&!s.meta&&B(p=>p+s.sequence);return}let x=S.length+1;if(s.name==="up"||s.name==="k")k(p=>Math.max(0,p-1));else if(s.name==="down"||s.name==="j")k(p=>Math.min(x-1,p+1));else if(s.name==="return"){if(y===S.length){Q(!0),B("");return}let p=S[y];R(p.id),g==="ollama"?O(g,p.id,void 0):N==="oauth"?(ye.current=!1,l("oauth-paste")):(l("apikey"),L(""),H(""))}return}if(a==="apikey"){if(s.name==="return"){if(!F.trim()){H("API key cannot be empty");return}O(g,I,F.trim())}else if((s.ctrl||s.meta)&&s.name==="v"){let x=dn().trim();x&&(L(p=>p+x),H(""))}else s.ctrl&&s.name==="s"?M(x=>!x):s.name==="backspace"?(L(x=>x.slice(0,-1)),H("")):s.ctrl&&s.name==="u"?(L(""),H("")):s.sequence&&!s.ctrl&&!s.meta&&(L(x=>x+s.sequence),H(""));return}if(a==="oauth-paste"){if(s.name==="return"){let x=Ne.trim();if(!x||ye.current)return;ye.current=!0,l("oauth-exchanging");try{let{exchangeOAuthCode:p}=Je("@cdoing/core");p(x,Oe,g).then(P=>{O(g,I,void 0),e.onComplete({provider:g,model:I,oauthToken:P.access_token})}).catch(P=>{ye.current=!1,ce(P.message),l("oauth-paste")})}catch{ye.current=!1,ce("OAuth exchange failed"),l("oauth-paste")}return}if((s.ctrl||s.meta)&&s.name==="v"){let x=dn().trim();x&&(Pe(p=>p+x),ce(""))}else s.ctrl&&s.name==="s"?He(x=>!x):s.name==="backspace"?(Pe(x=>x.slice(0,-1)),ce("")):s.ctrl&&s.name==="u"?(Pe(""),ce("")):s.sequence&&!s.ctrl&&!s.meta&&(Pe(x=>x+s.sequence),ce(""));return}}});let O=(s,x,p)=>{let P=un.join(Zo.homedir(),".cdoing"),Y=un.join(P,"config.json"),J={};try{$e.existsSync(Y)&&(J=JSON.parse($e.readFileSync(Y,"utf-8")))}catch{}J.provider=s,J.model=x,p&&(J.apiKeys||(J.apiKeys={}),J.apiKeys[s]=p),$e.existsSync(P)||$e.mkdirSync(P,{recursive:!0}),$e.writeFileSync(Y,JSON.stringify(J,null,2),"utf-8"),e.onComplete({provider:s,model:x,apiKey:p})},W=g==="anthropic",w=W?4:g==="ollama"?2:3,u=s=>{switch(s){case"provider":return`1/${w}`;case"auth-method":return"2/4";case"model":return W?"3/4":g==="ollama"?"2/2":"2/3";case"apikey":return W?"4/4":"3/3";case"oauth-paste":return"4/4";case"oauth-exchanging":return"4/4";default:return""}};return r?E("box",{children:E("text",{children:""})}):Te("box",{borderStyle:"single",borderColor:t.primary,backgroundColor:o||t.bg,paddingX:2,paddingY:1,flexDirection:"column",flexGrow:1,children:[E("text",{fg:t.primary,attributes:pe.BOLD,children:"Setup Wizard"}),E("text",{children:""}),a==="provider"&&Te("box",{flexDirection:"column",children:[E("text",{fg:t.text,attributes:pe.BOLD,children:`Step ${u("provider")}: Select Provider`}),E("text",{children:""}),Lt.map((s,x)=>E("text",{fg:h===x?t.primary:t.textMuted,attributes:h===x?pe.BOLD:void 0,children:` ${h===x?">":" "} ${s.name} ${h===x?s.hint:""}`},s.id)),E("text",{children:""}),E("text",{fg:t.textMuted,children:" Up/Down Navigate Enter Select Esc Cancel"})]}),a==="auth-method"&&Te("box",{flexDirection:"column",children:[E("text",{fg:t.text,attributes:pe.BOLD,children:`Step ${u("auth-method")}: How do you want to authenticate?`}),E("text",{children:""}),ln.map((s,x)=>E("text",{fg:d===x?t.primary:t.textMuted,attributes:d===x?pe.BOLD:void 0,children:` ${d===x?">":" "} ${s.name} ${d===x?s.hint:""}`},s.id)),E("text",{children:""}),E("text",{fg:t.textMuted,children:" Up/Down Navigate Enter Select Esc Back"})]}),a==="model"&&!m&&Te("box",{flexDirection:"column",children:[E("text",{fg:t.text,attributes:pe.BOLD,children:N==="oauth"?`Step ${u("model")}: Select Model (OAuth \u2014 ${C.name})`:`Step ${u("model")}: Select Model (${C.name})`}),E("text",{children:""}),S.map((s,x)=>E("text",{fg:y===x?t.primary:t.textMuted,attributes:y===x?pe.BOLD:void 0,children:` ${y===x?">":" "} ${s.name}${s.hint?` ${s.hint}`:""}`},s.id)),E("text",{fg:y===S.length?t.primary:t.textMuted,attributes:y===S.length?pe.BOLD:void 0,children:` ${y===S.length?">":" "} Custom model... type any model name`}),E("text",{children:""}),E("text",{fg:t.textMuted,children:" Up/Down Navigate Enter Select Esc Back"})]}),a==="model"&&m&&Te("box",{flexDirection:"column",children:[E("text",{fg:t.text,attributes:pe.BOLD,children:`Step ${u("model")}: Custom Model (${C.name})`}),E("text",{children:""}),E("text",{fg:t.text,children:` > ${$}|`}),E("text",{children:""}),E("text",{fg:t.textMuted,children:" Type model ID then Enter Esc Back"})]}),a==="apikey"&&Te("box",{flexDirection:"column",children:[E("text",{fg:t.text,attributes:pe.BOLD,children:`Step ${u("apikey")}: Enter API Key`}),E("text",{children:""}),E("text",{fg:t.textDim,children:` Provider: ${g} Model: ${I}`}),mn[g]&&E("text",{fg:t.textDim,children:` Get a key: ${mn[g]}`}),E("text",{fg:t.textDim,children:` Environment variable: ${tr[g]||"N/A"}`}),E("text",{children:""}),E("text",{fg:t.text,children:` > ${v?F:F.replace(/./g,"*")}|`}),U&&E("text",{fg:t.error,children:`
56
- ${U}`}),E("text",{children:""}),E("text",{fg:t.textMuted,children:" Enter Save Ctrl+V Paste Ctrl+S Toggle visibility Ctrl+U Clear Esc Back"})]}),a==="oauth-paste"&&Te("box",{flexDirection:"column",children:[E("text",{fg:t.text,attributes:pe.BOLD,children:`Step ${u("oauth-paste")}: OAuth Login`}),E("text",{children:""}),E("text",{fg:t.text,children:" 1. Browser opening to Claude login..."}),ue?E("text",{fg:t.textDim,children:` If it didn't open: ${ue.substring(0,70)}...`}):null,E("text",{fg:t.text,children:" 2. Approve -> you'll land on a page with a code in the URL"}),E("text",{fg:t.text,children:" 3. Copy the code= value from the URL and paste below"}),Ie?Te(rs,{children:[E("text",{children:""}),E("text",{fg:t.error,children:` Error: ${Ie}`})]}):null,E("text",{children:""}),E("text",{fg:t.text,children:` Code: ${nt?Ne:Ne.replace(/./g,"*")}|`}),E("text",{children:""}),E("text",{fg:t.textMuted,children:" Ctrl+V Paste Enter Submit Ctrl+S Toggle visible Esc Cancel"})]}),a==="oauth-exchanging"&&Te("box",{flexDirection:"column",children:[E("text",{fg:t.text,attributes:pe.BOLD,children:`Step ${u("oauth-exchanging")}: OAuth Login`}),E("text",{children:""}),E("text",{fg:t.warning,children:" Exchanging code for tokens..."})]})]})}var fn,Lt,ln,er,tr,mn,or=K(()=>{"use strict";te();fn=Qi(),Lt=fn.map(e=>({id:e.id,name:e.label,hint:e.hint})),ln=[{id:"apikey",name:"API Key",hint:"all models available - console.anthropic.com"},{id:"oauth",name:"OAuth",hint:"Claude Pro/Max - opens browser"}],er={};for(let e of fn)er[e.id]=e.models.map(n=>({id:n.id,name:n.label,hint:n.hint}));tr={},mn={};for(let e of fn)e.envVar&&(tr[e.id]=e.envVar),e.keyUrl&&(mn[e.id]=e.keyUrl)});import{TextAttributes as jt}from"@opentui/core";import{useKeyboard as is,useTerminalDimensions as ss}from"@opentui/react";import{jsx as V,jsxs as De}from"@opentui/react/jsx-runtime";function rr(e){let{theme:n,customBg:o}=G(),t=n,i=kt(),r=ss(),c=Math.min(60,(r.width||80)-4),a=Math.max(10,(r.height||24)-6),l=i.registry.getAll?i.registry.getAll():[],h=Array.isArray(l)?l.map(b=>b.definition?.name||b.name||"unknown"):[];return is(b=>{(b.name==="escape"||b.name==="q")&&e.onClose()}),De("box",{borderStyle:"double",borderColor:t.primary,backgroundColor:o||t.bg,paddingX:1,paddingY:1,flexDirection:"column",position:"absolute",top:Math.max(1,Math.floor((r.height||24)*.1)),left:Math.max(1,Math.floor(((r.width||80)-c)/2)),width:c,height:a,children:[De("box",{flexDirection:"row",flexShrink:0,children:[V("text",{fg:t.primary,attributes:jt.BOLD,flexGrow:1,children:" System Status"}),V("text",{fg:t.textDim,children:"esc"})]}),V("text",{flexShrink:0,children:""}),V("scrollbox",{flexGrow:1,children:De("box",{flexShrink:0,children:[V("text",{fg:t.secondary,attributes:jt.BOLD,children:" Provider"}),De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" Provider "}),V("text",{fg:t.text,children:i.provider})]}),De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" Model "}),V("text",{fg:t.text,children:i.model})]}),De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" Directory "}),V("text",{fg:t.text,children:i.workingDir})]}),V("text",{children:""}),V("text",{fg:t.secondary,attributes:jt.BOLD,children:" System"}),De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" Node "}),V("text",{fg:t.text,children:process.version})]}),De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" Platform "}),V("text",{fg:t.text,children:`${process.platform} ${process.arch}`})]}),De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" Terminal "}),V("text",{fg:t.text,children:process.env.TERM_PROGRAM||process.env.TERM||"unknown"})]}),De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" Shell "}),V("text",{fg:t.text,children:process.env.SHELL||"unknown"})]}),V("text",{children:""}),V("text",{fg:t.secondary,attributes:jt.BOLD,children:` Tools (${h.length})`}),h.map(b=>De("box",{flexDirection:"row",children:[V("text",{fg:t.textMuted,children:" \u2022 "}),V("text",{fg:t.text,children:b})]},b))]})})]})}var ir=K(()=>{"use strict";te();Ct()});var mr={};pr(mr,{startTUI:()=>Ss});import*as tt from"fs";import*as pn from"path";import*as yn from"os";import{createRoot as as,useKeyboard as sr,useTerminalDimensions as ar}from"@opentui/react";import{createCliRenderer as cs,TextAttributes as xn,RGBA as ls}from"@opentui/core";import{useState as Ae,useRef as pt,useCallback as yt}from"react";import{ToolRegistry as ds,PermissionManager as us,PermissionMode as gn,ProcessManager as ms,TodoStore as fs,MemoryStore as gs,registerAllTools as xs,resolveOAuthToken as cr,supportsOAuth as lr}from"@cdoing/core";import{AgentRunner as hn,getDefaultModel as hs,getApiKeyEnvVar as dr}from"@cdoing/ai";import{jsx as j,jsxs as Ft}from"@opentui/react/jsx-runtime";function bs(e){let n=ar(),{theme:o,themeId:t,customBg:i,setMode:r,setThemeId:c}=G(),a=o,[l,h]=Ae(e.options.prompt?"session":"home"),[b,d]=Ae("none"),[D,y]=Ae("Ready"),[k,N]=Ae(e.options.workingDir),[f,g]=Ae(),[T,I]=Ae(0),[R,F]=Ae(),L=se(C=>C.provider),v=se(C=>C.model),M=se(C=>C.sidebarMode),U=se(C=>C.setProvider),H=se(C=>C.setModel),$=se(C=>C.setSidebarMode),B=n.width>120,m=M==="show"||M==="auto"&&B,Q=yt(()=>{d("none")},[]),ue=pt(e.agent),xe=pt(e.registry),Oe=pt(e.permissionManager),Ke=pt(null),Ne=pt(null),[Pe,nt]=Ae(null),He=yt((C,S)=>new Promise(O=>{Ne.current=O,nt({toolName:C,message:S})}),[]);Oe.current.setPromptFn(async(C,S)=>{let O=await He(C,S);return O==="always"?"allow":O});let Ie=yt((C,S,O,W)=>{let w=O,u=W;if(!w&&!u&&O!==""){lr(C)&&cr(C).then(P=>{if(P){let Y={provider:C,model:S,oauthToken:P,baseURL:e.options.baseUrl||void 0,temperature:0,maxTokens:8096},J=new hn(Y,xe.current,Oe.current);ue.current=J,U(C),H(S)}}).catch(()=>{});let p=dr(C);if(process.env[p])w=process.env[p];else try{let P=pn.join(yn.homedir(),".cdoing","config.json");tt.existsSync(P)&&(w=JSON.parse(tt.readFileSync(P,"utf-8")).apiKeys?.[C])}catch{}}let s={provider:C,model:S,apiKey:w||void 0,oauthToken:u||void 0,baseURL:e.options.baseUrl||void 0,temperature:0,maxTokens:8096},x=new hn(s,xe.current,Oe.current);ue.current=x,U(C),H(S)},[e.options.baseUrl]),ce=yt(C=>{N(C)},[]);sr(C=>{if(b!=="none"){if(C.ctrl&&C.name==="c"){let S=globalThis.__cdoingCleanup;S&&S(),process.exit(0)}C.name==="escape"&&(d("none"),h("home"));return}if(C.ctrl&&C.name==="c"){let S=globalThis.__cdoingCleanup;S?S():process.exit(0)}C.ctrl&&C.name==="n"&&(h("session"),y("Ready")),C.ctrl&&C.name==="p"&&d(S=>S==="command"?"none":"command"),C.ctrl&&C.name==="s"&&d(S=>S==="sessions"?"none":"sessions"),C.ctrl&&C.name==="b"&&$(M==="hide"?"show":M==="show"||m?"hide":"show"),C.ctrl&&C.name==="t"&&d(S=>S==="theme"?"none":"theme"),C.ctrl&&C.name==="o"&&d(S=>S==="model"?"none":"model"),C.name==="f1"&&d(S=>S==="help"?"none":"help"),C.name==="escape"&&d("none")},{});let ye=yt(C=>{h("session"),d("none"),y("Ready")},[]);return Ft("box",{width:n.width,height:n.height,flexDirection:"column",backgroundColor:i?ls.fromHex(i):a.bg,children:[Ft("box",{height:1,flexDirection:"row",paddingX:1,flexShrink:0,backgroundColor:a.bgSubtle,children:[j("text",{fg:a.primary,attributes:xn.BOLD,children:"cdoing"}),j("text",{fg:a.border,children:" \u2502 "}),j("text",{fg:a.textMuted,children:v}),j("text",{fg:a.border,children:" \u2502 "}),j("text",{fg:D==="Error"?a.error:D==="Processing..."?a.warning:a.success,children:D})]}),l==="session"&&j(To,{title:"Session",provider:L,model:v,tokens:f,contextPercent:T,status:D}),j("box",{height:1,flexShrink:0,children:j("text",{fg:a.border,children:"\u2500".repeat(Math.max(n.width,40))})}),Ft("box",{flexDirection:"row",flexGrow:1,children:[j(Bn,{value:{agent:ue.current,registry:xe.current,permissionManager:Oe.current,workingDir:k,provider:L,model:v,requestPermission:He,rebuildAgent:Ie,setWorkingDir:ce},children:j("box",{flexGrow:1,flexDirection:"column",children:b==="sessions"?j(zo,{onResume:ye,onClose:()=>d("none")}):b==="setup"?j(nr,{onComplete:C=>{Ie(C.provider,C.model,C.apiKey,C.oauthToken),d("none")},onClose:()=>d("none")}):l==="home"?j(Xn,{provider:L,model:v,workingDir:k,themeId:t,onSubmit:(C,S)=>{Ke.current={text:C,images:S},h("session")}}):j(Do,{onStatus:y,onTokens:(C,S)=>g({input:C,output:S}),onActiveTool:F,onContextPercent:I,onOpenDialog:C=>d(C),initialMessage:Ke.current,dialogOpen:b!=="none"})})}),m&&j("box",{width:1,flexShrink:0,children:j("text",{fg:a.border,children:`\u2502
57
- `.repeat(Math.max(n.height-4,1))})}),m&&j(Po,{provider:L,model:v,workingDir:k,tokens:f,contextPercent:T,activeTool:R,status:D,themeId:t})]}),j("box",{height:1,flexShrink:0,children:j("text",{fg:a.border,children:"\u2500".repeat(Math.max(n.width,40))})}),l==="session"?j(Ao,{workingDir:k,isProcessing:D==="Processing..."}):j(Co,{provider:L,model:v,mode:e.options.mode,workingDir:k,tokens:f,contextPercent:T,activeTool:R,isProcessing:D==="Processing..."}),b==="model"&&j(Lo,{provider:L,currentModel:v,onSelect:C=>{Ie(L,C),d("none")},onClose:()=>d("none")}),b==="command"&&j(Go,{onSelect:C=>{switch(d("none"),C){case"session:new":h("session"),y("Ready");break;case"session:browse":d("sessions");break;case"session:clear":h("session"),y("Ready");break;case"model:switch":case"model:provider":d("model");break;case"theme:dark":r("dark");break;case"theme:light":r("light");break;case"theme:picker":d("theme");break;case"display:sidebar":$(M==="hide"?"show":M==="show"||m?"hide":"show");break;case"tool:shell":case"tool:search":case"tool:tree":h("session");break;case"system:status":d("status");break;case"system:help":d("help");break;case"system:doctor":y("Doctor");break;case"system:setup":d("setup");break;case"system:exit":{let S=globalThis.__cdoingCleanup;S?S():process.exit(0);break}}},onClose:()=>d("none")}),b==="help"&&j(qo,{onClose:()=>d("none")}),b==="theme"&&j(Vo,{onClose:()=>d("none")}),b==="status"&&j(rr,{onClose:()=>d("none")})]})}function ps(e){let[n,o]=Ae(ur);return bn=o,n?j(ys,{error:n,onReset:()=>o(null)}):e.children}function ys(e){let n=ar(),o=Math.max(n.width,40),t={bg:"#0a0a0a",text:"#eeeeee",muted:"#808080",primary:"#fab283",error:"#ff6b6b"},i=`https://github.com/AhmadMuj/cdoing-agent/issues/new?title=${encodeURIComponent(`tui: fatal: ${e.error.message}`)}&body=${encodeURIComponent("```\n"+(e.error.stack||e.error.message).substring(0,4e3)+"\n```")}`;sr(c=>{if(c.ctrl&&c.name==="c"){let a=globalThis.__cdoingCleanup;a?a():process.exit(1)}if(c.name==="r"&&e.onReset(),c.name==="q"||c.name==="escape"){let a=globalThis.__cdoingCleanup;a?a():process.exit(0)}});let r=(e.error.stack||"").split(`
58
- `).slice(0,Math.max(5,n.height-12));return Ft("box",{width:n.width,height:n.height,flexDirection:"column",backgroundColor:t.bg,paddingX:2,paddingY:1,children:[j("text",{fg:t.error,attributes:xn.BOLD,children:" A fatal error occurred!"}),j("text",{children:""}),j("text",{fg:t.text,attributes:xn.BOLD,children:` ${e.error.message}`}),j("text",{children:""}),j("text",{fg:t.muted,children:" Stack trace:"}),r.map((c,a)=>j("text",{fg:t.muted,children:` ${c}`},a)),j("text",{children:""}),j("text",{fg:t.primary,children:" Report this issue:"}),j("text",{fg:t.muted,children:` ${i.length>o-4?i.substring(0,o-7)+"...":i}`}),j("text",{children:""}),j("box",{height:1,flexShrink:0,children:j("text",{fg:t.muted,children:"\u2500".repeat(o)})}),j("text",{fg:t.text,children:" r Reset TUI \u2022 q/Esc Exit \u2022 Ctrl+C Force quit"})]})}async function Ss(e){let n=new ds,o=e.mode==="auto"?gn.BYPASS:e.mode==="auto-edit"?gn.ACCEPT_EDITS:gn.DEFAULT,t=new us(o,e.workingDir);t.setPromptFn(async(m,Q)=>"allow");let i=new ms,r=new fs,c=new gs(e.workingDir);await xs(n,{workingDir:e.workingDir,permissionManager:t,processManager:i,todoStore:r,memoryStore:c,planExitCallback:m=>{console.log(`
59
- \u{1F4CB} Plan ready: `+m),console.log(` Use /plan approve, /plan reject, or /plan show
60
- `)}});let a=e.apiKey,l,h=e.provider,b=e.model,d=e.baseUrl;if(!a){let m=pn.join(yn.homedir(),".cdoing","config.json"),Q={};try{tt.existsSync(m)&&(Q=JSON.parse(tt.readFileSync(m,"utf-8")))}catch{}h==="anthropic"&&Q.provider&&(h=Q.provider),!b&&Q.model&&(b=Q.model),!d&&Q.baseUrl&&(d=Q.baseUrl);let ue=dr(h);if(process.env[ue]?a=process.env[ue]:Q.apiKeys?.[h]&&(a=Q.apiKeys[h]),!a&&lr(h))try{let xe=await cr(h);xe&&(l=xe)}catch{}}let D=se.getState();(h&&h!=="anthropic"||!D.provider||D.provider==="anthropic")&&D.setProvider(h),b?D.setModel(b):D.model||D.setModel(hs(D.provider)||"default");let y=se.getState().provider,k=se.getState().model,N={provider:y,model:k||void 0,apiKey:a||void 0,oauthToken:l||void 0,baseURL:d||void 0,temperature:0,maxTokens:8096},f=new hn(N,n,t),g;e.theme==="auto"&&(g=await On());let T=e.theme==="light"?"light":e.theme==="auto"&&g||"dark",I=se.getState().themeId,R=se.getState().mode;e.theme!=="light"&&e.theme!=="dark"?R&&D.setMode(R):D.setMode(e.theme==="light"?"light":"dark");let F=Re(I||"default",T);Ve(F.bg);let L=Math.max(process.stdout.columns||80,80),v=Math.max(process.stdout.rows||24,24);process.stdout.write(`\x1B[8;${v};${L}t`),console.clear(),At("cdoing");let M=await cs({useMouse:!0,exitOnCtrlC:!1}),U=as(M),H=m=>{let Q=m instanceof Error?m:new Error(String(m));process.stderr.write(`
61
- [cdoing] Fatal error: ${Q.message}
62
- ${Q.stack||""}
63
- `),ur=Q,bn&&bn(Q)};process.on("uncaughtException",H),process.on("unhandledRejection",H),U.render(j(ps,{children:j(In,{mode:e.theme,themeId:I,detectedMode:g,syncTerminalBg:!0,children:j(Fn,{children:j(bs,{options:{...e,provider:y,model:k||void 0},agent:f,registry:n,permissionManager:t})})})}));let $=!1,B=()=>{if(!$){$=!0;try{U.unmount()}catch{}try{M.destroy()}catch{}uo(),Dt(),process.exit(0)}};process.on("SIGINT",B),process.on("SIGTERM",B),globalThis.__cdoingCleanup=B,await new Promise(()=>{})}var ur,bn,fr=K(()=>{"use strict";te();Ct();Ht();qt();Qn();ko();Mo();$o();Oo();Io();No();Uo();Ko();Yo();Xo();or();ir();zt();ur=null,bn=null});import{Command as vs}from"commander";import{getDefaultModel as ws}from"@cdoing/ai";var gr=new vs;gr.name("cdoing-tui").description("OpenTUI-based terminal interface for cdoing agent").version("0.1.0").option("-m, --model <model>","Model name").option("-p, --provider <provider>","AI provider","anthropic").option("--api-key <key>","API key").option("--base-url <url>","Base URL for custom providers").option("-d, --dir <directory>","Working directory",process.cwd()).option("--mode <mode>","Permission mode: ask, auto-edit, auto","ask").option("-r, --resume <id>","Resume conversation by ID").option("-c, --continue","Continue most recent conversation").option("--theme <theme>","Theme: dark, light, auto","dark").argument("[prompt]","Initial prompt").action(async(e,n)=>{let{startTUI:o}=await Promise.resolve().then(()=>(fr(),mr));await o({prompt:e,provider:n.provider,model:n.model||ws(n.provider),apiKey:n.apiKey,baseUrl:n.baseUrl,workingDir:n.dir,mode:n.mode,resume:n.resume,continue:n.continue,theme:n.theme})});gr.parse();
64
- //# sourceMappingURL=index.js.map