@arhan-w/ibex 0.0.0-stage → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -2
  3. package/npm-package/LICENSE +21 -0
  4. package/npm-package/README.md +176 -0
  5. package/npm-package/bin/goat.js +3 -0
  6. package/npm-package/bin/ibex.js +77 -0
  7. package/npm-package/package.json +58 -0
  8. package/npm-package/scripts/install-binary.js +168 -0
  9. package/package.json +69 -6
  10. package/src/agent.ts +695 -0
  11. package/src/agents/loader.ts +110 -0
  12. package/src/ambient.d.ts +2 -0
  13. package/src/code/extract.ts +292 -0
  14. package/src/code/find.ts +244 -0
  15. package/src/code/grammars.ts +88 -0
  16. package/src/code/indexer.ts +242 -0
  17. package/src/code/semantic.ts +253 -0
  18. package/src/code/slash.ts +88 -0
  19. package/src/code/tool.ts +40 -0
  20. package/src/collab/client.ts +141 -0
  21. package/src/collab/handlers.ts +141 -0
  22. package/src/collab/invite.ts +39 -0
  23. package/src/collab/relay.ts +106 -0
  24. package/src/collab/sync.ts +131 -0
  25. package/src/commands.tsx +943 -0
  26. package/src/computer.ts +629 -0
  27. package/src/config.ts +318 -0
  28. package/src/constants.ts +18 -0
  29. package/src/context.ts +73 -0
  30. package/src/data/providers.json +2342 -0
  31. package/src/diff.ts +50 -0
  32. package/src/doctor.ts +443 -0
  33. package/src/errors.ts +139 -0
  34. package/src/gflash.ts +170 -0
  35. package/src/hooks.ts +133 -0
  36. package/src/ide/assets.gen.ts +3 -0
  37. package/src/ide/index.html +844 -0
  38. package/src/ide/server.ts +506 -0
  39. package/src/ide/vendor/marked.umd.js +80 -0
  40. package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
  41. package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
  42. package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
  43. package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
  44. package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
  45. package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
  46. package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
  47. package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
  48. package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
  49. package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
  50. package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
  51. package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
  52. package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
  53. package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
  54. package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
  55. package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
  56. package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
  57. package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
  58. package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
  59. package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
  60. package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
  61. package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
  62. package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
  63. package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
  64. package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
  65. package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
  66. package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
  67. package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
  68. package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
  69. package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
  70. package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
  71. package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
  72. package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
  73. package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
  74. package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
  75. package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
  76. package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
  77. package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
  78. package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
  79. package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
  80. package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
  81. package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
  82. package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
  83. package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
  84. package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
  85. package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
  86. package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
  87. package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
  88. package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
  89. package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
  90. package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
  91. package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
  92. package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
  93. package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
  94. package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
  95. package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
  96. package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
  97. package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
  98. package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
  99. package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
  100. package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
  101. package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
  102. package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
  103. package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
  104. package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
  105. package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
  106. package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
  107. package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
  108. package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
  109. package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
  110. package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
  111. package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
  112. package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
  113. package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
  114. package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
  115. package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
  116. package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
  117. package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
  118. package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
  119. package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
  120. package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
  121. package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
  122. package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
  123. package/src/ide/vendor/vs/editor/editor.main.css +8 -0
  124. package/src/ide/vendor/vs/editor/editor.main.js +798 -0
  125. package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
  126. package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
  127. package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
  128. package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
  129. package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
  130. package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
  131. package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
  132. package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
  133. package/src/ide/vendor/vs/loader.js +11 -0
  134. package/src/index-shared.ts +117 -0
  135. package/src/index.ts +586 -0
  136. package/src/llm.ts +721 -0
  137. package/src/logger.ts +39 -0
  138. package/src/mcp/client.ts +121 -0
  139. package/src/mcp/types.ts +27 -0
  140. package/src/oauth.ts +205 -0
  141. package/src/onboarding.ts +140 -0
  142. package/src/palette.tsx +199 -0
  143. package/src/permissions.ts +123 -0
  144. package/src/plugins/loader.ts +120 -0
  145. package/src/plugins/marketplace.ts +252 -0
  146. package/src/plugins/sandbox.ts +303 -0
  147. package/src/plugins/tar.ts +241 -0
  148. package/src/pricing.ts +78 -0
  149. package/src/protocol/client.ts +102 -0
  150. package/src/protocol/rpc.ts +43 -0
  151. package/src/protocol/serve.ts +136 -0
  152. package/src/providers.ts +402 -0
  153. package/src/rate-limiter.ts +101 -0
  154. package/src/refs.ts +97 -0
  155. package/src/runtime.ts +144 -0
  156. package/src/session.ts +401 -0
  157. package/src/skills/loader.ts +136 -0
  158. package/src/statusline.ts +70 -0
  159. package/src/system-prompt.ts +28 -0
  160. package/src/tools.ts +1280 -0
  161. package/src/tui.tsx +1355 -0
  162. package/src/update.ts +236 -0
  163. package/src/vendor/flashServer.ts +2 -0
  164. package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
  165. package/src/virtual-list.tsx +125 -0
  166. package/src/window.ts +31 -0
  167. package/tsconfig.json +16 -0
package/src/tui.tsx ADDED
@@ -0,0 +1,1355 @@
1
+ /**
2
+ * GoatCode — Claude Code-style Ink/React REPL.
3
+ *
4
+ * ❯ prompt box with rounded border + mode · model · path footer
5
+ * thinking spinner (verb + elapsed + tokens + "esc to interrupt")
6
+ * ● Tool(args) / ⎿ result lines
7
+ * numbered permission dialog (Yes / Yes-all-session / No)
8
+ * slash-command completion with descriptions
9
+ * Shift+Tab / Ctrl+O mode cycle · Ctrl+C interrupt · ↑↓ history
10
+ */
11
+ import { Box, Static, Text, render, useApp, useInput } from "ink";
12
+ import TextInput from "ink-text-input";
13
+ import { CommandPalette, type Command, buildCommandList } from "./palette.tsx";
14
+ import { appendFileSync, existsSync, readFileSync, readdirSync, statSync, unlinkSync } from "node:fs";
15
+ import { execSync } from "node:child_process";
16
+ import { basename, join, relative, resolve as resolvePath } from "node:path";
17
+ import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
18
+ import { Agent, type AgentEvent } from "./agent.ts";
19
+ import { COMMAND_DESC, SLASH_COMMANDS, runSlash, type SlashIO } from "./commands.tsx";
20
+ import { appDir, loadConfig, saveConfig, splitModel, resolveRepos, type GoatConfig } from "./config.ts";
21
+ import { registerRemoteAgents } from "./index-shared.ts";
22
+ import { shouldShowOnboarding, runFirstRunWizard } from "./onboarding.ts";
23
+ import { VERSION } from "./constants.ts";
24
+ import { contextPct } from "./window.ts";
25
+ import { atCompletions, listProjectFiles } from "./refs.ts";
26
+ import { makeFindTool, FIND_TOOL_SPEC } from "./code/tool.ts";
27
+ import { autoIndexOnce } from "./code/slash.ts";
28
+ import type { Index } from "./code/indexer.ts";
29
+ import { workspaceHash, readIndex } from "./code/indexer.ts";
30
+ import { VirtualList, ScrollableList } from "./virtual-list.tsx";
31
+
32
+ /** Replace the trailing token (slash line or @token) with the completion. */
33
+ function acceptCompletion(input: string, kind: "slash" | "at", value: string): string {
34
+ if (kind === "slash") {
35
+ // replace only the command token; keep any already-typed arguments
36
+ const rest = input.trim().split(/\s+/).slice(1).join(" ");
37
+ return value + (rest ? " " + rest + " " : " ");
38
+ }
39
+ return input.replace(/@[^\s]*$/, "@" + value + " ");
40
+ }
41
+ import { unifiedDiff, diffStats } from "./diff.ts";
42
+ import { ProviderRegistry } from "./providers.ts";
43
+ import { resolveSmall, resolveFallbacks, ResolveError, resolve } from "./runtime.ts";
44
+ import { Session } from "./session.ts";
45
+ import { loadSkills, loadSkillBody, type SkillDef } from "./skills/loader.ts";
46
+ import { loadPlugins, pluginSkills } from "./plugins/loader.ts";
47
+ import { buildExtraSystem, loadOutputStyle } from "./context.ts";
48
+ import { loadMcpFromConfig, type McpClient } from "./mcp/client.ts";
49
+ import { ToolKit, IMAGE_TYPES, MAX_IMAGE_BYTES, sniffImage } from "./tools.ts";
50
+ import { clipboardImage } from "./computer.ts";
51
+ import { runStatusLine, statusInput } from "./statusline.ts";
52
+ import { cachedUpdateHint, refreshUpdateHint } from "./update.ts";
53
+ import { log } from "./logger.ts";
54
+ import { contentChars, estimateTokens } from "./llm.ts";
55
+ import type { ContentPart } from "./llm.ts";
56
+ import type { Todo } from "./tools.ts";
57
+ import type { CollabSession } from "./collab/client.ts";
58
+ import { costUsd } from "./pricing.ts";
59
+ import { loadCustomAgents, agentDirs } from "./agents/loader.ts";
60
+
61
+ // ---------- theme (goat noir: deep slate + black-green) ----------
62
+ export const ACCENT = "#a855f7";
63
+ const DIM = "#7c8390"; // slate gray — sits between the two darks
64
+ const GREEN = "#4ade80";
65
+ const RED = "#f87171";
66
+ const BORDER = "#25262D"; // panel slate
67
+ const BG_DEEP = "#000F08"; // black-green — input box / dialogs
68
+ const BG_PANEL = "#25262D"; // deep slate — secondary surfaces
69
+ const YELL = "#facc15";
70
+
71
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
72
+ const VERBS = [
73
+ "Accomplishing", "Actioning", "Architecting", "Baking", "Booping",
74
+ "Calculating", "Cerebrating", "Channelling", "Choreographing", "Coalescing",
75
+ "Computing", "Concocting", "Considering", "Contemplating", "Cooking",
76
+ "Crafting", "Creating", "Crunching", "Deciphering", "Deliberating",
77
+ "Determining", "Divining", "Doing", "Effecting", "Elucidating",
78
+ "Envisioning", "Finagling", "Forging", "Formulating", "Generating",
79
+ "Hatching", "Herding", "Ideating", "Inferring", "Manifesting",
80
+ "Moseying", "Mulling", "Mustering", "Musing", "Noodling", "Percolating",
81
+ "Pondering", "Processing", "Puttering", "Reasoning", "Reticulating",
82
+ "Ruminating", "Schlepping", "Simmering", "Spinning", "Synthesizing",
83
+ "Thinking", "Transmuting", "Vibing", "Working",
84
+ ];
85
+
86
+ function pickVerb(): string {
87
+ return VERBS[Math.floor(Math.random() * VERBS.length)];
88
+ }
89
+ function fmtElapsed(ms: number): string {
90
+ const s = Math.floor(ms / 1000);
91
+ if (s < 60) return `${s}s`;
92
+ return `${Math.floor(s / 60)}m ${s % 60}s`;
93
+ }
94
+ function shortPath(p: string): string {
95
+ const home = process.env.USERPROFILE || process.env.HOME || "";
96
+ return home && p.startsWith(home) ? "~" + p.slice(home.length) : p;
97
+ }
98
+
99
+ /**
100
+ * @file/@dir/@image expansion lives in refs.ts (shared with `goat web`).
101
+ * These wrappers keep the TUI signature (push renders React nodes).
102
+ */
103
+ import { expandFileRefs as _ef, buildUserContent as _bu } from "./refs.ts";
104
+ export const expandFileRefs = _ef;
105
+ export const buildUserContent = _bu;
106
+
107
+ type Mode = "default" | "acceptEdits" | "plan" | "bypass";
108
+ const MODE_LABEL: Record<Mode, string> = {
109
+ default: "ask before edits",
110
+ acceptEdits: "⏵⏵ accept edits on",
111
+ plan: "⏸ plan mode on",
112
+ bypass: "🐐 GOAT MODE — unchained",
113
+ };
114
+ const MODE_ORDER: Mode[] = ["default", "acceptEdits", "plan", "bypass"];
115
+
116
+ function modeColor(m: Mode): string {
117
+ return (m as "default" | "bypass" | "acceptEdits" | "plan") === "default" ? DIM : (m as "default" | "bypass" | "acceptEdits" | "plan") === "bypass" ? "#ff0" : ACCENT;
118
+ }
119
+
120
+ interface PermRequest {
121
+ tool: string;
122
+ args: Record<string, unknown>;
123
+ resolve: (ok: boolean) => void;
124
+ }
125
+
126
+ /** Visible terminal width in cells (CJK double-width counted as 2). */
127
+ function textWidth(s: string): number {
128
+ let w = 0;
129
+ for (const ch of s) w += /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]/.test(ch) ? 2 : 1;
130
+ return w;
131
+ }
132
+ const cols = () => Math.max(40, process.stdout.columns ?? 96);
133
+ /**
134
+ * Rows the streaming region may occupy. The rest of the live frame is fixed:
135
+ * spinner+thinkline (2), tool/plan context (a few), input box (3), status (2),
136
+ * margins (2) — plus a permission dialog (~7) that can appear while a turn
137
+ * runs. Overshooting stdout.rows makes the terminal scroll, which breaks Ink's
138
+ * erase-and-repaint and ghosts the borders. 15 is the honest reservation.
139
+ */
140
+ const liveBudget = () => Math.max(2, (process.stdout.rows ?? 24) - 15);
141
+ /** Keep the trailing lines of `text` that fit in `budget` wrapped rows of `width`. */
142
+ function tailWithin(text: string, budget: number, width: number): string {
143
+ const lines = text.split("\n");
144
+ let rows = 0, start = lines.length;
145
+ for (let i = lines.length - 1; i >= 0; i--) {
146
+ rows += Math.max(1, Math.ceil(textWidth(lines[i]) / (width - 2)));
147
+ if (rows > budget) break;
148
+ start = i;
149
+ }
150
+ return lines.slice(start).join("\n");
151
+ }
152
+
153
+ /** Renders the TUI and RESOLVES ONLY WHEN THE APP EXITS. Callers must await. */
154
+ export async function run(cfg: GoatConfig = loadConfig(), resume?: string): Promise<void> {
155
+ // Claude-style boot: wipe screen + scrollback first so the session owns a
156
+ // clean viewport instead of trailing under shell history.
157
+ process.stdout.write("\x1b[2J\x1b[H\x1b[3J");
158
+ const { waitUntilExit } = render(
159
+ <App initialCfg={cfg} resume={resume} />,
160
+ { stdin: process.stdin, stdout: process.stdout, exitOnCtrlC: false },
161
+ );
162
+ await waitUntilExit();
163
+ }
164
+
165
+ function App({ initialCfg, resume }: { initialCfg: GoatConfig; resume?: string }) {
166
+ const { exit } = useApp();
167
+ const [cfg, setCfg] = useState(initialCfg);
168
+ log("boot", `goat ${cfg.model} cwd=${resume ?? process.cwd()}`);
169
+ const mcpRef = useRef<McpClient | null>(null);
170
+
171
+ // Production: shutdown MCP cleanly and save on exit, SIGTERM, SIGHUP
172
+ useEffect(() => {
173
+ const cleanup = async () => {
174
+ try { await mcpRef.current?.shutdown(); } catch { /* */ }
175
+ try { sessionRef.current.save(); } catch { /* */ }
176
+ };
177
+ const onSig = () => { cleanup().then(() => exit()); };
178
+ process.on("SIGTERM", onSig);
179
+ process.on("SIGHUP", onSig);
180
+ return () => {
181
+ process.off("SIGTERM", onSig);
182
+ process.off("SIGHUP", onSig);
183
+ };
184
+ }, [exit]);
185
+ const registryRef = useRef(new ProviderRegistry(initialCfg.endpoints));
186
+ const [session, setSession] = useState<Session>(() => {
187
+ if (resume) {
188
+ try { return Session.loadById(resume); } catch { /* fall through */ }
189
+ }
190
+ return Session.new(process.cwd(), initialCfg.model);
191
+ });
192
+ const [mcp, setMcp] = useState<McpClient | null>(null);
193
+ const [mcpErrors, setMcpErrors] = useState<string[]>([]);
194
+ mcpRef.current = mcp;
195
+ const [skills, setSkills] = useState<SkillDef[]>([]);
196
+
197
+ const [mode, setMode] = useState<Mode>(initialCfg.autoApprove ? "bypass" : "default");
198
+ const [input, setInput] = useState("");
199
+ const [authBanner, setAuthBanner] = useState<string | null>(null);
200
+ const [history, setHistory] = useState<string[]>([]);
201
+ const [histIdx, setHistIdx] = useState(-1);
202
+ const [lines, setLines] = useState<ReactNode[]>([]);
203
+ const [stream, setStream] = useState("");
204
+ const [thinking, setThinking] = useState(false);
205
+ const [verb, setVerb] = useState("Thinking");
206
+ const [elapsed, setElapsed] = useState(0);
207
+ const [tokens, setTokens] = useState(0);
208
+ const [ctxTok, setCtxTok] = useState(0); // real prompt tokens of the last API call
209
+ const [perm, setPerm] = useState<PermRequest | null>(null);
210
+ const permRef = useRef<PermRequest | null>(null);
211
+ permRef.current = perm;
212
+ const toolQueueOpen = useRef(false);
213
+ /** Tools the user chose "always allow (session)" for — in memory only. */
214
+ const sessionRules = useRef<Set<string>>(new Set());
215
+ const [permSel, setPermSel] = useState(0);
216
+ const [completions, setCompletions] = useState<string[]>([]);
217
+ const [compKind, setCompKind] = useState<"slash" | "at">("slash");
218
+ const [compSel, setCompSel] = useState(0);
219
+ const [compOpen, setCompOpen] = useState(false);
220
+ const [thinkLine, setThinkLine] = useState("");
221
+ const [pasted, setPasted] = useState<string | null>(null); // ctrl+V image path
222
+ const [todos, setTodos] = useState<Todo[]>([]);
223
+ const [statusLines, setStatusLines] = useState<string[]>([]);
224
+ // live streaming tool output: { tool, brief, lines } for the running call
225
+ const [toolLive, setToolLive] = useState<{ tool: string; brief: string; lines: string[] } | null>(null);
226
+ /** Lines of streamed tool output kept visible in the live frame. */
227
+ const TOOL_LIVE_LINES = 6;
228
+ /** ctrl+j toggles the full streamed transcript inline. */
229
+ const [toolVerbose, setToolVerbose] = useState(false);
230
+
231
+ // Command palette state
232
+ const [isPaletteOpen, setIsPaletteOpen] = useState(false);
233
+ const [paletteCommands, setPaletteCommands] = useState<Command[]>([]);
234
+ const [paletteSelected, setPaletteSelected] = useState(0);
235
+
236
+ // Onboarding
237
+ const [shouldShowOnboard, setShouldShowOnboard] = useState(shouldShowOnboarding());
238
+ const [onboardStep, setOnboardStep] = useState(0);
239
+
240
+ const abortRef = useRef<AbortController | null>(null);
241
+ const queuedRef = useRef<string[]>([]);
242
+ const submitRef = useRef<((raw: string) => void) | null>(null);
243
+ const lastCtrlC = useRef(0);
244
+ const lineKey = useRef(0);
245
+ const toolsRef = useRef<ToolKit | null>(null);
246
+ const notifiedBg = useRef<Set<string>>(new Set());
247
+ const sessionRef = useRef(session);
248
+ sessionRef.current = session;
249
+ const cfgRef = useRef(cfg);
250
+ cfgRef.current = cfg;
251
+ const modeRef = useRef(mode);
252
+ modeRef.current = mode;
253
+ // Collab (Pillar B): live relay session + a peer/turn mirror for the footer.
254
+ const [collabPeers, setCollabPeers] = useState<{ id: string; name: string }[]>([]);
255
+ const [collabHolder, setCollabHolder] = useState<string | null>(null);
256
+ const collabRef = useRef<CollabSession | null>(null);
257
+
258
+ /** True when the local actor holds the collab turn token. */
259
+ function canSpeakFor(session: CollabSession): boolean {
260
+ return session.canSpeak(session.actor);
261
+ }
262
+
263
+ const push = useCallback((node: ReactNode) => {
264
+ setLines((prev) => [...prev, <Box key={lineKey.current++}>{node}</Box>]);
265
+ }, []);
266
+
267
+ // boot: welcome + async init of mcp/skills + a live auth probe so a
268
+ // misconfigured install shows a banner instead of a silent dead shell
269
+ useEffect(() => {
270
+ push(<Welcome cfg={cfgRef.current} cwd={sessionRef.current.cwd} />);
271
+ (async () => {
272
+ try {
273
+ const { resolve, AuthRequired, UnknownProvider } = await import("./runtime.ts");
274
+ await resolve(cfgRef.current, registryRef.current);
275
+ } catch (e) {
276
+ const msg = e instanceof Error ? e.message : String(e);
277
+ if (msg.includes("needs credentials")) {
278
+ setAuthBanner(msg);
279
+ } else {
280
+ push(<Text color="#f87171">{msg}</Text>);
281
+ }
282
+ }
283
+ try {
284
+ const m = await loadMcpFromConfig({ mcpServers: cfgRef.current.mcpServers });
285
+ m.onError = (msg) => { setMcpErrors((prev) => [...prev, msg]); log("mcp", msg); };
286
+ setMcp(m);
287
+ if (m.servers.size)
288
+ push(<Text dimColor color={DIM}> ⚡ {m.servers.size} MCP server(s) connected</Text>);
289
+ } catch { /* mcp optional */ }
290
+ const dirs = [
291
+ join(appDir(), "skills"),
292
+ join(process.cwd(), "skills"),
293
+ join(process.cwd(), ".claude", "skills"),
294
+ ];
295
+ const pl = loadPlugins(cfgRef.current.pluginDirs.map((d) => resolvePath(process.cwd(), d)));
296
+ const native = loadSkills(...dirs);
297
+ const fromPlugins = pluginSkills(pl);
298
+ if (pl.length)
299
+ push(<Text dimColor color={DIM}> 🔌 {pl.length} plugin(s) · {fromPlugins.length} command/skill(s)</Text>);
300
+ // native wins on name collision; plugins extend the palette
301
+ const names = new Set(native.map((s) => s.name));
302
+ setSkills([...native, ...fromPlugins.filter((s) => !names.has(s.name))]);
303
+ // update hint: cached check (max 1 API call / 6h), never blocks boot
304
+ const hint = cachedUpdateHint();
305
+ if (hint) push(<Text dimColor color={DIM}> ↑ GoatCode {hint.latest} available — run: goat self-update</Text>);
306
+ else refreshUpdateHint();
307
+ // Build palette commands from all available sources
308
+ const slashCommands = (await import("./commands.tsx")).SLASH_COMMANDS;
309
+ const commandDescs = (await import("./commands.tsx")).COMMAND_DESC;
310
+ const { allSkills } = await import("./index-shared.ts");
311
+ const allSk = allSkills(cfgRef.current);
312
+ const pluginLoader = await import("./plugins/loader.ts");
313
+ const pluginNames = pluginLoader
314
+ .loadPlugins(cfgRef.current.pluginDirs.map((d) => resolvePath(process.cwd(), d)))
315
+ .map((p) => p.manifest.name ?? basename(p.dir));
316
+ const sessions = (await import("./session.ts")).listSessions().map((s) => s.id);
317
+ const pluginDescriptions = pluginNames.map((n) => ({
318
+ name: `/plugin:${n}`,
319
+ description: `Plugin: ${n}`,
320
+ category: "plugin",
321
+ }));
322
+ setPaletteCommands(buildCommandList({
323
+ slashCommands,
324
+ commandDescs: commandDescs,
325
+ skills: allSk,
326
+ plugins: pluginDescriptions,
327
+ sessions,
328
+ }));
329
+ // Run first-run wizard if needed
330
+ if (shouldShowOnboard) {
331
+ setShouldShowOnboard(false);
332
+ const onboardResult = await runFirstRunWizard();
333
+ if (!onboardResult) {
334
+ // User aborted or wizard completed
335
+ }
336
+ }
337
+ // Collab: join a relay room advertised by GOAT_COLLAB_INVITE (Pillar B).
338
+ const inviteCode = process.env.GOAT_COLLAB_INVITE;
339
+ if (inviteCode && !collabRef.current) {
340
+ (async () => {
341
+ try {
342
+ const { CollabClient } = await import("./collab/client.ts");
343
+ const actor = process.env.GOAT_COLLAB_NAME || sessionRef.current.id.slice(0, 8);
344
+ const cs = CollabClient({ invite: inviteCode, name: actor });
345
+ collabRef.current = cs;
346
+ cs.onPeers((peers) => { setCollabPeers(peers); setCollabHolder(cs.holder()); });
347
+ cs.onOp((op) => {
348
+ setCollabHolder(cs.holder()); // turn ops moved the token
349
+ if (op.kind === "msg") {
350
+ const text = String((op.payload as { text?: string }).text ?? "");
351
+ push(<Text color={ACCENT}>◈ {op.actor}: {text}</Text>);
352
+ // surface the peer message to the model on the next turn
353
+ try {
354
+ sessionRef.current.append({ role: "user", content: `[peer ${op.actor}] ${text}` });
355
+ sessionRef.current.save();
356
+ } catch { /* session append is best-effort */ }
357
+ } else if (op.kind === "write") {
358
+ const p = op.payload as { repo?: string; path?: string };
359
+ push(<Text dimColor color={DIM}> peer {op.actor} wrote {p.repo ? p.repo + "/" : ""}{p.path ?? "?"}</Text>);
360
+ }
361
+ });
362
+ cs.onClosed((reason) => {
363
+ push(<Text color={RED}> collab: connection closed ({reason})</Text>);
364
+ collabRef.current = null; setCollabPeers([]); setCollabHolder(null);
365
+ });
366
+ await cs.ready;
367
+ push(<Text dimColor color={DIM}> ⚡ collab active — {cs.peers().length} peer(s) · turn: {cs.holder() === actor ? "you" : (cs.holder() ?? "waiting")}</Text>);
368
+ } catch (e: any) {
369
+ push(<Text color={RED}> collab join failed: {e?.message ?? e}</Text>);
370
+ }
371
+ })();
372
+ }
373
+ })();
374
+ }, [push]);
375
+
376
+ // spinner clock
377
+ useEffect(() => {
378
+ if (!thinking) return;
379
+ const t0 = Date.now();
380
+ setVerb(pickVerb());
381
+ const id = setInterval(() => setElapsed(Date.now() - t0), 100);
382
+ return () => clearInterval(id);
383
+ }, [thinking]);
384
+
385
+ // Permission queue: parallel subagents can ask simultaneously; one dialog
386
+ // at a time, FIFO, so no resolver is ever dropped (a lost resolver = deadlock).
387
+ const permQueue = useRef<PermRequest[]>([]);
388
+ const askPermission = useCallback((tool: string, args: Record<string, unknown>): Promise<boolean> => {
389
+ return new Promise((res) => {
390
+ const req = { tool, args, resolve: res };
391
+ if (toolQueueOpen.current) { permQueue.current.push(req); return; }
392
+ toolQueueOpen.current = true;
393
+ setPerm(req);
394
+ setPermSel(0);
395
+ });
396
+ }, []);
397
+ const nextPerm = useCallback(() => {
398
+ const nxt = permQueue.current.shift() ?? null;
399
+ if (!nxt) toolQueueOpen.current = false;
400
+ else setPerm(nxt);
401
+ setPermSel(0);
402
+ }, []);
403
+
404
+ const buildAgent = useCallback(async (): Promise<Agent | null> => {
405
+ try {
406
+ const r = await resolve(cfgRef.current, registryRef.current);
407
+ const smallClient = await resolveSmall(cfgRef.current, registryRef.current);
408
+ const fallbacks = await resolveFallbacks(cfgRef.current, registryRef.current, sessionRef.current.model);
409
+ const m = modeRef.current;
410
+ // one ToolKit per session so the undo stack + bg tasks survive turns
411
+ if (!toolsRef.current || toolsRef.current.root !== sessionRef.current.cwd)
412
+ toolsRef.current = new ToolKit(sessionRef.current.cwd, { roots: resolveRepos(cfgRef.current.repos, sessionRef.current.cwd) });
413
+ const tools = toolsRef.current;
414
+ // plan mode: read-only — mutating tools are denied up front
415
+ tools.readonly = m === "plan";
416
+ tools.autoApprove = m === "bypass";
417
+ tools.goat = m === "bypass";
418
+ tools.rules = cfgRef.current.permissions;
419
+ tools.hooks = cfgRef.current.hooks;
420
+ tools.sessionId = sessionRef.current.id;
421
+ // acceptEdits auto-approves file edits, still asks for bash (Claude semantics)
422
+ tools.permission = (t, a) =>
423
+ modeRef.current === "bypass" ? true
424
+ : modeRef.current === "acceptEdits" && (t === "write" || t === "edit") ? true
425
+ : sessionRules.current.has(t) ? true
426
+ : askPermission(t, a);
427
+ if (mcp)
428
+ for (const spec of mcp.specs())
429
+ tools.registerExternal({ spec, run: (args) => mcp.dispatch(spec.name, args) });
430
+ // Find tool (Pillar A)
431
+ const roots = new Map(Object.entries(resolveRepos(cfgRef.current.repos, sessionRef.current.cwd)));
432
+ void autoIndexOnce(roots, (p) => { /* progress is a no-op in live frame; /index shows it */ });
433
+ const indexCache = new Map<string, Index | null>();
434
+ const getIndex = (): Index | null => {
435
+ const h = workspaceHash(roots);
436
+ if (!indexCache.has(h)) indexCache.set(h, readIndex(h));
437
+ return indexCache.get(h) ?? null;
438
+ };
439
+ tools.registerExternal({ spec: FIND_TOOL_SPEC, run: makeFindTool({ roots, getIndex }) });
440
+ // remote goat agents (Pillar C) — mounted as remote_<name> tools
441
+ if (cfgRef.current.remoteAgents?.length) {
442
+ const n = await registerRemoteAgents(cfgRef.current, tools);
443
+ if (n < cfgRef.current.remoteAgents.length)
444
+ push(<Text dimColor color={DIM}> ⚠ {cfgRef.current.remoteAgents.length - n} remote agent(s) skipped — set GOAT_REMOTE_TOKEN_&lt;NAME&gt;</Text>);
445
+ else if (n) push(<Text dimColor color={DIM}> ⚡ {n} remote agent(s) mounted</Text>);
446
+ }
447
+ return new Agent({
448
+ client: r.client, smallClient: smallClient ?? undefined,
449
+ session: sessionRef.current, tools,
450
+ maxTokens: cfgRef.current.maxTokens, temperature: cfgRef.current.temperature,
451
+ maxSteps: cfgRef.current.maxSteps,
452
+ fallbacks,
453
+ cache: cfgRef.current.cachePrompts,
454
+ extraSystem: [buildExtraSystem(skills, sessionRef.current.cwd, resolveRepos(cfgRef.current.repos, sessionRef.current.cwd)),
455
+ loadOutputStyle(cfgRef.current.outputStyle)].filter(Boolean).join("\n\n"),
456
+ customAgents: loadCustomAgents(...agentDirs(sessionRef.current.cwd)),
457
+ budgetUsd: cfgRef.current.budgetUsd,
458
+ autoTitle: cfgRef.current.autoTitle,
459
+ // custom-agent `model:` overrides resolve through the same path as the
460
+ // primary model (credentials + OAuth refresh included)
461
+ resolveClientFor: async (model) => {
462
+ const alt = { ...cfgRef.current, model };
463
+ splitModel(alt);
464
+ return (await resolve(alt, registryRef.current)).client;
465
+ },
466
+ });
467
+ } catch (e) {
468
+ const msg = e instanceof ResolveError ? e.message : String((e as Error).message);
469
+ log("resolve", msg);
470
+ if (e instanceof ResolveError) push(<Text color={RED}>{msg}</Text>);
471
+ else push(<Text color={RED}>{msg}</Text>);
472
+ return null;
473
+ }
474
+ }, [askPermission, mcp, push]);
475
+
476
+ const runTurn = useCallback(async (text: string | ContentPart[]) => {
477
+ const agent = await buildAgent();
478
+ if (!agent) return;
479
+ // /rewind anchor: message count at the start of this user turn
480
+ sessionRef.current.turnMarks.push(sessionRef.current.messages.length);
481
+ agent.tools.beginCheckpoint(); // /undo reverts everything from here on
482
+ setThinking(true);
483
+ setStream("");
484
+ setTokens(0);
485
+ const ctrl = new AbortController();
486
+ abortRef.current = ctrl;
487
+ let acc = "";
488
+ let thinkAcc = "";
489
+ const flush = () => {
490
+ if (acc.trim()) push(<MdText text={acc.trimEnd()} />);
491
+ acc = "";
492
+ setStream("");
493
+ };
494
+ try {
495
+ for await (const ev of agent.runTurn(text, ctrl.signal)) {
496
+ if (ctrl.signal.aborted) break;
497
+ switch (ev.kind) {
498
+ case "text": {
499
+ acc += ev.text;
500
+ // The live frame must never exceed the viewport: scrolling breaks
501
+ // Ink's clear/redraw and ghosts the input box (duplicate borders).
502
+ // Anything past the budget scrolls into history (Static) as settled
503
+ // lines — same as Claude Code streaming into scrollback.
504
+ const budget = liveBudget();
505
+ const kept = tailWithin(acc, budget, cols());
506
+ if (kept !== acc) {
507
+ const done = acc.slice(0, acc.length - kept.length).trimEnd();
508
+ if (done.trim()) push(<MdText text={done} />);
509
+ acc = kept;
510
+ }
511
+ setStream(acc);
512
+ break;
513
+ }
514
+ case "thinking":
515
+ thinkAcc += ev.text;
516
+ setThinkLine(thinkAcc.split("\n").slice(-1)[0].slice(0, 120));
517
+ break;
518
+ case "tool_start": {
519
+ flush();
520
+ const a = ev.args as Record<string, unknown>;
521
+ const brief = String(a.path ?? a.command ?? a.pattern ?? JSON.stringify(a)).slice(0, 120);
522
+ push(
523
+ <Text>
524
+ <Text color={ACCENT}>●</Text> <Text bold>{ev.tool}</Text>{" "}
525
+ <Text dimColor color={DIM}>{brief}</Text>
526
+ </Text>,
527
+ );
528
+ // long-running tools (bash) stream their output into a live frame
529
+ if (ev.tool === "bash" || ev.tool === "grep" || ev.tool === "glob") {
530
+ setToolLive({ tool: ev.tool, brief, lines: [] });
531
+ }
532
+ break;
533
+ }
534
+ case "tool_output": {
535
+ // append streamed chunk to the live frame (keep the last N lines)
536
+ setToolLive((cur) => {
537
+ if (!cur) return cur;
538
+ const lines = [...cur.lines, ...ev.text.split("\n")].filter((l) => l.length > 0).slice(-TOOL_LIVE_LINES);
539
+ return { ...cur, lines };
540
+ });
541
+ break;
542
+ }
543
+ case "tool_end": {
544
+ setToolLive(null);
545
+ const first = (ev.result || "").split("\n")[0]?.slice(0, 160) ?? "";
546
+ const dur = ev.durationMs != null && ev.durationMs >= 100
547
+ ? ` · ${(ev.durationMs / 1000).toFixed(1)}s`
548
+ : "";
549
+ push(
550
+ <Text>
551
+ <Text color={ev.ok ? GREEN : RED}> ⎿ {ev.ok ? "completed" : "failed"}</Text>
552
+ <Text dimColor color={DIM}> {first}</Text>
553
+ {dur ? <Text dimColor color={DIM}>{dur}</Text> : null}
554
+ </Text>,
555
+ );
556
+ // inline unified diff after file mutations (from the undo snapshot)
557
+ if (ev.ok && (ev.tool === "edit" || ev.tool === "write" || ev.tool === "multiedit")) {
558
+ const snap = agent.tools.lastSnap();
559
+ if (snap) {
560
+ const lines = unifiedDiff(snap.before, snap.after);
561
+ if (lines.length) push(<DiffView path={snap.path} lines={lines} />);
562
+ // broadcast write op to collab peers (Pillar B)
563
+ const cs = collabRef.current;
564
+ if (cs) {
565
+ const display = agent.tools.displayPath(snap.path);
566
+ const repo = display.includes("/") ? display.split("/")[0] : "";
567
+ cs.sendOp("write", { repo, path: display, before: snap.before.slice(0, 200), after: snap.after.slice(0, 200) });
568
+ }
569
+ }
570
+ }
571
+ break;
572
+ }
573
+ case "usage": {
574
+ const mm = ev.text.match(/(\d+)\+(\d+)/);
575
+ if (mm) setTokens(Number(mm[2]));
576
+ if (ev.usage) setCtxTok(ev.usage.prompt + (ev.usage.cacheRead ?? 0) + (ev.usage.cacheWrite ?? 0));
577
+ break;
578
+ }
579
+ case "todo":
580
+ setTodos(ev.todos);
581
+ break;
582
+ case "fallback":
583
+ flush();
584
+ // stick the switch for later turns AND across restarts
585
+ setCfg((c) => {
586
+ const n = { ...c, model: ev.to };
587
+ splitModel(n);
588
+ saveConfig(n);
589
+ return n;
590
+ });
591
+ push(
592
+ <Text>
593
+ <Text color="#fbbf24">⇢ switched provider</Text>
594
+ <Text dimColor color={DIM}> {ev.from} → {ev.to} — {ev.reason}</Text>
595
+ </Text>,
596
+ );
597
+ log("agent", `fallback ${ev.from} -> ${ev.to}: ${ev.reason}`);
598
+ break;
599
+ case "retry":
600
+ flush();
601
+ push(
602
+ <Text>
603
+ <Text color="#facc15">↻ retrying</Text>
604
+ <Text dimColor color={DIM}> attempt {ev.attempt + 1} in {(ev.waitMs / 1000).toFixed(1)}s — {ev.reason}</Text>
605
+ </Text>,
606
+ );
607
+ break;
608
+ case "error":
609
+ flush();
610
+ log("agent", ev.text);
611
+ push(<Text color={RED}>✗ {ev.text}</Text>);
612
+ break;
613
+ }
614
+ }
615
+ } catch (e: any) {
616
+ push(<Text color={RED}>✗ {e?.message ?? String(e)}</Text>);
617
+ } finally {
618
+ flush();
619
+ setThinking(false);
620
+ setThinkLine("");
621
+ abortRef.current = null;
622
+ setAuthBanner(null); // a successful turn means credentials are fine
623
+ sessionRef.current.save();
624
+ // drain one queued mid-turn message (⤷ steering); recursion through
625
+ // submit->runTurn handles any that arrive during its turn
626
+ if (queuedRef.current.length && !ctrl.signal.aborted) {
627
+ const q = queuedRef.current.shift()!;
628
+ setTimeout(() => submitRef.current?.(q), 50);
629
+ }
630
+ // notify finished background tasks (Claude Code does this between turns)
631
+ for (const t of agent.tools.backgroundTasks()) {
632
+ if (t.status !== "running" && !notifiedBg.current.has(t.id)) {
633
+ notifiedBg.current.add(t.id);
634
+ push(
635
+ <Text>
636
+ <Text color={ACCENT}>⚡ </Text>
637
+ <Text dimColor color={DIM}>task {t.id} finished: {t.cmd.slice(0, 48)} — {t.status.split("\n")[0].slice(0, 80)}</Text>
638
+ </Text>,
639
+ );
640
+ }
641
+ }
642
+ }
643
+ }, [buildAgent, push]);
644
+
645
+ const makeSlashIO = useCallback((): SlashIO => ({
646
+ cfg: cfgRef.current, setCfg, registry: registryRef.current,
647
+ session: sessionRef.current,
648
+ setSession: (s) => { sessionRef.current = s; setSession(s); },
649
+ saveCfg: saveConfig, push, exit, mcp, skills,
650
+ clearAuthBanner: () => setAuthBanner(null),
651
+ undoTurn: () => toolsRef.current ? toolsRef.current.undoCheckpoint() : null,
652
+ sessionRules: () => [...sessionRules.current],
653
+ rewindTurn: (n) => {
654
+ const t = toolsRef.current;
655
+ const s = sessionRef.current;
656
+ if (!t || !s.turnMarks.length) return null;
657
+ const idx = Math.max(0, Math.min(n - 1, s.turnMarks.length - 1));
658
+ const mark = s.turnMarks[idx];
659
+ const res = t.rewindTo(idx);
660
+ if (!res) return null;
661
+ s.messages = s.messages.slice(0, mark);
662
+ s.turnMarks = s.turnMarks.slice(0, idx);
663
+ s.save();
664
+ return { files: res.files, msgs: s.messages.length };
665
+ },
666
+ backgroundTasks: () => toolsRef.current?.backgroundTasks() ?? [],
667
+ setMode: (m) => {
668
+ setMode(m);
669
+ setCfg((c) => ({ ...c, autoApprove: m === "bypass" }));
670
+ const tk = toolsRef.current;
671
+ if (tk) { tk.autoApprove = m === "bypass"; tk.goat = m === "bypass"; tk.readonly = m === "plan"; }
672
+ },
673
+ reloadPlugins: () => {
674
+ const pl = loadPlugins(cfgRef.current.pluginDirs.map((d) => resolvePath(process.cwd(), d)));
675
+ const fromPlugins = pluginSkills(pl);
676
+ const native = loadSkills(
677
+ join(appDir(), "skills"),
678
+ join(process.cwd(), "skills"),
679
+ join(process.cwd(), ".claude", "skills"),
680
+ );
681
+ const names = new Set(native.map((s) => s.name));
682
+ setSkills([...native, ...fromPlugins.filter((s) => !names.has(s.name))]);
683
+ return native.length + fromPlugins.length;
684
+ },
685
+ runTurn,
686
+ sessionSnaps: () => (toolsRef.current?.allSnaps() ?? []).map((s) => ({ path: s.path, before: s.before, after: s.after })),
687
+ customAgents: () => loadCustomAgents(...agentDirs(sessionRef.current.cwd)).map((a) => ({ name: a.name, description: a.description, tools: a.tools })),
688
+ compactNow: async () => {
689
+ const agent = await buildAgent();
690
+ if (!agent) return "compact failed — no usable client";
691
+ const r = await agent.compactNow();
692
+ if (r.folded === 0) return "already compacted — nothing older to fold";
693
+ return `summarized ${r.folded} older messages${r.model ? " with the model" : " (deterministic digest fallback)"} — context rebuilt`;
694
+ },
695
+ collab: collabRef.current,
696
+ }), [buildAgent, exit, mcp, push, runTurn, skills]);
697
+
698
+ const submit = useCallback((raw: string) => {
699
+ const text = raw.trim();
700
+ if (!text) return;
701
+ // Collab turn-gate: if not holding the turn, warn and do NOT runTurn
702
+ const cs = collabRef.current;
703
+ if (cs && !canSpeakFor(cs)) {
704
+ push(<Text color="#facc15"> waiting for turn ({cs.holder() ?? "unknown"})</Text>);
705
+ return;
706
+ }
707
+ // Mid-turn steering (Claude Code / Codex parity): typing while the agent
708
+ // works queues the message for immediate follow-up instead of dropping it.
709
+ if (thinking) {
710
+ setInput("");
711
+ setCompletions([]);
712
+ queuedRef.current.push(text);
713
+ push(<Text dimColor color={DIM}> ⤷ queued for next turn ({queuedRef.current.length})</Text>);
714
+ return;
715
+ }
716
+ // Enter with the completion menu open accepts, like Claude Code — but only
717
+ // while still typing the command itself (no space yet). Once the user has
718
+ // typed arguments, Enter submits; accepting would truncate them.
719
+ if (compOpen && completions.length > 0 && compSel < completions.length) {
720
+ const accepted = acceptCompletion(text, compKind, completions[compSel]);
721
+ if (accepted.trimEnd() !== text.trimEnd()) {
722
+ setInput(accepted);
723
+ setCompletions([]);
724
+ setCompOpen(false);
725
+ return;
726
+ }
727
+ // exact command already typed -> fall through and SUBMIT
728
+ }
729
+ setHistory((h) => [...h, text]);
730
+ setHistIdx(-1);
731
+ setInput("");
732
+ setCompletions([]);
733
+ push(<Text><Text color={ACCENT} bold>❯ </Text><Text>{text}</Text></Text>);
734
+
735
+ // !bash mode — run a shell command directly, output to scrollback
736
+ if (text.startsWith("!")) {
737
+ const cmd = text.slice(1).trim();
738
+ (async () => {
739
+ if (!toolsRef.current || toolsRef.current.root !== sessionRef.current.cwd)
740
+ toolsRef.current = new ToolKit(sessionRef.current.cwd, { roots: resolveRepos(cfgRef.current.repos, sessionRef.current.cwd) });
741
+ const tk = toolsRef.current;
742
+ const wasAuto = tk.autoApprove, hadPerm = tk.permission;
743
+ tk.autoApprove = true; tk.permission = null;
744
+ const r = await tk.dispatch("bash", { command: cmd });
745
+ tk.autoApprove = wasAuto; tk.permission = hadPerm;
746
+ push(<Text color={r.ok ? GREEN : RED}>{r.output.slice(0, 4000)}</Text>);
747
+ })();
748
+ return;
749
+ }
750
+ // # memory — append a line to project GOAT.md
751
+ if (text.startsWith("#")) {
752
+ const note = text.slice(1).trim();
753
+ if (note) {
754
+ try {
755
+ const memPath = join(sessionRef.current.cwd, "GOAT.md");
756
+ if (!existsSync(memPath)) appendFileSync(memPath, "# Project memory\n\n");
757
+ appendFileSync(memPath, `- ${note}\n`);
758
+ push(<Text color={GREEN}>✓ saved to GOAT.md</Text>);
759
+ } catch (e: any) {
760
+ push(<Text color={RED}>✗ {e?.message}</Text>);
761
+ }
762
+ }
763
+ return;
764
+ }
765
+
766
+ // @file references — text refs inline as fenced content; image refs attach
767
+ // base64 parts the model can see (anthropic/openai/gemini/responses)
768
+ let expanded = buildUserContent(text, sessionRef.current.cwd, (m) => push(<Text color={RED}> ⚠ {m}</Text>));
769
+ // ctrl+V image: attach as a base64 part (and give a bare paste a prompt)
770
+ if (pasted) {
771
+ try {
772
+ const buf = readFileSync(pasted);
773
+ const mediaType = sniffImage(buf);
774
+ if (mediaType) {
775
+ const imgPart = { type: "image", data: buf.toString("base64"), mediaType } as ContentPart;
776
+ const intro = typeof expanded === "string"
777
+ ? (text ? expanded : "What do you see in this image?")
778
+ : expanded;
779
+ expanded = Array.isArray(intro)
780
+ ? [...intro, imgPart]
781
+ : [{ type: "text", text: intro }, imgPart];
782
+ }
783
+ } catch { /* fall back to text-only */ }
784
+ try { unlinkSync(pasted); } catch { /* */ }
785
+ setPasted(null);
786
+ }
787
+
788
+ // /skill-name invocation: load the body and run it as a prompt
789
+ if (text.startsWith("/") && !SLASH_COMMANDS.some((c) => text === c || text.startsWith(c + " "))) {
790
+ const name = text.slice(1).split(" ")[0];
791
+ const rest = text.slice(1 + name.length).trim();
792
+ const sk = skills.find((s) => s.name === name);
793
+ if (sk) {
794
+ const body = loadSkillBody(sk).replace(/\$ARGUMENTS/g, rest).replace(/\$(\d)/g, (_, i) => rest.split(/\s+/)[Number(i) - 1] ?? "");
795
+ void runTurn(`[skill: /${sk.name}]\n${body}\n\n${rest || "Execute this skill on the current project."}`);
796
+ return;
797
+ }
798
+ }
799
+ if (text.startsWith("/")) {
800
+ runSlash(text, makeSlashIO());
801
+ return;
802
+ }
803
+ void runTurn(expanded);
804
+ }, [thinking, push, skills, runTurn, completions, compSel, pasted, makeSlashIO]);
805
+ submitRef.current = submit;
806
+
807
+ const cycleMode = useCallback(() => {
808
+ // entering bypass resolves any open permission prompt YES — the user just
809
+ // said "stop asking"; leaving bypass leaves a pending prompt alone
810
+ if (modeRef.current !== "bypass" && permRef.current) {
811
+ permRef.current.resolve(true);
812
+ setPerm(null);
813
+ nextPerm();
814
+ }
815
+ setMode((m) => {
816
+ const next = MODE_ORDER[(MODE_ORDER.indexOf(m) + 1) % MODE_ORDER.length];
817
+ setCfg((c) => ({ ...c, autoApprove: next === "bypass" }));
818
+ // apply to the RUNNING turn immediately — a mid-turn switch must take
819
+ // effect now, not at the next buildAgent (this was the bypass bug)
820
+ const tk = toolsRef.current;
821
+ if (tk) {
822
+ tk.autoApprove = next === "bypass";
823
+ tk.goat = next === "bypass";
824
+ tk.readonly = next === "plan";
825
+ }
826
+ if (next === "bypass")
827
+ push(<Text color="#facc15"> 🐐 GOAT MODE — no prompts, no rules, no sandbox. Full power. shift+tab to step back.</Text>);
828
+ return next;
829
+ });
830
+ }, [push]);
831
+
832
+ // keyboard handling
833
+ useInput((ch, k) => {
834
+ if (perm) {
835
+ const resolvePerm = (choice: number) => {
836
+ if (choice === 1) {
837
+ sessionRules.current.add(perm.tool);
838
+ if (perm.tool === "write" || perm.tool === "edit" || perm.tool === "multiedit") setMode("acceptEdits");
839
+ }
840
+ perm.resolve(choice < 2);
841
+ setPerm(null);
842
+ nextPerm();
843
+ };
844
+ if (k.upArrow) setPermSel((s) => (s + 2) % 3);
845
+ else if (k.downArrow) setPermSel((s) => (s + 1) % 3);
846
+ else if (k.return) resolvePerm(permSel);
847
+ else if (ch === "1" || ch === "y" || ch === "Y") resolvePerm(0);
848
+ else if (ch === "2" || ch === "a" || ch === "A") resolvePerm(1);
849
+ else if (k.escape || ch === "3" || ch === "n" || ch === "N") resolvePerm(2);
850
+ return;
851
+ }
852
+ if (k.ctrl && ch === "c") {
853
+ if (thinking) { abortRef.current?.abort(); push(<Text color={RED}>⚠ interrupted</Text>); return; }
854
+ // Claude Code semantics: one Ctrl+C warns, a second within 2s exits
855
+ const now = Date.now();
856
+ if (now - lastCtrlC.current < 2000) { exit(); return; }
857
+ lastCtrlC.current = now;
858
+ push(<Text dimColor color={DIM}> press ctrl+c again to exit · or /quit · session auto-saved</Text>);
859
+ return;
860
+ }
861
+ if (k.ctrl && ch === "p") {
862
+ // Ctrl+P: open command palette
863
+ setIsPaletteOpen(true);
864
+ return;
865
+ }
866
+ if (k.ctrl && ch === "d") { exit(); return; }
867
+ if (k.ctrl && ch === "k") { setInput(""); return; } // clear current input line
868
+ if (k.ctrl && ch === "v") {
869
+ // clipboard image attach (Claude-Code-style); text pastes are handled by
870
+ // the terminal itself and arrive as ordinary input
871
+ void clipboardImage().then((p) => {
872
+ if (!p) { push(<Text dimColor color={DIM}> clipboard has no image</Text>); return; }
873
+ try {
874
+ const size = statSync(p).size;
875
+ if (size > MAX_IMAGE_BYTES) { push(<Text color={RED}> ⚠ pasted image too large ({size} bytes)</Text>); return; }
876
+ if (!sniffImage(readFileSync(p))) { push(<Text color={RED}> ⚠ clipboard image is not a png/jpeg/gif/webp</Text>); return; }
877
+ setPasted(p);
878
+ push(<Text color={ACCENT}> ⧈ image attached from clipboard — type your question and hit Enter</Text>);
879
+ } catch (e: any) {
880
+ push(<Text color={RED}> paste failed: {e?.message ?? e}</Text>);
881
+ }
882
+ });
883
+ return;
884
+ }
885
+ if (k.ctrl && ch === "t") {
886
+ const rows = toolsRef.current?.backgroundTasks() ?? [];
887
+ if (!rows.length) push(<Text dimColor color={DIM}> no background tasks</Text>);
888
+ else for (const t of rows)
889
+ push(
890
+ <Text>
891
+ <Text color={ACCENT}>{t.id.padEnd(24)}</Text>
892
+ <Text color={t.status === "running" ? "#facc15" : GREEN}>{t.status === "running" ? "● running" : "✓ done"}</Text>
893
+ <Text dimColor color={DIM}> {t.cmd.slice(0, 48)}</Text>
894
+ </Text>,
895
+ );
896
+ return;
897
+ }
898
+ if (k.ctrl && ch === "j") {
899
+ // toggle verbose streamed tool output in the live frame
900
+ setToolVerbose((v) => !v);
901
+ return;
902
+ }
903
+ if (k.ctrl && ch === "o") { cycleMode(); return; }
904
+ if (ch === "\x1b" || ch.toLowerCase() === "f1") { /* F1/Escape show help - handled below */ }
905
+ // Shift+Tab arrives as an empty char with shift+tab flags (verified via
906
+ // Ink's parse-keypress); older/odd terminals send ESC [ Z as raw text.
907
+ if ((k.shift && k.tab) || ch === "\x1b[Z") { cycleMode(); return; }
908
+ if (k.ctrl && ch === "l") {
909
+ // Static output is already on the terminal — wipe screen + scrollback
910
+ // then reset state so the live region repaints from a clean slate.
911
+ process.stdout.write("\x1b[2J\x1b[H\x1b[3J");
912
+ setLines([]); setStream(""); return;
913
+ }
914
+ if (k.ctrl && ch === "r") {
915
+ // reverse history search: cycle inserted prompt from history
916
+ if (history.length) {
917
+ const q = input.trim();
918
+ const idx = history.map((h, i) => ({ h, i })).reverse()
919
+ .find(({ h }) => !q || h.toLowerCase().includes(q.toLowerCase()));
920
+ if (idx) setInput(history[idx.i]);
921
+ }
922
+ return;
923
+ }
924
+ if (k.meta && ch === "m") { cycleMode(); return; } // Windows fallback for Shift+Tab
925
+ if (k.escape && thinking) { abortRef.current?.abort(); return; }
926
+ if (k.upArrow) {
927
+ if (completions.length) setCompSel((s) => Math.max(0, s - 1));
928
+ else if (history.length) {
929
+ const ni = histIdx < 0 ? history.length - 1 : Math.max(0, histIdx - 1);
930
+ setHistIdx(ni);
931
+ setInput(history[ni]);
932
+ }
933
+ return;
934
+ }
935
+ if (k.downArrow) {
936
+ if (completions.length) setCompSel((s) => Math.min(completions.length - 1, s + 1));
937
+ else if (histIdx >= 0) {
938
+ const ni = histIdx + 1;
939
+ if (ni >= history.length) { setHistIdx(-1); setInput(""); }
940
+ else { setHistIdx(ni); setInput(history[ni]); }
941
+ }
942
+ return;
943
+ }
944
+ if (k.tab && completions.length) {
945
+ setInput(acceptCompletion(input, compKind, completions[compSel]));
946
+ setCompletions([]);
947
+ }
948
+ });
949
+
950
+ // live completion: slash commands at line start, @file refs in the last token
951
+ useEffect(() => {
952
+ if (input.startsWith("/") && !input.includes(" ")) {
953
+ setCompKind("slash");
954
+ setCompOpen(true); setCompletions(SLASH_COMMANDS.filter((c) => c.startsWith(input)).slice(0, 8));
955
+ setCompSel(0);
956
+ return;
957
+ }
958
+ const m = input.match(/(^|\s)@([^\s]*)$/);
959
+ if (m) {
960
+ const token = m[2];
961
+ const files = listProjectFiles(sessionRef.current.cwd);
962
+ setCompKind("at");
963
+ setCompOpen(true); setCompletions(atCompletions(token, files));
964
+ setCompSel(0);
965
+ return;
966
+ }
967
+ setCompletions([]);
968
+ }, [input]);
969
+
970
+ // custom statusline: refresh on mode/session changes, during thinking, and
971
+ // every 12s otherwise (5s command timeout — cheap enough)
972
+ useEffect(() => {
973
+ const cmd = cfg.statusLine?.command;
974
+ if (!cmd) { setStatusLines([]); return; }
975
+ let cancelled = false;
976
+ const tick = async () => {
977
+ const used = sessionRef.current.messages.reduce((s, m) => s + contentChars(m.content), 0);
978
+ const lines = await runStatusLine(cmd, statusInput(sessionRef.current, cfg.model, cfg.outputStyle, used, thinking));
979
+ if (!cancelled && lines) setStatusLines(lines);
980
+ };
981
+ void tick();
982
+ const id = setInterval(() => void tick(), thinking ? 3000 : 12_000);
983
+ return () => { cancelled = true; clearInterval(id); };
984
+ }, [cfg.statusLine?.command, thinking, session, mode, cfg.model, cfg.outputStyle]);
985
+
986
+ const frame = SPINNER_FRAMES[Math.floor(elapsed / 120) % SPINNER_FRAMES.length];
987
+
988
+ return (
989
+ <Box flexDirection="column" width="100%">
990
+ <Static items={lines}>
991
+ {(item) => item}
992
+ </Static>
993
+
994
+ {authBanner && (
995
+ <Box flexDirection="column" borderStyle="round" borderColor="#facc15" paddingX={1} marginY={1} backgroundColor={BG_PANEL}>
996
+ <Text color="#facc15" bold>⚠ GoatCode is installed but not ready yet</Text>
997
+ <Text dimColor color={DIM}>{authBanner}</Text>
998
+ <Text dimColor color={DIM}> then type a message and hit Enter, or run /auth to fix it now</Text>
999
+ </Box>
1000
+ )}
1001
+ {thinking && (
1002
+ <Box flexDirection="column">
1003
+ <Text>
1004
+ <Text color={ACCENT}>{frame} {verb}…</Text>
1005
+ <Text dimColor color={DIM}>
1006
+ {" "}{fmtElapsed(elapsed)}{tokens ? ` · ${tokens} tok` : ""}
1007
+ </Text>
1008
+ </Text>
1009
+ {thinkLine && !stream ? <Text dimColor color={DIM}> {thinkLine}</Text> : null}
1010
+ {stream ? <MdText text={stream} /> : null}
1011
+ {toolLive ? (
1012
+ <Box flexDirection="column" paddingLeft={2} marginTop={0}>
1013
+ {(toolVerbose ? toolLive.lines : toolLive.lines.slice(-TOOL_LIVE_LINES)).map((l, i) => (
1014
+ <Text key={i} color="#9aa3b8">{l.slice(0, Math.max(40, cols() - 6))}</Text>
1015
+ ))}
1016
+ {!toolVerbose && toolLive.lines.length > TOOL_LIVE_LINES ? (
1017
+ <Text dimColor color={DIM}> … {toolLive.lines.length - TOOL_LIVE_LINES} more lines (ctrl+j for all)</Text>
1018
+ ) : null}
1019
+ </Box>
1020
+ ) : null}
1021
+ <Text dimColor color={DIM}> esc to interrupt</Text>
1022
+ </Box>
1023
+ )}
1024
+
1025
+ {perm && <PermDialog req={perm} sel={permSel} />}
1026
+
1027
+ {todos.length > 0 && <PlanPanel todos={todos} />}
1028
+
1029
+ {mcpErrors.length > 0 && (
1030
+ <Box flexDirection="column" paddingLeft={1} marginBottom={0}>
1031
+ {mcpErrors.map((e, i) => (
1032
+ <Text key={i} color="#facc15"> ⚠ {e}</Text>
1033
+ ))}
1034
+ </Box>
1035
+ )}
1036
+
1037
+ <Box flexDirection="column">
1038
+ <Box borderStyle="round" borderColor={thinking ? ACCENT : "#6d28d9"} paddingLeft={1} backgroundColor={BG_DEEP}>
1039
+ <Text color={ACCENT} bold>❯ </Text>
1040
+ <TextInput
1041
+ value={input}
1042
+ onChange={setInput}
1043
+ onSubmit={submit}
1044
+ placeholder="help me build… (/ for commands)"
1045
+ />
1046
+ </Box>
1047
+ {completions.length > 0 && (
1048
+ <Box flexDirection="column" paddingLeft={2}>
1049
+ {completions.map((c, i) => (
1050
+ <Text key={c}>
1051
+ <Text color={i === compSel ? ACCENT : undefined} backgroundColor={i === compSel ? BG_PANEL : undefined} bold={i === compSel}>{compKind === "at" ? "@" + c : c}</Text>
1052
+ {compKind === "slash" && <Text dimColor color={DIM}> {COMMAND_DESC[c]}</Text>}
1053
+ </Text>
1054
+ ))}
1055
+ </Box>
1056
+ )}
1057
+ </Box>
1058
+
1059
+ {mode === "bypass" ? (
1060
+ <Box paddingLeft={1} marginBottom={1}>
1061
+ <Text color="#facc15" bold> 🐐 ULTRACODE ACTIVE · no sandbox · no rules · no prompts · subagents fan to 8</Text>
1062
+ </Box>
1063
+ ) : cfg.statusLine?.command && statusLines.length ? (
1064
+ <Box flexDirection="column" paddingLeft={1}>
1065
+ {statusLines.map((l, i) => <Text key={i} dimColor color={DIM}>{l}</Text>)}
1066
+ </Box>
1067
+ ) : (
1068
+ <Box paddingLeft={1} flexDirection="column">
1069
+ <Text dimColor color={DIM}>
1070
+ <Text color={modeColor(mode)}>{MODE_LABEL[mode]}</Text>
1071
+ <Text dimColor color={DIM}> · </Text>
1072
+ <Text color={cfg.model.startsWith("anthropic") || cfg.model.startsWith("claude") ? GREEN : ACCENT}>{cfg.model}</Text>
1073
+ <Text dimColor color={DIM}> │ </Text>
1074
+ <Text color={DIM}>{shortPath(session.cwd)}</Text>
1075
+ {(() => {
1076
+ const pct = contextPct(cfg.modelId, ctxTok, cfg.contextWindow);
1077
+ if (pct == null) return null;
1078
+ const clamped = Math.max(0, Math.min(1, pct));
1079
+ const filled = Math.round(clamped * 8);
1080
+ const bar = "█".repeat(filled) + "░".repeat(8 - filled);
1081
+ const c = clamped > 0.9 ? RED : clamped > 0.7 ? "#facc15" : GREEN;
1082
+ return <Text color={c}>{` · [${bar}] ${Math.round(clamped * 100)}%`}</Text>;
1083
+ })()}
1084
+ {(() => {
1085
+ const usd = costUsd(cfg.model, session.usage);
1086
+ if (usd == null || usd <= 0) return null;
1087
+ return <Text color={GREEN}> · ${usd < 0.01 ? usd.toFixed(4) : usd.toFixed(2)}</Text>;
1088
+ })()}
1089
+ {queuedRef.current.length ? <Text color={ACCENT}> · ⤷ {queuedRef.current.length} queued</Text> : null}
1090
+ {mcp?.servers.size ? <Text dimColor color={DIM}> · {mcp.servers.size} mcp</Text> : null}
1091
+ {skills.length ? <Text dimColor color={DIM}> · {skills.length} skills</Text> : null}
1092
+ </Text>
1093
+ <Text dimColor color={DIM}>
1094
+ <Text color={ACCENT}>/help</Text>
1095
+ <Text dimColor color={DIM}> · shift+tab mode · ctrl+t tasks · ctrl+j verbose · /undo · ctrl+p commands</Text>
1096
+ </Text>
1097
+ </Box>
1098
+ )}
1099
+
1100
+ {isPaletteOpen && (
1101
+ <CommandPalette
1102
+ commands={paletteCommands}
1103
+ onSelect={(cmd: Command) => {
1104
+ setIsPaletteOpen(false);
1105
+ if (cmd.name.startsWith("/")) {
1106
+ void runSlash(cmd.name, makeSlashIO());
1107
+ }
1108
+ }}
1109
+ onClose={() => setIsPaletteOpen(false)}
1110
+ />
1111
+ )}
1112
+ </Box>
1113
+ );
1114
+ }
1115
+
1116
+ // ---------- sub-components ----------
1117
+
1118
+ /** Colored unified diff block, capped at 12 rows (Static history — safe). */
1119
+ function DiffView({ path, lines }: { path: string; lines: string[] }) {
1120
+ const { added, removed } = diffStats(lines);
1121
+ const shown = lines.slice(0, 12);
1122
+ return (
1123
+ <Box flexDirection="column" paddingLeft={2}>
1124
+ <Text dimColor color={DIM}>{" "}{shortPath(path)} <Text color={GREEN}>+{added}</Text><Text color={RED}> -{removed}</Text></Text>
1125
+ {shown.map((l, i) => (
1126
+ <Text key={i} color={l[0] === "+" ? GREEN : l[0] === "-" ? RED : DIM}>
1127
+ {l.slice(0, 140)}
1128
+ </Text>
1129
+ ))}
1130
+ {lines.length > 12 && <Text dimColor color={DIM}> … {lines.length - 12} more rows</Text>}
1131
+ </Box>
1132
+ );
1133
+ }
1134
+
1135
+ function PlanPanel({ todos }: { todos: Todo[] }) {
1136
+ const done = todos.filter((t) => t.status === "completed").length;
1137
+ return (
1138
+ <Box flexDirection="column" paddingLeft={1} marginBottom={0}>
1139
+ <Text dimColor color={DIM}> Plan {done}/{todos.length}</Text>
1140
+ {todos.slice(-4).map((t, i) => (
1141
+ <Text key={`${t.content}-${i}`}>
1142
+ <Text color={t.status === "completed" ? GREEN : t.status === "in_progress" ? ACCENT : DIM}>
1143
+ {" "}{t.status === "completed" ? "✔" : t.status === "in_progress" ? "▸" : "○"}{" "}
1144
+ </Text>
1145
+ <Text color={t.status === "completed" ? DIM : undefined} strikethrough={t.status === "completed"}>
1146
+ {t.status === "in_progress" ? t.activeForm : t.content}
1147
+ </Text>
1148
+ </Text>
1149
+ ))}
1150
+ </Box>
1151
+ );
1152
+ }
1153
+
1154
+ function gitBranchOf(cwd: string): string | null {
1155
+ try {
1156
+ const out = execSync("git rev-parse --abbrev-ref HEAD", { cwd, stdio: ["ignore", "pipe", "ignore"], timeout: 1200 })
1157
+ .toString("utf8").trim();
1158
+ return out || null;
1159
+ } catch {
1160
+ return null;
1161
+ }
1162
+ }
1163
+
1164
+ function Welcome({ cfg, cwd }: { cfg: GoatConfig; cwd: string }) {
1165
+ const mark = [
1166
+ "███ ███",
1167
+ "███▄ ▄███",
1168
+ "▀███▄ ▄▄▄▄▄▄ ▄███▀",
1169
+ " ▀████▀▀▀▀████▀",
1170
+ " ▄▄████▄ ▄████▄▄",
1171
+ " ██▀▀▀ ▀▀▀██",
1172
+ " ▀██▄ ▀▀ ▄██▀",
1173
+ " ▀██████▀",
1174
+ " ▄▀▄",
1175
+ ];
1176
+ const branch = gitBranchOf(cwd);
1177
+ const tips = [
1178
+ { key: "↑↓", label: "history" },
1179
+ { key: "ctrl+p", label: "palette" },
1180
+ { key: "ctrl+t", label: "tasks" },
1181
+ { key: "shift+tab", label: "mode" },
1182
+ { key: "esc", label: "interrupt" },
1183
+ ];
1184
+ return (
1185
+ <Box flexDirection="column" marginBottom={1}>
1186
+ <Box flexDirection="row">
1187
+ <Box flexDirection="column" marginRight={3}>
1188
+ {mark.map((l, i) => <Text key={i} color={ACCENT}>{l}</Text>)}
1189
+ </Box>
1190
+ <Box flexDirection="column" justifyContent="center">
1191
+ <Text>
1192
+ <Text color={ACCENT} bold>ibex</Text>
1193
+ <Text dimColor color={DIM}> (GoatCode v{VERSION}) · every provider, one terminal</Text>
1194
+ </Text>
1195
+ <Text dimColor color={DIM}>model <Text color={GREEN}>{cfg.model}</Text></Text>
1196
+ <Text dimColor color={DIM}>path {shortPath(cwd)}{branch ? <Text color={ACCENT}> ({branch})</Text> : null}</Text>
1197
+ <Text> </Text>
1198
+ <Text dimColor color={DIM}>180+ providers · native Anthropic/OpenAI/Gemini · Monaco IDE · P2P</Text>
1199
+ <Text dimColor color={DIM}>/index /find /ultraplan /share /doctor /fork /models --live</Text>
1200
+ </Box>
1201
+ </Box>
1202
+ <Text> </Text>
1203
+ <Box flexDirection="row">
1204
+ <Text dimColor color={DIM}>keys </Text>
1205
+ {tips.map((t, i) => (
1206
+ <Text key={i} dimColor color={DIM}>
1207
+ {i > 0 ? " " : ""}
1208
+ <Text color={ACCENT}>{t.key}</Text>
1209
+ <Text color={DIM}> {t.label}</Text>
1210
+ </Text>
1211
+ ))}
1212
+ </Box>
1213
+ </Box>
1214
+ );
1215
+ }
1216
+
1217
+ function PermDialog({ req, sel }: { req: PermRequest; sel: number }) {
1218
+ const a = req.args as Record<string, unknown>;
1219
+ const detail = String(a.command ?? a.path ?? JSON.stringify(a)).slice(0, 200);
1220
+ const opts = [
1221
+ "Yes",
1222
+ `Yes, and always allow ${req.tool} this session`,
1223
+ "No, and tell the agent what to do differently",
1224
+ ];
1225
+ return (
1226
+ <Box flexDirection="column" borderStyle="round" borderColor={ACCENT} paddingX={1} marginY={1} backgroundColor={BG_PANEL}>
1227
+ <Text bold>● {req.tool} — allow?</Text>
1228
+ <Text dimColor color={DIM}> {detail}</Text>
1229
+ <Text> </Text>
1230
+ <Text>Do you want to proceed?</Text>
1231
+ {opts.map((o, i) => (
1232
+ <Text key={i}>
1233
+ <Text color={i === sel ? ACCENT : DIM}>{i === sel ? "❯ " : " "}</Text>
1234
+ <Text bold={i === sel}>{i + 1}. {o}</Text>
1235
+ </Text>
1236
+ ))}
1237
+ <Text dimColor color={DIM}> [y/a/n or 1-3] · ↑↓ move · enter confirm · esc cancel</Text>
1238
+ </Box>
1239
+ );
1240
+ }
1241
+
1242
+ const CODE_KW = /\b(const|let|var|function|async|await|return|import|export|from|if|else|for|while|match|fn|pub|struct|enum|impl|trait|use|mod|crate|def|class|try|catch|throw|new|type|interface|true|false|null|None|Some|Ok|Err|self|mut)\b/g;
1243
+
1244
+ function highlightCodeLine(line: string, baseKey: number): ReactNode[] {
1245
+ const trimmed = line.trimStart();
1246
+ if (trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("--")) {
1247
+ return [<Text key={baseKey} dimColor color={DIM}>{line}</Text>];
1248
+ }
1249
+ const nodes: ReactNode[] = [];
1250
+ const tokenRe = /("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`|\b\d+(?:\.\d+)?\b|\b(?:const|let|var|function|async|await|return|import|export|from|if|else|for|while|match|fn|pub|struct|enum|impl|trait|use|mod|crate|def|class|try|catch|throw|new|type|interface|true|false|null|None|Some|Ok|Err|self|mut)\b)/g;
1251
+ let last = 0, m: RegExpExecArray | null, k = 0;
1252
+ while ((m = tokenRe.exec(line))) {
1253
+ if (m.index > last) nodes.push(<Text key={`${baseKey}-${k++}`} color="#e2e8f0">{line.slice(last, m.index)}</Text>);
1254
+ const tok = m[0];
1255
+ if (tok.startsWith('"') || tok.startsWith("'") || tok.startsWith("`")) {
1256
+ nodes.push(<Text key={`${baseKey}-${k++}`} color={GREEN}>{tok}</Text>);
1257
+ } else if (/^\d/.test(tok)) {
1258
+ nodes.push(<Text key={`${baseKey}-${k++}`} color={YELL}>{tok}</Text>);
1259
+ } else {
1260
+ nodes.push(<Text key={`${baseKey}-${k++}`} color={ACCENT} bold>{tok}</Text>);
1261
+ }
1262
+ last = m.index + tok.length;
1263
+ }
1264
+ if (last < line.length) nodes.push(<Text key={`${baseKey}-${k++}`} color="#e2e8f0">{line.slice(last)}</Text>);
1265
+ return nodes.length ? nodes : [<Text key={baseKey} color="#e2e8f0">{line}</Text>];
1266
+ }
1267
+
1268
+ function renderInlineMd(ln: string): ReactNode[] {
1269
+ const parts: ReactNode[] = [];
1270
+ const re = /(\*\*[^*]+\*\*|`[^`]+`)/g;
1271
+ let last = 0, m: RegExpExecArray | null, key = 0;
1272
+ while ((m = re.exec(ln))) {
1273
+ if (m.index > last) parts.push(<Text key={key++}>{ln.slice(last, m.index)}</Text>);
1274
+ const tok = m[0];
1275
+ if (tok.startsWith("**")) parts.push(<Text key={key++} bold>{tok.slice(2, -2)}</Text>);
1276
+ else parts.push(<Text key={key++} color={ACCENT}>{tok.slice(1, -1)}</Text>);
1277
+ last = m.index + tok.length;
1278
+ }
1279
+ if (last < ln.length) parts.push(<Text key={key++}>{ln.slice(last)}</Text>);
1280
+ return parts;
1281
+ }
1282
+
1283
+ /** Markdown renderer: fenced code blocks with syntax highlight, headings, quotes, lists, bold & inline code. */
1284
+ function MdText({ text }: { text: string }) {
1285
+ const out: ReactNode[] = [];
1286
+ const rawLines = text.split("\n");
1287
+ let inCode = false;
1288
+ let codeLang = "";
1289
+ rawLines.forEach((ln, i) => {
1290
+ const fence = ln.match(/^```(\S*)/);
1291
+ if (fence) {
1292
+ if (!inCode) {
1293
+ inCode = true;
1294
+ codeLang = fence[1] || "code";
1295
+ out.push(
1296
+ <Box key={i} paddingLeft={1}>
1297
+ <Text dimColor color={ACCENT}>┌─ {codeLang} ──────────</Text>
1298
+ </Box>,
1299
+ );
1300
+ } else {
1301
+ inCode = false;
1302
+ codeLang = "";
1303
+ out.push(
1304
+ <Box key={i} paddingLeft={1}>
1305
+ <Text dimColor color={DIM}>└────────────────</Text>
1306
+ </Box>,
1307
+ );
1308
+ }
1309
+ return;
1310
+ }
1311
+ if (inCode) {
1312
+ out.push(
1313
+ <Box key={i} paddingLeft={1} minHeight={1}>
1314
+ <Text>
1315
+ <Text color={DIM}>│ </Text>
1316
+ {highlightCodeLine(ln, i)}
1317
+ </Text>
1318
+ </Box>,
1319
+ );
1320
+ return;
1321
+ }
1322
+ const heading = ln.match(/^(#{1,3})\s+(.*)$/);
1323
+ if (heading) {
1324
+ out.push(
1325
+ <Box key={i} minHeight={1}>
1326
+ <Text color={heading[1].length === 1 ? ACCENT : "#e2e8f0"} bold>{heading[2]}</Text>
1327
+ </Box>,
1328
+ );
1329
+ return;
1330
+ }
1331
+ if (/^(-{3,}|\*{3,})$/.test(ln.trim())) {
1332
+ out.push(<Box key={i}><Text dimColor color={DIM}>────────────────────────</Text></Box>);
1333
+ return;
1334
+ }
1335
+ if (ln.startsWith("> ")) {
1336
+ out.push(
1337
+ <Box key={i} minHeight={1}>
1338
+ <Text><Text color={ACCENT}>▎ </Text><Text dimColor color={DIM}>{renderInlineMd(ln.slice(2))}</Text></Text>
1339
+ </Box>,
1340
+ );
1341
+ return;
1342
+ }
1343
+ const bullet = ln.match(/^(\s*)[-*]\s+(.*)$/);
1344
+ if (bullet) {
1345
+ out.push(
1346
+ <Box key={i} minHeight={1}>
1347
+ <Text>{bullet[1]}<Text color={ACCENT}>• </Text>{renderInlineMd(bullet[2])}</Text>
1348
+ </Box>,
1349
+ );
1350
+ return;
1351
+ }
1352
+ out.push(<Box key={i} minHeight={1}><Text>{renderInlineMd(ln)}</Text></Box>);
1353
+ });
1354
+ return <Box flexDirection="column">{out}</Box>;
1355
+ }