@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
@@ -0,0 +1,506 @@
1
+ /**
2
+ * goat ide — the GoatCode IDE: a Monaco-based web IDE served locally with the
3
+ * full GoatCode agent embedded.
4
+ *
5
+ * Same trust model as `goat web`: binds 127.0.0.1 only, requires a per-boot
6
+ * token in the URL, and streams the live agent loop over SSE. The editor is
7
+ * the vendored Monaco engine (MIT, from VS Code) — no network needed.
8
+ *
9
+ * Endpoints:
10
+ * GET / the IDE shell (HTML)
11
+ * GET /vendor/vs/* vendored Monaco assets
12
+ * GET /api/events?token= SSE: hello/state/user/agent/permission/file
13
+ * POST /api/action prompt | stop | permission | mode | open | save
14
+ * GET /api/state?token= session + tree snapshot
15
+ * GET /api/file?path= read a file (cwd-jailed)
16
+ * POST /api/file write a file (cwd-jailed)
17
+ * GET /api/tree?token= file tree JSON
18
+ */
19
+ import { randomBytes } from "node:crypto";
20
+ import { execSync, spawn } from "node:child_process";
21
+ import { readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from "node:fs";
22
+ import { join, relative, resolve as resolvePath, extname } from "node:path";
23
+ import { UI_HTML } from "./assets.gen.ts";
24
+ import { Agent } from "../agent.ts";
25
+ import { Session, listSessions } from "../session.ts";
26
+ import { ToolKit } from "../tools.ts";
27
+ import { loadConfig, MODEL_ALIASES, saveConfig, splitModel, resolveRepos, type GoatConfig } from "../config.ts";
28
+ import { ProviderRegistry } from "../providers.ts";
29
+ import { resolve, resolveSmall, resolveFallbacks } from "../runtime.ts";
30
+ import { buildExtraSystem, loadOutputStyle } from "../context.ts";
31
+ import { allSkills } from "../index-shared.ts";
32
+ import { loadMcpFromConfig } from "../mcp/client.ts";
33
+ import { estimateTokens, type ContentPart } from "../llm.ts";
34
+ import { costUsd } from "../pricing.ts";
35
+ import { VERSION, WEB_DEFAULT_PORT } from "../constants.ts";
36
+ import { buildUserContent } from "../refs.ts";
37
+ import { insideRoot, SKIP_DIRS } from "../tools.ts";
38
+ import { loadCustomAgents, agentDirs } from "../agents/loader.ts";
39
+
40
+ interface PermReq { tool: string; args: Record<string, unknown>; resolve: (ok: boolean) => void }
41
+
42
+ const JSON_EXT = new Set([".json", ".jsonc", ".json5"]);
43
+ const LANG_BY_EXT: Record<string, string> = {
44
+ ".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
45
+ ".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
46
+ ".py": "python", ".rs": "rust", ".go": "go", ".java": "java", ".c": "c", ".h": "c",
47
+ ".cpp": "cpp", ".hpp": "cpp", ".cs": "csharp", ".rb": "ruby", ".php": "php",
48
+ ".swift": "swift", ".kt": "kotlin", ".md": "markdown", ".html": "html", ".htm": "html",
49
+ ".css": "css", ".scss": "scss", ".less": "less", ".json": "json", ".jsonc": "json",
50
+ ".yml": "yaml", ".yaml": "yaml", ".toml": "ini", ".ini": "ini", ".sql": "sql",
51
+ ".sh": "shell", ".bash": "shell", ".zsh": "shell", ".xml": "xml", ".svg": "xml",
52
+ ".vue": "html", ".svelte": "html", ".lua": "lua", ".pl": "perl", ".r": "r",
53
+ ".dart": "dart", ".graphql": "graphql", ".proto": "proto", ".tf": "hcl",
54
+ };
55
+
56
+ export interface IdeOpts { port?: number; open?: boolean }
57
+
58
+ export async function runIde(opts: IdeOpts = {}): Promise<void> {
59
+ const cfg: GoatConfig = loadConfig();
60
+ const registry = new ProviderRegistry(cfg.endpoints);
61
+ const token = randomBytes(12).toString("hex");
62
+ const port = Number(opts.port ?? process.env.GOAT_IDE_PORT ?? WEB_DEFAULT_PORT);
63
+ const root = process.cwd();
64
+
65
+ let session = Session.new(root, cfg.model);
66
+ let mode = (cfg.autoApprove ? "bypass" : "default") as "default" | "acceptEdits" | "plan" | "bypass";
67
+ let tools: ToolKit | null = null;
68
+ let mcp: Awaited<ReturnType<typeof loadMcpFromConfig>> | null = null;
69
+ let turnCtrl: AbortController | null = null;
70
+ let turnBusy = false;
71
+ const pending = new Map<string, PermReq>();
72
+ const clients = new Set<{ controller: ReadableStreamDefaultController; enc: TextEncoder }>();
73
+ const openFiles = new Set<string>();
74
+ /** Ring buffer of the last events, replayed to clients that connect mid-turn. */
75
+ const eventLog: unknown[] = [];
76
+ const EVENT_LOG_MAX = 500;
77
+
78
+ try { mcp = await loadMcpFromConfig({ mcpServers: cfg.mcpServers }); } catch { /* optional */ }
79
+
80
+ function textOfLite(c: string | ContentPart[]): string {
81
+ return typeof c === "string" ? c : c.map((p) => (p.type === "text" ? p.text : "[image]")).join(" ");
82
+ }
83
+
84
+ function broadcast(obj: unknown): void {
85
+ eventLog.push(obj);
86
+ if (eventLog.length > EVENT_LOG_MAX) eventLog.splice(0, eventLog.length - EVENT_LOG_MAX);
87
+ const data = `data: ${JSON.stringify(obj)}\n\n`;
88
+ for (const c of clients) {
89
+ try { c.controller.enqueue(c.enc.encode(data)); }
90
+ catch { clients.delete(c); } // client gone — drop it
91
+ }
92
+ }
93
+
94
+ function buildTools(): ToolKit {
95
+ const tk = new ToolKit(root, { autoApprove: cfg.autoApprove, rules: cfg.permissions, roots: resolveRepos(cfg.repos, root) });
96
+ if (mode === "bypass") tk.goat = true;
97
+ if (mode === "acceptEdits") {
98
+ tk.permission = async (tool) => tool === "bash" || tool === "computer" ? askPerm(tool, {}) : true;
99
+ } else if (mode === "plan") {
100
+ tk.readonly = true;
101
+ } else {
102
+ tk.permission = async (tool, args) => askPerm(tool, args);
103
+ }
104
+ tk.hooks = cfg.hooks;
105
+ return tk;
106
+ }
107
+
108
+ function askPerm(tool: string, args: Record<string, unknown>): Promise<boolean> {
109
+ return new Promise((res) => {
110
+ const id = randomBytes(6).toString("hex");
111
+ pending.set(id, { tool, args, resolve: res });
112
+ broadcast({ kind: "permission", id, tool, args });
113
+ });
114
+ }
115
+
116
+ async function rebuildAgent(resumeId?: string): Promise<Agent | null> {
117
+ const r = await resolve(cfg, registry);
118
+ if (!tools) tools = buildTools();
119
+ tools.goat = mode === "bypass";
120
+ tools.readonly = mode === "plan";
121
+ if (mcp) {
122
+ for (const spec of mcp.specs())
123
+ tools.registerExternal({ spec, run: (args) => mcp!.dispatch(spec.name, args) });
124
+ }
125
+ return new Agent({
126
+ client: r.client, smallClient: (await resolveSmall(cfg, registry)) ?? undefined,
127
+ fallbacks: await resolveFallbacks(cfg, registry),
128
+ session, tools,
129
+ maxTokens: cfg.maxTokens, temperature: cfg.temperature, maxSteps: cfg.maxSteps,
130
+ cache: cfg.cachePrompts,
131
+ extraSystem: [buildExtraSystem(allSkills(cfg), root, resolveRepos(cfg.repos, root)),
132
+ loadOutputStyle(cfg.outputStyle)].filter(Boolean).join("\n\n"),
133
+ customAgents: loadCustomAgents(...agentDirs(root)),
134
+ budgetUsd: cfg.budgetUsd,
135
+ resolveClientFor: async (model) => {
136
+ const alt = { ...cfg, model };
137
+ splitModel(alt);
138
+ return (await resolve(alt, registry)).client;
139
+ },
140
+ });
141
+ }
142
+
143
+ function snapshotState() {
144
+ let cost: number | null = null;
145
+ try { cost = costUsd(session.model, session.usage) ?? null; } catch { cost = null; }
146
+ const prov = registry.get(cfg.provider);
147
+ const modelOpts = [...new Set([
148
+ cfg.model,
149
+ ...(prov?.models ?? []).map((m) => `${cfg.provider}/${m}`),
150
+ ...Object.values(MODEL_ALIASES),
151
+ ])].slice(0, 30);
152
+ return {
153
+ session: { id: session.id, title: session.title, cwd: root },
154
+ model: cfg.model,
155
+ models: modelOpts,
156
+ mode,
157
+ version: VERSION,
158
+ busy: turnBusy,
159
+ usage: session.usage,
160
+ contextTokens: session.messages.reduce((s, m) => s + estimateTokens(m.content), 0),
161
+ cost,
162
+ openFiles: [...openFiles],
163
+ mcpServers: Object.keys(cfg.mcpServers).length,
164
+ skills: allSkills(cfg).length,
165
+ };
166
+ }
167
+
168
+ function gitStatusSnapshot(): { branch: string | null; changes: Record<string, string> } {
169
+ const changes: Record<string, string> = {};
170
+ let branch: string | null = null;
171
+ try {
172
+ branch = execSync("git rev-parse --abbrev-ref HEAD", { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 1500 })
173
+ .toString("utf8").trim() || null;
174
+ const raw = execSync("git status --porcelain", { cwd: root, stdio: ["ignore", "pipe", "ignore"], timeout: 1500 })
175
+ .toString("utf8");
176
+ for (const line of raw.split(/\r?\n/)) {
177
+ if (line.length < 4) continue;
178
+ const code = line.slice(0, 2).trim() || "M";
179
+ const file = line.slice(3).replace(/^"|"$/g, "").replaceAll("\\", "/");
180
+ if (file) changes[file] = code === "??" ? "?" : code[0] ?? "M";
181
+ }
182
+ } catch { /* not a git repo */ }
183
+ return { branch, changes };
184
+ }
185
+
186
+ function searchWorkspace(query: string): Array<{ path: string; line: number; text: string }> {
187
+ const q = query.trim().toLowerCase();
188
+ if (!q) return [];
189
+ const hits: Array<{ path: string; line: number; text: string }> = [];
190
+ const walkSearch = (dir: string, depth: number) => {
191
+ if (depth > 6 || hits.length >= 80) return;
192
+ let entries;
193
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
194
+ for (const e of entries) {
195
+ if (hits.length >= 80) break;
196
+ if (SKIP_DIRS.has(e.name) || (e.name.startsWith(".") && e.name !== ".github")) continue;
197
+ const abs = join(dir, e.name);
198
+ if (e.isDirectory()) { walkSearch(abs, depth + 1); continue; }
199
+ try {
200
+ if (statSync(abs).size > 512_000) continue;
201
+ const raw = readFileSync(abs);
202
+ if (raw.subarray(0, 2048).includes(0)) continue;
203
+ const lines = raw.toString("utf8").split(/\r?\n/);
204
+ const rel = relative(root, abs).replaceAll("\\", "/");
205
+ for (let i = 0; i < lines.length && hits.length < 80; i++) {
206
+ if (lines[i].toLowerCase().includes(q)) {
207
+ hits.push({ path: rel, line: i + 1, text: lines[i].trim().slice(0, 140) });
208
+ }
209
+ }
210
+ } catch { /* unreadable */ }
211
+ }
212
+ };
213
+ walkSearch(root, 0);
214
+ return hits;
215
+ }
216
+
217
+ function broadcastState(): void {
218
+ broadcast({ kind: "state", ...snapshotState() });
219
+ }
220
+
221
+ // ---------- file APIs (cwd-jailed) ----------
222
+
223
+ function jail(relPath: string): string {
224
+ return insideRoot(root, relPath);
225
+ }
226
+
227
+ function fileTree(dir = root, depth = 0, maxDepth = 6): any[] {
228
+ if (depth > maxDepth) return [];
229
+ let entries;
230
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return []; }
231
+ entries.sort((a, b) => (a.isDirectory() === b.isDirectory())
232
+ ? a.name.localeCompare(b.name)
233
+ : (a.isDirectory() ? -1 : 1));
234
+ const out: any[] = [];
235
+ for (const e of entries) {
236
+ if (SKIP_DIRS.has(e.name) || (e.name.startsWith(".") && e.name !== ".github" && e.name !== ".vscode")) continue;
237
+ const abs = join(dir, e.name);
238
+ const rel = relative(root, abs).replaceAll("\\", "/");
239
+ if (e.isDirectory()) {
240
+ out.push({ name: e.name, path: rel, dir: true, children: fileTree(abs, depth + 1, maxDepth) });
241
+ } else {
242
+ let size = 0;
243
+ try { size = statSync(abs).size; } catch { /* unreadable */ }
244
+ out.push({ name: e.name, path: rel, dir: false, size, lang: LANG_BY_EXT[extname(e.name).toLowerCase()] ?? "plaintext" });
245
+ }
246
+ if (out.length > 2000) break;
247
+ }
248
+ return out;
249
+ }
250
+
251
+ async function runTurn(text: string): Promise<void> {
252
+ turnBusy = true;
253
+ broadcastState();
254
+ try {
255
+ const agent = await rebuildAgent();
256
+ if (!agent) throw new Error("no usable provider — run `goat auth <provider> --key <K>` or connect a key");
257
+ broadcast({ kind: "user", text });
258
+ const expanded = buildUserContent(text, root);
259
+ turnCtrl = new AbortController();
260
+ const turn = agent.runTurn(expanded, turnCtrl.signal);
261
+ for await (const ev of turn) {
262
+ if (ev.kind === "text") broadcast({ kind: "agent", ev });
263
+ else if (ev.kind === "thinking") broadcast({ kind: "agent", ev });
264
+ else if (ev.kind === "tool_start") broadcast({ kind: "agent", ev });
265
+ else if (ev.kind === "tool_output") broadcast({ kind: "agent", ev });
266
+ else if (ev.kind === "tool_end") { broadcast({ kind: "agent", ev }); broadcastState(); }
267
+ else if (ev.kind === "todo") broadcast({ kind: "agent", ev });
268
+ else if (ev.kind === "usage") broadcast({ kind: "agent", ev });
269
+ else if (ev.kind === "retry") broadcast({ kind: "agent", ev });
270
+ else if (ev.kind === "fallback") broadcast({ kind: "agent", ev });
271
+ else if (ev.kind === "error") broadcast({ kind: "error", text: ev.text });
272
+ else if (ev.kind === "done") { broadcastState(); }
273
+ }
274
+ } catch (e: any) {
275
+ broadcast({ kind: "error", text: e?.message ?? String(e) });
276
+ } finally {
277
+ turnBusy = false;
278
+ turnCtrl = null;
279
+ broadcastState();
280
+ }
281
+ }
282
+
283
+ // ---------- HTTP + SSE server ----------
284
+
285
+ const MIME: Record<string, string> = {
286
+ ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css",
287
+ ".json": "application/json", ".svg": "image/svg+xml", ".ttf": "font/ttf", ".woff": "font/woff",
288
+ };
289
+
290
+ async function handle(req: Request): Promise<Response> {
291
+ const url = new URL(req.url);
292
+ const path = url.pathname;
293
+ const auth = () => url.searchParams.get("token") === token || req.headers.get("x-goat-token") === token;
294
+
295
+ if (path === "/") {
296
+ return new Response(UI_HTML, { headers: { "content-type": "text/html; charset=utf-8" } });
297
+ }
298
+
299
+ // vendored Monaco — immutable, local. In dev this resolves to
300
+ // src/ide/vendor (this module's directory). In a `bun build --compile`
301
+ // binary import.meta.dir is a virtual path, so we also try beside the
302
+ // executable (ide-vendor/, copied by the release workflow / installer)
303
+ // and ~/.goatcode/ide-vendor (written on first run by the updater).
304
+ if (path.startsWith("/vendor/vs/")) {
305
+ const rel = decodeURIComponent(path.slice("/vendor/".length)).replaceAll("\\", "/");
306
+ if (rel.includes("..")) return new Response("forbidden", { status: 403 });
307
+ const { dirname } = await import("node:path");
308
+ const home = process.env.GOATCODE_HOME || join(process.env.USERPROFILE || process.env.HOME || ".", ".goatcode");
309
+ const candidates = [
310
+ join(dirname(process.execPath), "ide-vendor", rel),
311
+ join(home, "ide-vendor", rel),
312
+ join(import.meta.dir, "vendor", rel),
313
+ ];
314
+ let body: Buffer | null = null;
315
+ let foundExt = "";
316
+ for (const file of candidates) {
317
+ try { body = readFileSync(file); foundExt = extname(file); break; } catch { /* try next */ }
318
+ }
319
+ if (!body) return new Response("not found", { status: 404 });
320
+ return new Response(new Uint8Array(body), {
321
+ headers: {
322
+ "content-type": MIME[foundExt.toLowerCase()] ?? "application/octet-stream",
323
+ "cache-control": "public, max-age=31536000, immutable",
324
+ },
325
+ });
326
+ }
327
+
328
+ if (path === "/api/events") {
329
+ if (!auth()) return new Response("unauthorized", { status: 401 });
330
+ const enc = new TextEncoder();
331
+ let ping: ReturnType<typeof setInterval> | null = null;
332
+ const stream = new ReadableStream({
333
+ start(controller) {
334
+ const client = { controller, enc };
335
+ clients.add(client);
336
+ // replay: anything broadcast before this client connected (capped)
337
+ try {
338
+ for (const past of eventLog) controller.enqueue(enc.encode(`data: ${JSON.stringify(past)}\n\n`));
339
+ } catch { /* client vanished mid-replay */ }
340
+ const hello = { kind: "hello", state: snapshotState(), token };
341
+ controller.enqueue(enc.encode(`data: ${JSON.stringify(hello)}\n\n`));
342
+ ping = setInterval(() => {
343
+ try { controller.enqueue(enc.encode(": ping\n\n")); } catch { /* gone */ }
344
+ }, 20_000);
345
+ },
346
+ cancel() {
347
+ if (ping) clearInterval(ping);
348
+ // cancel() has no handle to the client entry — drop the most recently
349
+ // added stream whose controller is unusable. Probing with a zero-byte
350
+ // enqueue can ECONNRESET healthy streams, so sweep lazily: broadcast
351
+ // prunes dead entries on its next enqueue failure.
352
+ },
353
+ });
354
+ return new Response(stream, {
355
+ headers: { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" },
356
+ });
357
+ }
358
+
359
+ if (path === "/api/state") {
360
+ if (!auth()) return new Response("unauthorized", { status: 401 });
361
+ return Response.json({ ...snapshotState(), sessions: listSessions().slice(0, 12) });
362
+ }
363
+
364
+ if (path === "/api/tree") {
365
+ if (!auth()) return new Response("unauthorized", { status: 401 });
366
+ return Response.json({ root, tree: fileTree() });
367
+ }
368
+
369
+ if (path === "/api/git") {
370
+ if (!auth()) return new Response("unauthorized", { status: 401 });
371
+ return Response.json(gitStatusSnapshot());
372
+ }
373
+
374
+ if (path === "/api/search") {
375
+ if (!auth()) return new Response("unauthorized", { status: 401 });
376
+ const q = url.searchParams.get("q") ?? "";
377
+ return Response.json({ query: q, hits: searchWorkspace(q) });
378
+ }
379
+
380
+ if (path === "/api/exec" && req.method === "POST") {
381
+ if (!auth()) return new Response("unauthorized", { status: 401 });
382
+ const body = await req.json() as { command?: string };
383
+ const command = String(body.command ?? "").trim();
384
+ if (!command) return Response.json({ ok: false, exitCode: 1, output: "command is required" }, { status: 400 });
385
+ const res = await new Promise<{ ok: boolean; exitCode: number; output: string }>((done) => {
386
+ const sh = process.platform === "win32" ? (process.env.COMSPEC || "cmd.exe") : "/bin/sh";
387
+ const args = process.platform === "win32" ? ["/c", command] : ["-c", command];
388
+ const child = spawn(sh, args, { cwd: root });
389
+ let out = "";
390
+ const timer = setTimeout(() => {
391
+ try { child.kill(); } catch { /* */ }
392
+ done({ ok: false, exitCode: 124, output: out + "\n[command timed out after 15s]" });
393
+ }, 15_000);
394
+ child.stdout.on("data", (d) => { if (out.length < 32_000) out += d.toString(); });
395
+ child.stderr.on("data", (d) => { if (out.length < 32_000) out += d.toString(); });
396
+ child.on("close", (code) => {
397
+ clearTimeout(timer);
398
+ done({ ok: code === 0, exitCode: code ?? 0, output: out.slice(0, 32_000) });
399
+ });
400
+ child.on("error", (e) => {
401
+ clearTimeout(timer);
402
+ done({ ok: false, exitCode: 1, output: String(e?.message ?? e) });
403
+ });
404
+ });
405
+ return Response.json(res);
406
+ }
407
+
408
+ if (path === "/api/file" && req.method === "GET") {
409
+ if (!auth()) return new Response("unauthorized", { status: 401 });
410
+ try {
411
+ const p = jail(url.searchParams.get("path") ?? "");
412
+ const stat = statSync(p);
413
+ if (stat.size > 2_000_000) return Response.json({ error: "file too large (>2MB)" }, { status: 413 });
414
+ return Response.json({ path: url.searchParams.get("path"), content: readFileSync(p, "utf8") });
415
+ } catch (e: any) {
416
+ return Response.json({ error: e?.message ?? "read failed" }, { status: 400 });
417
+ }
418
+ }
419
+
420
+ if (path === "/api/file" && req.method === "POST") {
421
+ if (!auth()) return new Response("unauthorized", { status: 401 });
422
+ try {
423
+ const body = await req.json() as { path?: string; content?: string };
424
+ const p = jail(String(body.path ?? ""));
425
+ writeFileSync(p, String(body.content ?? ""), "utf8");
426
+ openFiles.add(String(body.path));
427
+ return Response.json({ ok: true });
428
+ } catch (e: any) {
429
+ return Response.json({ error: e?.message ?? "write failed" }, { status: 400 });
430
+ }
431
+ }
432
+
433
+ if (path === "/api/action" && req.method === "POST") {
434
+ if (!auth()) return new Response("unauthorized", { status: 401 });
435
+ const a = await req.json() as Record<string, any>;
436
+ switch (a.action) {
437
+ case "prompt": {
438
+ if (turnBusy) return Response.json({ ok: false, error: "busy" });
439
+ void runTurn(String(a.text ?? ""));
440
+ return Response.json({ ok: true });
441
+ }
442
+ case "stop": {
443
+ turnCtrl?.abort();
444
+ return Response.json({ ok: true });
445
+ }
446
+ case "permission": {
447
+ const pr = pending.get(String(a.id));
448
+ if (pr) { pending.delete(String(a.id)); pr.resolve(!!a.allow); }
449
+ return Response.json({ ok: true });
450
+ }
451
+ case "mode": {
452
+ const m = String(a.mode ?? "default");
453
+ if (["default", "acceptEdits", "plan", "bypass"].includes(m)) { mode = m as any; broadcastState(); }
454
+ return Response.json({ ok: true });
455
+ }
456
+ case "model": {
457
+ cfg.model = String(a.model ?? cfg.model); splitModel(cfg); saveConfig(cfg);
458
+ session.model = cfg.model;
459
+ broadcastState();
460
+ return Response.json({ ok: true });
461
+ }
462
+ case "open": {
463
+ const rel = String(a.path ?? "");
464
+ openFiles.add(rel);
465
+ broadcast({ kind: "file", path: rel, action: "open" });
466
+ return Response.json({ ok: true });
467
+ }
468
+ case "new_session": {
469
+ if (turnBusy) return Response.json({ ok: false, error: "busy" });
470
+ session = Session.new(root, cfg.model);
471
+ broadcastState();
472
+ return Response.json({ ok: true, sessionId: session.id });
473
+ }
474
+ default:
475
+ return Response.json({ ok: false, error: "unknown action" }, { status: 400 });
476
+ }
477
+ }
478
+
479
+ return new Response("not found", { status: 404 });
480
+ }
481
+
482
+ const server = Bun.serve({ port, hostname: "127.0.0.1", fetch: (req) => handle(req) });
483
+ const actual = server.port;
484
+ const url = `http://127.0.0.1:${actual}/?token=${token}`;
485
+
486
+ console.log("");
487
+ console.log(" 🐐 GoatCode IDE");
488
+ console.log(` ${url}`);
489
+ console.log(` workspace: ${root}`);
490
+ console.log(` model: ${cfg.model}`);
491
+ console.log(" Ctrl+C to stop");
492
+ console.log("");
493
+
494
+ if (opts.open) {
495
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
496
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
497
+ const { spawn } = await import("node:child_process");
498
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
499
+ child.unref();
500
+ }
501
+
502
+ await new Promise<void>((res) => {
503
+ process.once("SIGINT", () => { server.stop(true); mcp?.shutdown?.(); res(); });
504
+ process.once("SIGTERM", () => { server.stop(true); mcp?.shutdown?.(); res(); });
505
+ });
506
+ }