wide-cli 0.0.0-stage → 0.3.101126

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 (172) hide show
  1. package/.github/workflows/ci.yml +29 -0
  2. package/LICENSE +674 -0
  3. package/README.md +80 -2
  4. package/assets/logo.png +0 -0
  5. package/assets/wide-logo.png +0 -0
  6. package/bin/wide.js +17 -0
  7. package/dist/agent/context.d.ts +7 -0
  8. package/dist/agent/context.d.ts.map +1 -0
  9. package/dist/agent/context.js +38 -0
  10. package/dist/agent/context.js.map +1 -0
  11. package/dist/agent/index.d.ts +16 -0
  12. package/dist/agent/index.d.ts.map +1 -0
  13. package/dist/agent/index.js +138 -0
  14. package/dist/agent/index.js.map +1 -0
  15. package/dist/config/index.d.ts +29 -0
  16. package/dist/config/index.d.ts.map +1 -0
  17. package/dist/config/index.js +66 -0
  18. package/dist/config/index.js.map +1 -0
  19. package/dist/config/workspace.d.ts +7 -0
  20. package/dist/config/workspace.d.ts.map +1 -0
  21. package/dist/config/workspace.js +31 -0
  22. package/dist/config/workspace.js.map +1 -0
  23. package/dist/decision/index.d.ts +113 -0
  24. package/dist/decision/index.d.ts.map +1 -0
  25. package/dist/decision/index.js +485 -0
  26. package/dist/decision/index.js.map +1 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +167 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/providers/claude.d.ts +10 -0
  32. package/dist/providers/claude.d.ts.map +1 -0
  33. package/dist/providers/claude.js +147 -0
  34. package/dist/providers/claude.js.map +1 -0
  35. package/dist/providers/gemini.d.ts +10 -0
  36. package/dist/providers/gemini.d.ts.map +1 -0
  37. package/dist/providers/gemini.js +129 -0
  38. package/dist/providers/gemini.js.map +1 -0
  39. package/dist/providers/index.d.ts +4 -0
  40. package/dist/providers/index.d.ts.map +1 -0
  41. package/dist/providers/index.js +44 -0
  42. package/dist/providers/index.js.map +1 -0
  43. package/dist/providers/ollama.d.ts +10 -0
  44. package/dist/providers/ollama.d.ts.map +1 -0
  45. package/dist/providers/ollama.js +94 -0
  46. package/dist/providers/ollama.js.map +1 -0
  47. package/dist/providers/openai.d.ts +11 -0
  48. package/dist/providers/openai.d.ts.map +1 -0
  49. package/dist/providers/openai.js +142 -0
  50. package/dist/providers/openai.js.map +1 -0
  51. package/dist/providers/types.d.ts +22 -0
  52. package/dist/providers/types.d.ts.map +1 -0
  53. package/dist/providers/types.js +2 -0
  54. package/dist/providers/types.js.map +1 -0
  55. package/dist/repl/index.d.ts +2 -0
  56. package/dist/repl/index.d.ts.map +1 -0
  57. package/dist/repl/index.js +94 -0
  58. package/dist/repl/index.js.map +1 -0
  59. package/dist/security/fuzzer.d.ts +20 -0
  60. package/dist/security/fuzzer.d.ts.map +1 -0
  61. package/dist/security/fuzzer.js +109 -0
  62. package/dist/security/fuzzer.js.map +1 -0
  63. package/dist/security/loader.d.ts +17 -0
  64. package/dist/security/loader.d.ts.map +1 -0
  65. package/dist/security/loader.js +126 -0
  66. package/dist/security/loader.js.map +1 -0
  67. package/dist/security/payloads.d.ts +9 -0
  68. package/dist/security/payloads.d.ts.map +1 -0
  69. package/dist/security/payloads.js +88 -0
  70. package/dist/security/payloads.js.map +1 -0
  71. package/dist/security/rules.d.ts +14 -0
  72. package/dist/security/rules.d.ts.map +1 -0
  73. package/dist/security/rules.js +288 -0
  74. package/dist/security/rules.js.map +1 -0
  75. package/dist/security/scanner.d.ts +29 -0
  76. package/dist/security/scanner.d.ts.map +1 -0
  77. package/dist/security/scanner.js +136 -0
  78. package/dist/security/scanner.js.map +1 -0
  79. package/dist/tools/browser.d.ts +47 -0
  80. package/dist/tools/browser.d.ts.map +1 -0
  81. package/dist/tools/browser.js +441 -0
  82. package/dist/tools/browser.js.map +1 -0
  83. package/dist/tools/fs.d.ts +5 -0
  84. package/dist/tools/fs.d.ts.map +1 -0
  85. package/dist/tools/fs.js +131 -0
  86. package/dist/tools/fs.js.map +1 -0
  87. package/dist/tools/git.d.ts +3 -0
  88. package/dist/tools/git.d.ts.map +1 -0
  89. package/dist/tools/git.js +50 -0
  90. package/dist/tools/git.js.map +1 -0
  91. package/dist/tools/http.d.ts +3 -0
  92. package/dist/tools/http.d.ts.map +1 -0
  93. package/dist/tools/http.js +69 -0
  94. package/dist/tools/http.js.map +1 -0
  95. package/dist/tools/index.d.ts +5 -0
  96. package/dist/tools/index.d.ts.map +1 -0
  97. package/dist/tools/index.js +50 -0
  98. package/dist/tools/index.js.map +1 -0
  99. package/dist/tools/search.d.ts +4 -0
  100. package/dist/tools/search.d.ts.map +1 -0
  101. package/dist/tools/search.js +109 -0
  102. package/dist/tools/search.js.map +1 -0
  103. package/dist/tools/security.d.ts +5 -0
  104. package/dist/tools/security.d.ts.map +1 -0
  105. package/dist/tools/security.js +129 -0
  106. package/dist/tools/security.js.map +1 -0
  107. package/dist/tools/shell.d.ts +3 -0
  108. package/dist/tools/shell.d.ts.map +1 -0
  109. package/dist/tools/shell.js +50 -0
  110. package/dist/tools/shell.js.map +1 -0
  111. package/dist/tools/types.d.ts +33 -0
  112. package/dist/tools/types.d.ts.map +1 -0
  113. package/dist/tools/types.js +2 -0
  114. package/dist/tools/types.js.map +1 -0
  115. package/dist/ui/banner.d.ts +2 -0
  116. package/dist/ui/banner.d.ts.map +1 -0
  117. package/dist/ui/banner.js +14 -0
  118. package/dist/ui/banner.js.map +1 -0
  119. package/dist/ui/colors.d.ts +18 -0
  120. package/dist/ui/colors.d.ts.map +1 -0
  121. package/dist/ui/colors.js +19 -0
  122. package/dist/ui/colors.js.map +1 -0
  123. package/dist/ui/diff.d.ts +2 -0
  124. package/dist/ui/diff.d.ts.map +1 -0
  125. package/dist/ui/diff.js +26 -0
  126. package/dist/ui/diff.js.map +1 -0
  127. package/dist/ui/markdown.d.ts +2 -0
  128. package/dist/ui/markdown.d.ts.map +1 -0
  129. package/dist/ui/markdown.js +32 -0
  130. package/dist/ui/markdown.js.map +1 -0
  131. package/dist/ui/spinner.d.ts +12 -0
  132. package/dist/ui/spinner.d.ts.map +1 -0
  133. package/dist/ui/spinner.js +46 -0
  134. package/dist/ui/spinner.js.map +1 -0
  135. package/package.json +50 -4
  136. package/src/agent/context.ts +44 -0
  137. package/src/agent/index.ts +166 -0
  138. package/src/config/index.ts +88 -0
  139. package/src/config/workspace.ts +39 -0
  140. package/src/decision/index.ts +528 -0
  141. package/src/index.ts +180 -0
  142. package/src/providers/claude.ts +163 -0
  143. package/src/providers/gemini.ts +147 -0
  144. package/src/providers/index.ts +52 -0
  145. package/src/providers/ollama.ts +108 -0
  146. package/src/providers/openai.ts +159 -0
  147. package/src/providers/types.ts +29 -0
  148. package/src/repl/index.ts +100 -0
  149. package/src/security/fuzzer.ts +140 -0
  150. package/src/security/loader.ts +129 -0
  151. package/src/security/payloads.ts +95 -0
  152. package/src/security/rules.ts +300 -0
  153. package/src/security/scanner.ts +180 -0
  154. package/src/tools/browser.ts +528 -0
  155. package/src/tools/fs.ts +143 -0
  156. package/src/tools/git.ts +51 -0
  157. package/src/tools/http.ts +77 -0
  158. package/src/tools/index.ts +64 -0
  159. package/src/tools/search.ts +109 -0
  160. package/src/tools/security.ts +140 -0
  161. package/src/tools/shell.ts +56 -0
  162. package/src/tools/types.ts +33 -0
  163. package/src/ui/banner.ts +17 -0
  164. package/src/ui/colors.ts +19 -0
  165. package/src/ui/diff.ts +24 -0
  166. package/src/ui/markdown.ts +34 -0
  167. package/src/ui/spinner.ts +53 -0
  168. package/tests/browser.test.mjs +71 -0
  169. package/tests/decision.test.mjs +68 -0
  170. package/tests/loader.test.mjs +24 -0
  171. package/tests/suite.test.mjs +61 -0
  172. package/tsconfig.json +20 -0
@@ -0,0 +1,528 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { Tool, ToolExecutionContext, ToolResult } from "./types.js";
4
+
5
+ export interface DOMElement {
6
+ index: number;
7
+ tag: string;
8
+ text: string;
9
+ role: string;
10
+ href?: string;
11
+ name?: string;
12
+ value?: string;
13
+ attributes: Record<string, string>;
14
+ }
15
+
16
+ export interface BrowserState {
17
+ url: string;
18
+ title: string;
19
+ statusCode: number;
20
+ elements: DOMElement[];
21
+ textContent: string;
22
+ rawHtml: string;
23
+ formInputs: Record<string, string>;
24
+ history: string[];
25
+ }
26
+
27
+ export class HeadlessBrowserController {
28
+ private state: BrowserState = {
29
+ url: "about:blank",
30
+ title: "",
31
+ statusCode: 200,
32
+ elements: [],
33
+ textContent: "",
34
+ rawHtml: "",
35
+ formInputs: {},
36
+ history: []
37
+ };
38
+
39
+ private userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Wide-CLI/0.291126";
40
+
41
+ public findSystemBrowserExecutable(): string | null {
42
+ const candidates: string[] = [];
43
+
44
+ if (process.platform === "win32") {
45
+ const localAppData = process.env.LOCALAPPDATA || "";
46
+ const programFiles = process.env["ProgramFiles"] || "C:\\Program Files";
47
+ const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
48
+
49
+ candidates.push(
50
+ path.join(programFilesX86, "Microsoft", "Edge", "Application", "msedge.exe"),
51
+ path.join(programFiles, "Microsoft", "Edge", "Application", "msedge.exe"),
52
+ path.join(programFiles, "Google", "Chrome", "Application", "chrome.exe"),
53
+ path.join(programFilesX86, "Google", "Chrome", "Application", "chrome.exe"),
54
+ path.join(localAppData, "Microsoft", "Edge", "Application", "msedge.exe"),
55
+ path.join(localAppData, "Google", "Chrome", "Application", "chrome.exe")
56
+ );
57
+ } else if (process.platform === "darwin") {
58
+ candidates.push(
59
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
60
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
61
+ "/Applications/Chromium.app/Contents/MacOS/Chromium"
62
+ );
63
+ } else {
64
+ candidates.push(
65
+ "/usr/bin/google-chrome",
66
+ "/usr/bin/google-chrome-stable",
67
+ "/usr/bin/chromium",
68
+ "/usr/bin/chromium-browser",
69
+ "/usr/bin/microsoft-edge"
70
+ );
71
+ }
72
+
73
+ for (const p of candidates) {
74
+ if (fs.existsSync(p)) return p;
75
+ }
76
+ return null;
77
+ }
78
+
79
+ public parseHtml(rawHtml: string): { title: string; elements: DOMElement[]; textContent: string } {
80
+ let clean = rawHtml
81
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")
82
+ .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, "")
83
+ .replace(/<noscript\b[^<]*(?:(?!<\/noscript>)<[^<]*)*<\/noscript>/gi, "")
84
+ .replace(/<svg\b[^<]*(?:(?!<\/svg>)<[^<]*)*<\/svg>/gi, "");
85
+
86
+ const titleMatch = /<title[^>]*>([^<]*)<\/title>/i.exec(clean);
87
+ const title = titleMatch ? titleMatch[1].trim() : "";
88
+
89
+ const elements: DOMElement[] = [];
90
+ let elemIdx = 1;
91
+
92
+ const inputRegex = /<input\b([^>]*)>/gi;
93
+ let inputMatch: RegExpExecArray | null;
94
+ while ((inputMatch = inputRegex.exec(clean)) !== null) {
95
+ const attrsStr = inputMatch[1];
96
+ const attrs = this.parseAttributes(attrsStr);
97
+ const type = (attrs.type || "text").toLowerCase();
98
+ const name = attrs.name || "";
99
+ const val = attrs.value || "";
100
+ const placeholder = attrs.placeholder || "";
101
+ const role = `input[${type}]`;
102
+ const desc = placeholder || name || val || role;
103
+
104
+ elements.push({
105
+ index: elemIdx++,
106
+ tag: "input",
107
+ text: desc,
108
+ role,
109
+ name,
110
+ value: val,
111
+ attributes: attrs
112
+ });
113
+ }
114
+
115
+ const tagRegex = /<(a|button|select|textarea)\b([^>]*)>([\s\S]*?)<\/\1>/gi;
116
+ let tagMatch: RegExpExecArray | null;
117
+ while ((tagMatch = tagRegex.exec(clean)) !== null) {
118
+ const tag = tagMatch[1].toLowerCase();
119
+ const attrsStr = tagMatch[2];
120
+ const inner = tagMatch[3].replace(/<[^>]+>/g, " ").trim();
121
+ const attrs = this.parseAttributes(attrsStr);
122
+ const role = tag === "a" ? "link" : tag;
123
+ const text = inner || attrs["aria-label"] || attrs["title"] || role;
124
+
125
+ elements.push({
126
+ index: elemIdx++,
127
+ tag,
128
+ text,
129
+ role,
130
+ href: attrs.href,
131
+ name: attrs.name,
132
+ attributes: attrs
133
+ });
134
+ }
135
+
136
+ const plainText = clean
137
+ .replace(/<[^>]+>/g, " ")
138
+ .replace(/&nbsp;/g, " ")
139
+ .replace(/&amp;/g, "&")
140
+ .replace(/&lt;/g, "<")
141
+ .replace(/&gt;/g, ">")
142
+ .replace(/\s+/g, " ")
143
+ .trim();
144
+
145
+ return { title, elements, textContent: plainText };
146
+ }
147
+
148
+ private parseAttributes(attrStr: string): Record<string, string> {
149
+ const attrs: Record<string, string> = {};
150
+ const regex = /([a-zA-Z0-9_-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
151
+ let match: RegExpExecArray | null;
152
+ while ((match = regex.exec(attrStr)) !== null) {
153
+ const key = match[1].toLowerCase();
154
+ const val = match[2] ?? match[3] ?? match[4] ?? "";
155
+ attrs[key] = val;
156
+ }
157
+ return attrs;
158
+ }
159
+
160
+ public async navigate(url: string): Promise<string> {
161
+ let target = url.trim();
162
+ if (!target.startsWith("http://") && !target.startsWith("https://")) {
163
+ target = "https://" + target;
164
+ }
165
+
166
+ const controller = new AbortController();
167
+ const timer = setTimeout(() => controller.abort(), 20000);
168
+
169
+ try {
170
+ const res = await fetch(target, {
171
+ headers: {
172
+ "User-Agent": this.userAgent,
173
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8"
174
+ },
175
+ signal: controller.signal
176
+ });
177
+ clearTimeout(timer);
178
+
179
+ this.state.statusCode = res.status;
180
+ this.state.url = res.url || target;
181
+ this.state.rawHtml = await res.text();
182
+ this.state.history.push(this.state.url);
183
+ this.state.formInputs = {};
184
+
185
+ const parsed = this.parseHtml(this.state.rawHtml);
186
+ this.state.title = parsed.title || this.state.url;
187
+ this.state.elements = parsed.elements;
188
+ this.state.textContent = parsed.textContent;
189
+
190
+ return this.renderView();
191
+ } catch (err: any) {
192
+ clearTimeout(timer);
193
+ return `Navigation failed for ${target}: ${err.message}`;
194
+ }
195
+ }
196
+
197
+ public async click(target: string): Promise<string> {
198
+ if (this.state.elements.length === 0) {
199
+ return "No interactive elements on the current page. Please navigate first.";
200
+ }
201
+
202
+ const cleanTarget = target.trim().toLowerCase();
203
+ let matched: DOMElement | undefined;
204
+
205
+ if (cleanTarget.startsWith("[") && cleanTarget.endsWith("]")) {
206
+ const idx = parseInt(cleanTarget.slice(1, -1), 10);
207
+ matched = this.state.elements.find(e => e.index === idx);
208
+ } else {
209
+ const idx = parseInt(cleanTarget, 10);
210
+ if (!isNaN(idx)) {
211
+ matched = this.state.elements.find(e => e.index === idx);
212
+ }
213
+ }
214
+
215
+ if (!matched) {
216
+ matched = this.state.elements.find(e =>
217
+ e.text.toLowerCase().includes(cleanTarget) ||
218
+ (e.name && e.name.toLowerCase().includes(cleanTarget))
219
+ );
220
+ }
221
+
222
+ if (!matched) {
223
+ const available = this.state.elements.slice(0, 10).map(e => `[${e.index}] ${e.role}: ${e.text.slice(0, 25)}`).join(", ");
224
+ return `Element '${target}' not found. Available elements: ${available}`;
225
+ }
226
+
227
+ if (matched.href) {
228
+ const resolved = new URL(matched.href, this.state.url).toString();
229
+ return await this.navigate(resolved);
230
+ }
231
+
232
+ if (matched.tag === "button" || (matched.tag === "input" && ["submit", "button"].includes(matched.attributes.type || ""))) {
233
+ if (Object.keys(this.state.formInputs).length > 0) {
234
+ const params = new URLSearchParams(this.state.formInputs);
235
+ const controller = new AbortController();
236
+ const timer = setTimeout(() => controller.abort(), 20000);
237
+
238
+ try {
239
+ const res = await fetch(this.state.url, {
240
+ method: "POST",
241
+ headers: {
242
+ "User-Agent": this.userAgent,
243
+ "Content-Type": "application/x-www-form-urlencoded"
244
+ },
245
+ body: params.toString(),
246
+ signal: controller.signal
247
+ });
248
+ clearTimeout(timer);
249
+
250
+ this.state.statusCode = res.status;
251
+ this.state.url = res.url || this.state.url;
252
+ this.state.rawHtml = await res.text();
253
+ const parsed = this.parseHtml(this.state.rawHtml);
254
+ this.state.title = parsed.title || this.state.url;
255
+ this.state.elements = parsed.elements;
256
+ this.state.textContent = parsed.textContent;
257
+
258
+ return `Form submitted with payload ${JSON.stringify(this.state.formInputs)}.\n\n` + this.renderView();
259
+ } catch (err: any) {
260
+ clearTimeout(timer);
261
+ return `Form submission failed: ${err.message}`;
262
+ }
263
+ }
264
+ return `Clicked [${matched.index}] ${matched.role}: ${matched.text}`;
265
+ }
266
+
267
+ return `Clicked [${matched.index}] ${matched.role}: ${matched.text}`;
268
+ }
269
+
270
+ public fill(target: string, text: string, submit = false): Promise<string> {
271
+ const cleanTarget = target.trim().toLowerCase();
272
+ let matched: DOMElement | undefined;
273
+
274
+ if (cleanTarget.startsWith("[") && cleanTarget.endsWith("]")) {
275
+ const idx = parseInt(cleanTarget.slice(1, -1), 10);
276
+ matched = this.state.elements.find(e => e.index === idx);
277
+ } else {
278
+ const idx = parseInt(cleanTarget, 10);
279
+ if (!isNaN(idx)) {
280
+ matched = this.state.elements.find(e => e.index === idx);
281
+ }
282
+ }
283
+
284
+ if (!matched) {
285
+ matched = this.state.elements.find(e =>
286
+ ["input", "textarea"].includes(e.tag) && (
287
+ e.text.toLowerCase().includes(cleanTarget) ||
288
+ (e.name && e.name.toLowerCase().includes(cleanTarget)) ||
289
+ (e.attributes.placeholder && e.attributes.placeholder.toLowerCase().includes(cleanTarget))
290
+ )
291
+ );
292
+ }
293
+
294
+ const fieldName = (matched && matched.name) ? matched.name : (cleanTarget || "field");
295
+ this.state.formInputs[fieldName] = text;
296
+
297
+ if (submit) {
298
+ return this.click("submit");
299
+ }
300
+
301
+ const desc = matched ? `[${matched.index}] ${matched.role}` : fieldName;
302
+ return Promise.resolve(`Filled ${desc} with value '${text}'.`);
303
+ }
304
+
305
+ public extract(query = ""): string {
306
+ if (!this.state.rawHtml) {
307
+ return "No webpage currently loaded. Use browser_navigate first.";
308
+ }
309
+
310
+ const lines: string[] = [
311
+ `Page Title: ${this.state.title}`,
312
+ `Page URL: ${this.state.url}`,
313
+ `Status Code: ${this.state.statusCode}`,
314
+ ""
315
+ ];
316
+
317
+ if (query.trim()) {
318
+ const qLower = query.toLowerCase();
319
+ const matched = this.state.textContent
320
+ .split(/(?<=\.|\n)/)
321
+ .map(s => s.trim())
322
+ .filter(s => s.toLowerCase().includes(qLower));
323
+
324
+ if (matched.length > 0) {
325
+ lines.push(`Content matching '${query}':`);
326
+ lines.push(...matched.slice(0, 25));
327
+ } else {
328
+ lines.push(`No exact matches for '${query}'. Showing preview:`);
329
+ lines.push(this.state.textContent.slice(0, 2000));
330
+ }
331
+ } else {
332
+ lines.push("Page Content:");
333
+ lines.push(this.state.textContent.slice(0, 3000));
334
+ }
335
+
336
+ return lines.join("\n");
337
+ }
338
+
339
+ public screenshot(): string {
340
+ const lines: string[] = [
341
+ "+----------------------------------------------------------------+",
342
+ `| HEADLESS BROWSER SNAPSHOT: ${this.state.title.slice(0, 35).padEnd(35)} |`,
343
+ `| URL: ${this.state.url.slice(0, 56).padEnd(56)} |`,
344
+ `| Status: ${String(this.state.statusCode).padEnd(53)} |`,
345
+ "+----------------------------------------------------------------+"
346
+ ];
347
+
348
+ for (const el of this.state.elements.slice(0, 15)) {
349
+ const text = el.text.slice(0, 40).padEnd(40);
350
+ const role = el.role.slice(0, 14).padEnd(14);
351
+ lines.push(`| [${String(el.index).padStart(2, "0")}] ${role} | ${text} |`);
352
+ }
353
+
354
+ lines.push("+----------------------------------------------------------------+");
355
+ return lines.join("\n");
356
+ }
357
+
358
+ public renderView(): string {
359
+ const out: string[] = [
360
+ `Page Title: ${this.state.title}`,
361
+ `Current URL: ${this.state.url}`,
362
+ `Status Code: ${this.state.statusCode}`,
363
+ "",
364
+ "Interactive Elements:"
365
+ ];
366
+
367
+ if (this.state.elements.length === 0) {
368
+ out.push("(No interactive elements found)");
369
+ } else {
370
+ for (const el of this.state.elements.slice(0, 25)) {
371
+ const extra = el.href ? ` -> ${el.href}` : "";
372
+ out.push(`[${el.index}] ${el.role}: ${el.text}${extra}`);
373
+ }
374
+ }
375
+
376
+ out.push("");
377
+ out.push("Page Content Preview:");
378
+ out.push(this.state.textContent.slice(0, 1500) || "(Empty content)");
379
+ return out.join("\n");
380
+ }
381
+
382
+ public close(): string {
383
+ const u = this.state.url;
384
+ this.state = {
385
+ url: "about:blank",
386
+ title: "",
387
+ statusCode: 200,
388
+ elements: [],
389
+ textContent: "",
390
+ rawHtml: "",
391
+ formInputs: {},
392
+ history: []
393
+ };
394
+ return `Headless browser session closed. Cleared session for ${u}.`;
395
+ }
396
+ }
397
+
398
+ export const defaultBrowser = new HeadlessBrowserController();
399
+
400
+ export const browserNavigateTool: Tool = {
401
+ definition: {
402
+ name: "browser_navigate",
403
+ description: "Navigate the autonomous background headless browser to a target URL. Returns page title, status, and numbered interactive controls.",
404
+ parameters: {
405
+ type: "object",
406
+ properties: {
407
+ url: { type: "string", description: "Target URL to visit (e.g. https://example.com)." }
408
+ },
409
+ required: ["url"]
410
+ }
411
+ },
412
+ async execute(params: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
413
+ try {
414
+ const result = await defaultBrowser.navigate(params.url);
415
+ return { success: true, output: result };
416
+ } catch (err: any) {
417
+ return { success: false, output: "", error: `Navigation error: ${err.message}` };
418
+ }
419
+ }
420
+ };
421
+
422
+ export const browserClickTool: Tool = {
423
+ definition: {
424
+ name: "browser_click",
425
+ description: "Click an interactive element (link, button, tab) in the headless browser by its index (e.g. '[1]') or text label.",
426
+ parameters: {
427
+ type: "object",
428
+ properties: {
429
+ target: { type: "string", description: "Element index (e.g. '[3]' or '3') or text label to click." }
430
+ },
431
+ required: ["target"]
432
+ }
433
+ },
434
+ async execute(params: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
435
+ try {
436
+ const result = await defaultBrowser.click(params.target);
437
+ return { success: true, output: result };
438
+ } catch (err: any) {
439
+ return { success: false, output: "", error: `Click error: ${err.message}` };
440
+ }
441
+ }
442
+ };
443
+
444
+ export const browserTypeTool: Tool = {
445
+ definition: {
446
+ name: "browser_type",
447
+ description: "Fill text into an input field or textarea identified by its index (e.g. '[2]') or name/placeholder, with optional form submission.",
448
+ parameters: {
449
+ type: "object",
450
+ properties: {
451
+ target: { type: "string", description: "Element index (e.g. '[2]') or input name/placeholder." },
452
+ text: { type: "string", description: "Text string to fill into the input field." },
453
+ submit: { type: "boolean", description: "Optional boolean flag to automatically submit the form after typing." }
454
+ },
455
+ required: ["target", "text"]
456
+ }
457
+ },
458
+ async execute(params: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
459
+ try {
460
+ const result = await defaultBrowser.fill(params.target, params.text, Boolean(params.submit));
461
+ return { success: true, output: result };
462
+ } catch (err: any) {
463
+ return { success: false, output: "", error: `Type error: ${err.message}` };
464
+ }
465
+ }
466
+ };
467
+
468
+ export const browserExtractTool: Tool = {
469
+ definition: {
470
+ name: "browser_extract",
471
+ description: "Extract text content or search for specific keywords from the currently loaded page in the headless browser.",
472
+ parameters: {
473
+ type: "object",
474
+ properties: {
475
+ query: { type: "string", description: "Optional search query or term to filter extracted content." }
476
+ },
477
+ required: []
478
+ }
479
+ },
480
+ async execute(params: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
481
+ try {
482
+ const result = defaultBrowser.extract(params.query || "");
483
+ return { success: true, output: result };
484
+ } catch (err: any) {
485
+ return { success: false, output: "", error: `Extract error: ${err.message}` };
486
+ }
487
+ }
488
+ };
489
+
490
+ export const browserScreenshotTool: Tool = {
491
+ definition: {
492
+ name: "browser_screenshot",
493
+ description: "Capture a structured viewport snapshot of the current headless browser state including title, URL, status code, and interactive elements.",
494
+ parameters: {
495
+ type: "object",
496
+ properties: {},
497
+ required: []
498
+ }
499
+ },
500
+ async execute(params: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
501
+ try {
502
+ const result = defaultBrowser.screenshot();
503
+ return { success: true, output: result };
504
+ } catch (err: any) {
505
+ return { success: false, output: "", error: `Screenshot error: ${err.message}` };
506
+ }
507
+ }
508
+ };
509
+
510
+ export const browserCloseTool: Tool = {
511
+ definition: {
512
+ name: "browser_close",
513
+ description: "Close the active headless browser session and reset browsing history.",
514
+ parameters: {
515
+ type: "object",
516
+ properties: {},
517
+ required: []
518
+ }
519
+ },
520
+ async execute(params: Record<string, any>, context: ToolExecutionContext): Promise<ToolResult> {
521
+ try {
522
+ const result = defaultBrowser.close();
523
+ return { success: true, output: result };
524
+ } catch (err: any) {
525
+ return { success: false, output: "", error: `Close error: ${err.message}` };
526
+ }
527
+ }
528
+ };
@@ -0,0 +1,143 @@
1
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
2
+ import { resolve, dirname, relative } from "node:path";
3
+ import pc from "picocolors";
4
+ import { formatUnifiedDiff } from "../ui/diff.js";
5
+ import type { Tool, ToolExecutionContext, ToolResult } from "./types.js";
6
+
7
+ export const readFileTool: Tool = {
8
+ definition: {
9
+ name: "read_file",
10
+ description: "Read the contents of a text file from disk. Can read entire file or specific line ranges.",
11
+ parameters: {
12
+ type: "object",
13
+ properties: {
14
+ path: { type: "string", description: "Absolute path or path relative to current workspace directory." },
15
+ startLine: { type: "number", description: "Optional 1-based start line number." },
16
+ endLine: { type: "number", description: "Optional 1-based end line number." }
17
+ },
18
+ required: ["path"]
19
+ }
20
+ },
21
+ async execute(params, context): Promise<ToolResult> {
22
+ try {
23
+ const fullPath = resolve(context.workingDirectory, params.path);
24
+ if (!existsSync(fullPath)) {
25
+ return { success: false, output: "", error: `File not found: ${params.path}` };
26
+ }
27
+ const raw = readFileSync(fullPath, "utf8");
28
+ const lines = raw.split("\n");
29
+
30
+ let start = 1;
31
+ let end = lines.length;
32
+
33
+ if (params.startLine && typeof params.startLine === "number") {
34
+ start = Math.max(1, params.startLine);
35
+ }
36
+ if (params.endLine && typeof params.endLine === "number") {
37
+ end = Math.min(lines.length, params.endLine);
38
+ }
39
+
40
+ const selected = lines.slice(start - 1, end);
41
+ const formatted = selected.map((line, idx) => `${start + idx}: ${line}`).join("\n");
42
+ return {
43
+ success: true,
44
+ output: `File: ${relative(context.workingDirectory, fullPath)} (Lines ${start}-${end} of ${lines.length})\n\n${formatted}`
45
+ };
46
+ } catch (err: any) {
47
+ return { success: false, output: "", error: err.message };
48
+ }
49
+ }
50
+ };
51
+
52
+ export const writeFileTool: Tool = {
53
+ definition: {
54
+ name: "write_file",
55
+ description: "Write content to a file, completely creating or overwriting it. Parent directories are created automatically.",
56
+ parameters: {
57
+ type: "object",
58
+ properties: {
59
+ path: { type: "string", description: "Path to write the file to." },
60
+ content: { type: "string", description: "The full content to write to the file." }
61
+ },
62
+ required: ["path", "content"]
63
+ }
64
+ },
65
+ async execute(params, context): Promise<ToolResult> {
66
+ try {
67
+ const fullPath = resolve(context.workingDirectory, params.path);
68
+ const relPath = relative(context.workingDirectory, fullPath);
69
+ const parentDir = dirname(fullPath);
70
+
71
+ if (!existsSync(parentDir)) {
72
+ mkdirSync(parentDir, { recursive: true });
73
+ }
74
+
75
+ const oldContent = existsSync(fullPath) ? readFileSync(fullPath, "utf8") : "";
76
+
77
+ if (!context.autoApproveWrite) {
78
+ console.log(`\n${pc.cyan("[WRITE]")} ${pc.bold(relPath)}`);
79
+ const diff = formatUnifiedDiff(relPath, oldContent, params.content);
80
+ console.log(diff || pc.dim("(New file created)"));
81
+ }
82
+
83
+ writeFileSync(fullPath, params.content, "utf8");
84
+ return {
85
+ success: true,
86
+ output: `Successfully wrote ${Buffer.byteLength(params.content, "utf8")} bytes to ${relPath}`
87
+ };
88
+ } catch (err: any) {
89
+ return { success: false, output: "", error: err.message };
90
+ }
91
+ }
92
+ };
93
+
94
+ export const editFileTool: Tool = {
95
+ definition: {
96
+ name: "edit_file",
97
+ description: "Replace exact target string with replacement content in an existing file. Target must match existing text uniquely.",
98
+ parameters: {
99
+ type: "object",
100
+ properties: {
101
+ path: { type: "string", description: "Path to the file to edit." },
102
+ target: { type: "string", description: "The exact text to replace." },
103
+ replacement: { type: "string", description: "The replacement text." }
104
+ },
105
+ required: ["path", "target", "replacement"]
106
+ }
107
+ },
108
+ async execute(params, context): Promise<ToolResult> {
109
+ try {
110
+ const fullPath = resolve(context.workingDirectory, params.path);
111
+ const relPath = relative(context.workingDirectory, fullPath);
112
+
113
+ if (!existsSync(fullPath)) {
114
+ return { success: false, output: "", error: `File not found: ${relPath}` };
115
+ }
116
+
117
+ const content = readFileSync(fullPath, "utf8");
118
+ if (!content.includes(params.target)) {
119
+ return {
120
+ success: false,
121
+ output: "",
122
+ error: `Target string was not found in ${relPath}. Ensure exact whitespace and line match.`
123
+ };
124
+ }
125
+
126
+ const newContent = content.replace(params.target, params.replacement);
127
+
128
+ if (!context.autoApproveWrite) {
129
+ console.log(`\n${pc.cyan("[EDIT]")} ${pc.bold(relPath)}`);
130
+ const diff = formatUnifiedDiff(relPath, content, newContent);
131
+ console.log(diff);
132
+ }
133
+
134
+ writeFileSync(fullPath, newContent, "utf8");
135
+ return {
136
+ success: true,
137
+ output: `Successfully edited ${relPath}`
138
+ };
139
+ } catch (err: any) {
140
+ return { success: false, output: "", error: err.message };
141
+ }
142
+ }
143
+ };