@thegitai/cli 1.0.0-preview.8 → 1.0.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 (100) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +301 -15
  3. package/dist/bin/ai.js +142 -112
  4. package/dist/bin/browser-host.js +284 -0
  5. package/dist/src/agent-mode.js +33 -7
  6. package/dist/src/api/auth.js +8 -2
  7. package/dist/src/api/browser-login.js +147 -35
  8. package/dist/src/api/chat.js +703 -166
  9. package/dist/src/api/contracts.js +55 -1
  10. package/dist/src/api/default-host.js +1 -0
  11. package/dist/src/api/http.js +168 -8
  12. package/dist/src/api/models.js +47 -9
  13. package/dist/src/api/startup-handshake.js +36 -0
  14. package/dist/src/api/turn-recovery.js +189 -0
  15. package/dist/src/background-jobs.js +8 -2
  16. package/dist/src/browser/bridge.js +268 -0
  17. package/dist/src/browser/chrome-profiles.js +73 -0
  18. package/dist/src/browser/framing.js +42 -0
  19. package/dist/src/browser/native-host.js +219 -0
  20. package/dist/src/browser/protocol.js +46 -0
  21. package/dist/src/browser/session-bridge.js +130 -0
  22. package/dist/src/cli-args.js +19 -5
  23. package/dist/src/client-environment.js +2 -0
  24. package/dist/src/core/clipboard.js +8 -14
  25. package/dist/src/core/image-limits.js +56 -0
  26. package/dist/src/core/image-path-extractor.js +70 -3
  27. package/dist/src/core/session-image-store.js +246 -0
  28. package/dist/src/edit-journal.js +33 -2
  29. package/dist/src/executor.js +26 -4
  30. package/dist/src/help-text.js +152 -41
  31. package/dist/src/install-id.js +32 -0
  32. package/dist/src/job-follow-up.js +40 -0
  33. package/dist/src/mcp-client.js +335 -0
  34. package/dist/src/mcp-command.js +176 -0
  35. package/dist/src/mcp-config.js +123 -0
  36. package/dist/src/mcp-sdk.js +3 -0
  37. package/dist/src/mcp-types.js +26 -0
  38. package/dist/src/patcher.js +46 -4
  39. package/dist/src/permissions.js +301 -0
  40. package/dist/src/preferences.js +39 -0
  41. package/dist/src/project-key.js +11 -0
  42. package/dist/src/project-model-preferences.js +74 -0
  43. package/dist/src/quota-notice.js +62 -0
  44. package/dist/src/reasoning-effort.js +27 -0
  45. package/dist/src/session-safety.js +0 -12
  46. package/dist/src/session-store.js +123 -30
  47. package/dist/src/session.js +12 -4
  48. package/dist/src/signin.js +58 -0
  49. package/dist/src/skills/discovery.js +280 -0
  50. package/dist/src/skills/frontmatter.js +192 -0
  51. package/dist/src/skills/install.js +394 -0
  52. package/dist/src/skills/types.js +43 -0
  53. package/dist/src/skills-command.js +71 -0
  54. package/dist/src/tool-executor.js +41 -51
  55. package/dist/src/tools/browser.js +928 -0
  56. package/dist/src/tools/delete-file.js +21 -5
  57. package/dist/src/tools/index.js +34 -10
  58. package/dist/src/tools/patch-file.js +14 -29
  59. package/dist/src/tools/read-file.js +7 -1
  60. package/dist/src/tools/read-image-file.js +85 -0
  61. package/dist/src/tools/replace-document-text.js +28 -18
  62. package/dist/src/tools/restore-checkpoint.js +1 -2
  63. package/dist/src/tools/run-command.js +14 -71
  64. package/dist/src/tools/run-node-script.js +12 -81
  65. package/dist/src/tools/save-generated-image.js +120 -0
  66. package/dist/src/tools/shell-diagnostics.js +246 -72
  67. package/dist/src/tools/str-replace.js +14 -29
  68. package/dist/src/tools/undo-edit.js +2 -7
  69. package/dist/src/tools/use-skill.js +38 -0
  70. package/dist/src/tools/write-file.js +69 -14
  71. package/dist/src/ui/prompt-history-store.js +1 -1
  72. package/dist/src/ui/repl.js +1155 -301
  73. package/dist/src/ui/slash-commands.js +140 -0
  74. package/dist/src/ui/tui/attention.js +25 -0
  75. package/dist/src/ui/tui/bridge.js +38 -5
  76. package/dist/src/ui/tui/build-frame.js +903 -304
  77. package/dist/src/ui/tui/composer-layout.js +76 -0
  78. package/dist/src/ui/tui/desktop-notification.js +118 -0
  79. package/dist/src/ui/tui/markdown-render.js +21 -11
  80. package/dist/src/ui/tui/model-label.js +13 -0
  81. package/dist/src/ui/tui/shell-input.js +266 -61
  82. package/dist/src/ui/tui/shortcuts.js +61 -0
  83. package/dist/src/ui/tui/terminal-theme.js +28 -0
  84. package/dist/src/ui/tui/text.js +31 -6
  85. package/dist/src/ui/tui/user-input.js +593 -0
  86. package/dist/src/update-check.js +205 -0
  87. package/dist/src/usage-notice.js +52 -0
  88. package/dist/src/usage.js +25 -2
  89. package/dist/src/utils.js +13 -0
  90. package/dist/src/version.js +52 -2
  91. package/dist/vendor/mcp/LICENSES.txt +414 -0
  92. package/dist/vendor/mcp/client.cjs +82 -0
  93. package/package.json +22 -9
  94. package/dist/src/project-index.js +0 -233
  95. package/dist/src/tools/code-intel.js +0 -472
  96. package/dist/src/tools/find-symbol.js +0 -70
  97. package/dist/src/tools/hover-symbol.js +0 -95
  98. package/dist/src/tools/list-symbols.js +0 -55
  99. package/dist/src/tools/search-code.js +0 -37
  100. package/dist/src/tools/signature-help.js +0 -118
@@ -0,0 +1,928 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { normalizeProjectRelativePath } from '../artifact-policy.js';
4
+ import { BrowserBridgeError } from '../browser/bridge.js';
5
+ import { chromeProfileLabel } from '../browser/chrome-profiles.js';
6
+ import { isSupportedImageMimeType } from '../core/image-limits.js';
7
+ import { storeSessionImageBytes } from '../core/session-image-store.js';
8
+ import { browserAvailability, drainBrowserEvents, ensureBrowserBridge, resyncBrowserBridge, } from '../browser/session-bridge.js';
9
+ import { getClientStateDir } from '../client-state.js';
10
+ import { ensurePermission, originForUrl } from '../permissions.js';
11
+ const READ_TIMEOUT_MS = 20000;
12
+ const NAVIGATE_TIMEOUT_MS = 45000;
13
+ const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
14
+ const DISCOVERY_TIMEOUT_MS = 2500;
15
+ export const READ_ONLY_BROWSER_TOOLS = new Set([
16
+ 'browser',
17
+ 'browser_tabs',
18
+ 'browser_read_page',
19
+ 'browser_get_page_text',
20
+ 'browser_find',
21
+ 'browser_console',
22
+ 'browser_network',
23
+ 'browser_screenshot',
24
+ ]);
25
+ function missing(argument, tool) {
26
+ return {
27
+ ok: false,
28
+ error: `${argument} is required.`,
29
+ failureCategory: 'missing_required_argument',
30
+ failureDetails: {
31
+ category: 'missing_required_argument',
32
+ tool,
33
+ missing: [argument],
34
+ action: `Call ${tool} again with ${argument}.`,
35
+ },
36
+ };
37
+ }
38
+ async function waitForBrowser(options, timeoutMs) {
39
+ const deadline = Date.now() + timeoutMs;
40
+ const bridge = ensureBrowserBridge(options);
41
+ while (!bridge.status().connected && Date.now() < deadline) {
42
+ await new Promise((resolve) => setTimeout(resolve, 100));
43
+ }
44
+ return browserAvailability(options);
45
+ }
46
+ async function notConnected(context, { allowUnchosen = false, tabId } = {}) {
47
+ const options = { cwd: context.rootDir, env: context.env };
48
+ const status = ensureBrowserBridge(options).status();
49
+ if (!status.connected) {
50
+ if (status.everConnected)
51
+ resyncBrowserBridge(options);
52
+ const availability = await waitForBrowser(options, DISCOVERY_TIMEOUT_MS);
53
+ if (!availability.connected) {
54
+ return {
55
+ ok: false,
56
+ connected: false,
57
+ browserErrorCode: 'not_connected',
58
+ error: `TheGitAI is not connected to a browser. ${availability.hint ?? ''}`.trim(),
59
+ failureCategory: 'external_service',
60
+ };
61
+ }
62
+ }
63
+ return allowUnchosen ? { ok: true } : profileChosen(context, Number(tabId));
64
+ }
65
+ const resolvedProfileNames = new Map();
66
+ function profileLabel(profile) {
67
+ const unnamed = /^profile ([0-9a-f]{6})$/.exec(profile);
68
+ if (!unnamed)
69
+ return profile;
70
+ if (!resolvedProfileNames.has(unnamed[1])) {
71
+ resolvedProfileNames.set(unnamed[1], chromeProfileLabel(unnamed[1]) || profile);
72
+ }
73
+ return resolvedProfileNames.get(unnamed[1]);
74
+ }
75
+ function describeBrowsers(availability) {
76
+ const latest = Math.max(0, ...availability.browsers.map((browser) => browser.lastFocusedAt ?? 0));
77
+ return [...availability.browsers]
78
+ .sort((a, b) => (b.lastFocusedAt ?? 0) - (a.lastFocusedAt ?? 0))
79
+ .map((browser) => ({
80
+ key: browser.key,
81
+ name: `${browser.browser} - ${profileLabel(browser.profile)}`,
82
+ extensionVersion: browser.extensionVersion,
83
+ ...(latest > 0 && browser.lastFocusedAt === latest ? { lastUsed: true } : {}),
84
+ }));
85
+ }
86
+ const BROWSER_CHOICES_FILE = 'browser-choices.json';
87
+ const BROWSER_CHOICES_KEPT = 200;
88
+ const sessionProfiles = new Map();
89
+ function readBrowserChoices(env) {
90
+ try {
91
+ const parsed = JSON.parse(fs.readFileSync(path.join(getClientStateDir(env), BROWSER_CHOICES_FILE), 'utf8'));
92
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
93
+ }
94
+ catch {
95
+ return {};
96
+ }
97
+ }
98
+ function profileChoiceFor(context) {
99
+ const session = context.sessionId ?? '';
100
+ const remembered = sessionProfiles.get(session);
101
+ if (remembered)
102
+ return remembered;
103
+ const saved = session ? readBrowserChoices(context.env)[session] : undefined;
104
+ if (!saved?.key)
105
+ return null;
106
+ const choice = { key: String(saved.key), name: String(saved.name ?? saved.key), at: Number(saved.at) || 0 };
107
+ sessionProfiles.set(session, choice);
108
+ return choice;
109
+ }
110
+ function recordProfileChoice(context, browser) {
111
+ const session = context.sessionId ?? '';
112
+ const choice = { key: browser.key, name: browser.name, at: Date.now() };
113
+ sessionProfiles.set(session, choice);
114
+ if (!session)
115
+ return;
116
+ try {
117
+ const choices = readBrowserChoices(context.env);
118
+ choices[session] = choice;
119
+ const kept = Object.fromEntries(Object.entries(choices)
120
+ .sort(([, a], [, b]) => (b?.at ?? 0) - (a?.at ?? 0))
121
+ .slice(0, BROWSER_CHOICES_KEPT));
122
+ const dir = getClientStateDir(context.env);
123
+ fs.mkdirSync(dir, { recursive: true });
124
+ fs.writeFileSync(path.join(dir, BROWSER_CHOICES_FILE), JSON.stringify(kept), { mode: 0o600 });
125
+ }
126
+ catch {
127
+ }
128
+ }
129
+ async function askForProfile(context, listed, suggested) {
130
+ if (!context.requestUserInput)
131
+ return null;
132
+ const recommended = suggested ?? listed.find((browser) => browser.lastUsed) ?? listed[0];
133
+ const ordered = [recommended, ...listed.filter((browser) => browser.key !== recommended.key)];
134
+ const result = await context.requestUserInput({
135
+ questions: [
136
+ {
137
+ id: 'chrome_profile',
138
+ header: 'Chrome profile',
139
+ question: 'Which Chrome profile should TheGitAI use for this conversation?',
140
+ options: ordered.map((browser, index) => ({
141
+ id: `profile_${index}`,
142
+ label: browser.name,
143
+ description: browser.lastUsed ? 'The profile you used last' : 'Connected',
144
+ })),
145
+ multiSelect: false,
146
+ recommendedOptionId: 'profile_0',
147
+ },
148
+ ],
149
+ });
150
+ if (result?.status !== 'submitted')
151
+ return 'cancelled';
152
+ const answer = result.answers?.chrome_profile;
153
+ const option = /^profile_(\d+)$/.exec(answer?.selectedOptionIds?.[0] ?? '');
154
+ if (option && ordered[Number(option[1])])
155
+ return ordered[Number(option[1])];
156
+ const text = String(answer?.customText ?? '').trim();
157
+ return text ? { text } : 'cancelled';
158
+ }
159
+ async function useProfile(context, listed, suggested) {
160
+ const bridge = ensureBrowserBridge({ cwd: context.rootDir, env: context.env });
161
+ const choice = listed.length === 1 ? listed[0] : await askForProfile(context, listed, suggested);
162
+ if (choice === 'cancelled') {
163
+ return {
164
+ ok: false,
165
+ browserErrorCode: 'profile_question_cancelled',
166
+ error: 'The user closed the question about which Chrome profile to use, so nothing was done.',
167
+ failureCategory: 'user_declined',
168
+ browsers: listed,
169
+ };
170
+ }
171
+ if (choice && typeof choice === 'object' && 'text' in choice) {
172
+ return {
173
+ ok: false,
174
+ browserErrorCode: 'profile_answered_in_text',
175
+ error: `Asked which Chrome profile to use, the user answered in their own words instead of picking one: "${choice.text.slice(0, 300)}". Nothing was done.`,
176
+ failureCategory: 'user_declined',
177
+ browsers: listed,
178
+ };
179
+ }
180
+ const picked = choice ?? suggested;
181
+ if (!picked) {
182
+ return {
183
+ ok: false,
184
+ browserErrorCode: 'browser_not_chosen',
185
+ error: `${listed.length} Chrome profiles are connected and none has been chosen for this conversation.`,
186
+ failureCategory: 'invalid_argument',
187
+ browsers: listed,
188
+ };
189
+ }
190
+ recordProfileChoice(context, picked);
191
+ if (!bridge.selectBrowser(picked.key)) {
192
+ return {
193
+ ok: false,
194
+ browserErrorCode: 'chosen_profile_missing',
195
+ error: `The Chrome profile chosen for this conversation, ${picked.name}, is not connected.`,
196
+ failureCategory: 'external_service',
197
+ browsers: describeBrowsers(browserAvailability({ cwd: context.rootDir, env: context.env })),
198
+ };
199
+ }
200
+ return { ok: true };
201
+ }
202
+ async function profilesHoldingTab(context, listed, tabId) {
203
+ const bridge = ensureBrowserBridge({ cwd: context.rootDir, env: context.env });
204
+ const holders = await Promise.all(listed.map(async (browser) => {
205
+ try {
206
+ const result = await bridge.request('context', { includeAll: true }, { timeoutMs: READ_TIMEOUT_MS, browser: browser.key });
207
+ const tabs = Array.isArray(result?.tabs) ? result.tabs : [];
208
+ return tabs.some((tab) => Number(tab?.tabId) === tabId) ? browser : null;
209
+ }
210
+ catch {
211
+ return null;
212
+ }
213
+ }));
214
+ return holders.filter((browser) => browser !== null);
215
+ }
216
+ async function profileChosen(context, tabId = NaN) {
217
+ const options = { cwd: context.rootDir, env: context.env };
218
+ const listed = describeBrowsers(browserAvailability(options));
219
+ const choice = profileChoiceFor(context);
220
+ if (choice) {
221
+ if (ensureBrowserBridge(options).selectBrowser(choice.key))
222
+ return { ok: true };
223
+ return {
224
+ ok: false,
225
+ browserErrorCode: 'chosen_profile_missing',
226
+ error: `The Chrome profile chosen for this conversation, ${choice.name}, is not connected.`,
227
+ failureCategory: 'external_service',
228
+ browsers: listed,
229
+ };
230
+ }
231
+ if (!listed.length)
232
+ return { ok: true };
233
+ if (listed.length > 1 && Number.isInteger(tabId)) {
234
+ const holders = await profilesHoldingTab(context, listed, tabId);
235
+ if (holders.length === 1) {
236
+ ensureBrowserBridge(options).selectBrowser(holders[0].key);
237
+ recordProfileChoice(context, holders[0]);
238
+ return { ok: true };
239
+ }
240
+ }
241
+ return useProfile(context, listed);
242
+ }
243
+ function bridgeFailure(error) {
244
+ const code = error instanceof BrowserBridgeError ? error.code : 'browser_error';
245
+ const message = String(error?.message ?? error);
246
+ return {
247
+ ok: false,
248
+ error: message,
249
+ failureCategory: code === 'not_connected' ? 'external_service' : 'tool_exception',
250
+ browserErrorCode: code,
251
+ };
252
+ }
253
+ async function call(context, op, args = {}, timeoutMs = READ_TIMEOUT_MS) {
254
+ const bridge = ensureBrowserBridge({ cwd: context.rootDir, env: context.env });
255
+ return bridge.request(op, args, { timeoutMs, browser: profileChoiceFor(context)?.key });
256
+ }
257
+ async function currentTab(context, tabId) {
258
+ const result = await call(context, 'context', { includeAll: true });
259
+ const tabs = Array.isArray(result?.tabs) ? result.tabs : [];
260
+ const tab = tabs.find((entry) => Number(entry.tabId) === tabId);
261
+ if (!tab)
262
+ return null;
263
+ return { ...tab, url: String(tab.url ?? '').replace(/…+$/, '') };
264
+ }
265
+ async function ensureSiteAllowed(context, { url, tool, summary, }) {
266
+ const origin = originForUrl(String(url ?? ''));
267
+ if (!origin) {
268
+ return null;
269
+ }
270
+ return ensurePermission({
271
+ autoYes: context.autoYes,
272
+ grants: context.grants,
273
+ requestPermission: context.requestPermission,
274
+ }, {
275
+ bucket: 'browse',
276
+ origin,
277
+ title: `TheGitAI wants to use ${origin}`,
278
+ body: summary,
279
+ }, tool);
280
+ }
281
+ function attachEvents(result) {
282
+ const events = drainBrowserEvents();
283
+ if (!events.length)
284
+ return result;
285
+ const notable = events.filter((entry) => entry.event === 'detached' || entry.event === 'stopped' || entry.event === 'group_removed');
286
+ if (!notable.length)
287
+ return result;
288
+ return {
289
+ ...result,
290
+ browserNotices: notable.map((entry) => String(entry.data?.message ?? `Browser ${entry.event}.`)),
291
+ };
292
+ }
293
+ export async function browserGateway(context, args = {}) {
294
+ const guard = await notConnected(context, { allowUnchosen: true });
295
+ if (guard.ok === false)
296
+ return guard;
297
+ const options = { cwd: context.rootDir, env: context.env };
298
+ const requested = String(args.browser ?? '').trim();
299
+ const listed = describeBrowsers(browserAvailability(options));
300
+ if (requested) {
301
+ const wanted = requested.toLowerCase();
302
+ const partial = listed.filter((browser) => browser.name.toLowerCase().includes(wanted));
303
+ const match = listed.find((browser) => browser.key === requested) ??
304
+ listed.find((browser) => browser.name.toLowerCase() === wanted) ??
305
+ listed.find((browser) => browser.name.toLowerCase().endsWith(`(${wanted})`)) ??
306
+ (partial.length === 1 ? partial[0] : undefined);
307
+ if (!match) {
308
+ return {
309
+ ok: false,
310
+ error: partial.length > 1
311
+ ? `"${requested}" matches more than one connected browser. Use a key from browsers.`
312
+ : `No connected browser matches "${requested}". Use a key from browsers.`,
313
+ failureCategory: 'invalid_argument',
314
+ browsers: listed,
315
+ };
316
+ }
317
+ if (profileChoiceFor(context)?.key !== match.key) {
318
+ const chosen = await useProfile(context, listed, match);
319
+ if (chosen.ok === false)
320
+ return chosen;
321
+ }
322
+ }
323
+ else if (listed.length === 1 && !profileChoiceFor(context)) {
324
+ await useProfile(context, listed);
325
+ }
326
+ const availability = browserAvailability(options);
327
+ const platform = availability.browsers[0]?.platform ?? process.platform;
328
+ const choice = profileChoiceFor(context);
329
+ const connectedChoice = choice && availability.browsers.some((browser) => browser.key === choice.key) ? choice : null;
330
+ return {
331
+ ok: true,
332
+ connected: true,
333
+ browsers: describeBrowsers(availability),
334
+ selected: connectedChoice?.key ?? null,
335
+ choiceNeeded: !connectedChoice,
336
+ shortcutModifier: platform === 'darwin' ? 'cmd' : 'ctrl',
337
+ platform,
338
+ };
339
+ }
340
+ export async function browserTabs(context, args) {
341
+ const includeAll = args.include_all === true || args.includeAll === true;
342
+ const guard = await notConnected(context, { allowUnchosen: includeAll });
343
+ if (guard.ok === false)
344
+ return guard;
345
+ const options = { cwd: context.rootDir, env: context.env };
346
+ const availability = browserAvailability(options);
347
+ if (includeAll && availability.browsers.length > 1) {
348
+ const bridge = ensureBrowserBridge(options);
349
+ const profiles = await Promise.all(describeBrowsers(availability).map(async (browser) => {
350
+ try {
351
+ const result = await bridge.request('context', { includeAll: true }, { timeoutMs: READ_TIMEOUT_MS, browser: browser.key });
352
+ return { ...browser, selected: browser.key === profileChoiceFor(context)?.key, ...result };
353
+ }
354
+ catch (error) {
355
+ return { ...browser, selected: browser.key === profileChoiceFor(context)?.key, error: String(error?.message ?? error) };
356
+ }
357
+ }));
358
+ const choice = profileChoiceFor(context);
359
+ return attachEvents({
360
+ ok: true,
361
+ choiceNeeded: !choice || !availability.browsers.some((browser) => browser.key === choice.key),
362
+ profiles,
363
+ });
364
+ }
365
+ try {
366
+ const result = await call(context, 'context', { includeAll });
367
+ return attachEvents({ ok: true, ...result });
368
+ }
369
+ catch (error) {
370
+ return bridgeFailure(error);
371
+ }
372
+ }
373
+ export async function browserTabNew(context, args = {}) {
374
+ const guard = await notConnected(context);
375
+ if (guard.ok === false)
376
+ return guard;
377
+ const url = String(args.url ?? '').trim();
378
+ try {
379
+ if (url) {
380
+ const denied = await ensureSiteAllowed(context, {
381
+ url,
382
+ tool: 'browser_tab_new',
383
+ summary: `Open ${url} in a new tab in TheGitAI's tab group.`,
384
+ });
385
+ if (denied)
386
+ return denied;
387
+ }
388
+ const created = await call(context, 'tab.create', {});
389
+ if (!url)
390
+ return attachEvents({ ok: true, ...created });
391
+ const result = await call(context, 'navigate', { tabId: Number(created.tabId), url }, NAVIGATE_TIMEOUT_MS);
392
+ return attachEvents({ ok: true, ...result });
393
+ }
394
+ catch (error) {
395
+ return bridgeFailure(error);
396
+ }
397
+ }
398
+ export async function browserTabClose(context, args) {
399
+ const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
400
+ if (guard.ok === false)
401
+ return guard;
402
+ const tabId = Number(args.tabId ?? args.tab_id);
403
+ if (!Number.isInteger(tabId))
404
+ return missing('tabId', 'browser_tab_close');
405
+ try {
406
+ const result = await call(context, 'tab.close', { tabId });
407
+ return attachEvents({ ok: true, ...result });
408
+ }
409
+ catch (error) {
410
+ return bridgeFailure(error);
411
+ }
412
+ }
413
+ export async function browserNavigate(context, args) {
414
+ const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
415
+ if (guard.ok === false)
416
+ return guard;
417
+ const url = String(args.url ?? '').trim();
418
+ if (!url)
419
+ return missing('url', 'browser_navigate');
420
+ let tabId = Number(args.tabId ?? args.tab_id);
421
+ try {
422
+ if (url !== 'back' && url !== 'forward') {
423
+ const denied = await ensureSiteAllowed(context, {
424
+ url,
425
+ tool: 'browser_navigate',
426
+ summary: `Open ${url} in TheGitAI's tab group.`,
427
+ });
428
+ if (denied)
429
+ return denied;
430
+ }
431
+ if (!Number.isInteger(tabId)) {
432
+ const context_ = await call(context, 'context');
433
+ tabId = Number(context_?.tabs?.find((tab) => tab.inSession && tab.available)?.tabId);
434
+ if (!Number.isInteger(tabId)) {
435
+ const created = await call(context, 'tab.create', {});
436
+ tabId = Number(created.tabId);
437
+ }
438
+ }
439
+ const result = await call(context, 'navigate', { tabId, url }, NAVIGATE_TIMEOUT_MS);
440
+ return attachEvents({ ok: true, ...result });
441
+ }
442
+ catch (error) {
443
+ return bridgeFailure(error);
444
+ }
445
+ }
446
+ async function gatedTabCall(context, { tool, op, args, summary, timeoutMs = READ_TIMEOUT_MS, }) {
447
+ const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
448
+ if (guard.ok === false)
449
+ return guard;
450
+ const tabId = Number(args.tabId ?? args.tab_id);
451
+ if (!Number.isInteger(tabId))
452
+ return missing('tabId', tool);
453
+ try {
454
+ const tab = await currentTab(context, tabId);
455
+ if (!tab) {
456
+ return {
457
+ ok: false,
458
+ error: `Tab ${tabId} is no longer available. Call browser_tabs for the current list.`,
459
+ failureCategory: 'not_found',
460
+ failureDetails: {
461
+ category: 'not_found',
462
+ tool,
463
+ action: 'List the session tabs and use an id from that list.',
464
+ },
465
+ };
466
+ }
467
+ const denied = await ensureSiteAllowed(context, {
468
+ url: tab.url,
469
+ tool,
470
+ summary: summary(tab.url),
471
+ });
472
+ if (denied)
473
+ return denied;
474
+ const result = await call(context, op, {
475
+ ...args, tabId, expectedOrigin: new URL(tab.url || 'about:blank').origin,
476
+ }, timeoutMs);
477
+ return attachEvents({ ok: true, tabId, url: tab.url, ...result });
478
+ }
479
+ catch (error) {
480
+ return bridgeFailure(error);
481
+ }
482
+ }
483
+ export function browserReadPage(context, args) {
484
+ return gatedTabCall(context, {
485
+ tool: 'browser_read_page',
486
+ op: 'read_page',
487
+ args: {
488
+ tabId: args.tabId ?? args.tab_id,
489
+ filter: args.filter === 'interactive' ? 'interactive' : 'all',
490
+ depth: Number(args.depth ?? 15),
491
+ maxChars: Number(args.max_chars ?? args.maxChars ?? 50000),
492
+ },
493
+ summary: (url) => `Read the accessibility tree of ${url}.`,
494
+ });
495
+ }
496
+ export function browserGetPageText(context, args) {
497
+ return gatedTabCall(context, {
498
+ tool: 'browser_get_page_text',
499
+ op: 'page_text',
500
+ args: { tabId: args.tabId ?? args.tab_id },
501
+ summary: (url) => `Read the text of ${url}.`,
502
+ });
503
+ }
504
+ export function browserFind(context, args) {
505
+ const query = String(args.query ?? '').trim();
506
+ if (!query)
507
+ return Promise.resolve(missing('query', 'browser_find'));
508
+ return gatedTabCall(context, {
509
+ tool: 'browser_find',
510
+ op: 'find_candidates',
511
+ args: { tabId: args.tabId ?? args.tab_id },
512
+ summary: (url) => `Look for "${query}" on ${url}.`,
513
+ }).then((result) => (result.ok ? { ...result, query } : result));
514
+ }
515
+ export async function browserComputer(context, args) {
516
+ const action = String(args.action ?? '').trim();
517
+ if (!action)
518
+ return missing('action', 'browser_computer');
519
+ const result = await gatedTabCall(context, {
520
+ tool: 'browser_computer',
521
+ op: 'computer',
522
+ args: { ...args, tabId: args.tabId ?? args.tab_id, action },
523
+ summary: (url) => `${describeComputerAction(action, args)} on ${url}.`,
524
+ timeoutMs: action === 'wait' ? 30000 : READ_TIMEOUT_MS,
525
+ });
526
+ if (!result.ok || typeof result.base64Data !== 'string')
527
+ return result;
528
+ return reshapeScreenshot(context, result, args);
529
+ }
530
+ function reshapeScreenshot(context, result, args) {
531
+ const { base64Data, mimeType, geometry, ...rest } = result;
532
+ const imageMimeType = isSupportedImageMimeType(String(mimeType)) ? mimeType : 'image/png';
533
+ const payload = {
534
+ ...rest,
535
+ viewport: geometry,
536
+ coordinateSpace: geometry?.scale === 1 && !geometry?.offsetX && !geometry?.offsetY
537
+ ? 'Image pixels are viewport CSS pixels. Use coordinates directly.'
538
+ : 'Convert image pixels to viewport CSS coordinates: x = imageX / viewport.scale + viewport.offsetX; y = imageY / viewport.scale + viewport.offsetY.',
539
+ imageBytes: { base64Data, mimeType: imageMimeType },
540
+ };
541
+ const wantsFile = args.save_to_disk === true || args.saveToDisk === true;
542
+ const sessionId = context.sessionId;
543
+ if (sessionId) {
544
+ try {
545
+ const stored = storeSessionImageBytes({
546
+ sessionId,
547
+ base64Data,
548
+ mimeType: imageMimeType,
549
+ env: context.env,
550
+ });
551
+ if (wantsFile)
552
+ payload.savedPath = stored.cachePath;
553
+ payload.imageBytes.cachePath = stored.cachePath;
554
+ payload.imageBytes.index = stored.index;
555
+ }
556
+ catch (error) {
557
+ if (wantsFile)
558
+ payload.saveError = String(error?.message ?? error);
559
+ }
560
+ }
561
+ return payload;
562
+ }
563
+ function describeComputerAction(action, args) {
564
+ if (action === 'type')
565
+ return `Type ${JSON.stringify(String(args.text ?? '').slice(0, 60))}`;
566
+ if (action === 'key')
567
+ return `Press ${String(args.text ?? '')}`;
568
+ if (action === 'screenshot')
569
+ return 'Take a screenshot';
570
+ if (action === 'zoom')
571
+ return 'Take a close-up screenshot';
572
+ if (action === 'scroll')
573
+ return `Scroll ${String(args.scroll_direction ?? '')}`;
574
+ if (action === 'hover')
575
+ return 'Hover';
576
+ return `${action.replace(/_/g, ' ')}`;
577
+ }
578
+ export function browserFormInput(context, args) {
579
+ const ref = String(args.ref ?? '').trim();
580
+ if (!ref)
581
+ return Promise.resolve(missing('ref', 'browser_form_input'));
582
+ if (args.value === undefined) {
583
+ return Promise.resolve(missing('value', 'browser_form_input'));
584
+ }
585
+ return gatedTabCall(context, {
586
+ tool: 'browser_form_input',
587
+ op: 'form_input',
588
+ args: { tabId: args.tabId ?? args.tab_id, ref, value: args.value },
589
+ summary: (url) => `Set ${ref} on ${url}.`,
590
+ });
591
+ }
592
+ export function browserEvaluate(context, args) {
593
+ const text = String(args.text ?? args.code ?? '').trim();
594
+ if (!text)
595
+ return Promise.resolve(missing('text', 'browser_evaluate'));
596
+ return gatedTabCall(context, {
597
+ tool: 'browser_evaluate',
598
+ op: 'evaluate',
599
+ args: { tabId: args.tabId ?? args.tab_id, text },
600
+ summary: (url) => `Run JavaScript on ${url}.`,
601
+ });
602
+ }
603
+ export function browserConsole(context, args) {
604
+ return gatedTabCall(context, {
605
+ tool: 'browser_console',
606
+ op: 'console',
607
+ args: {
608
+ tabId: args.tabId ?? args.tab_id,
609
+ pattern: args.pattern,
610
+ onlyErrors: args.onlyErrors === true || args.only_errors === true,
611
+ limit: Number(args.limit ?? 100),
612
+ clear: args.clear === true,
613
+ },
614
+ summary: (url) => `Read console output from ${url}.`,
615
+ });
616
+ }
617
+ export function browserNetwork(context, args) {
618
+ return gatedTabCall(context, {
619
+ tool: 'browser_network',
620
+ op: 'network',
621
+ args: {
622
+ tabId: args.tabId ?? args.tab_id,
623
+ urlPattern: args.urlPattern ?? args.url_pattern,
624
+ limit: Number(args.limit ?? 100),
625
+ clear: args.clear === true,
626
+ },
627
+ summary: (url) => `Read network requests from ${url}.`,
628
+ });
629
+ }
630
+ export async function browserDownloads(context, args) {
631
+ const action = String(args.action ?? 'list').trim();
632
+ if (context.agentMode === 'plan' && action !== 'list') {
633
+ return {
634
+ ok: false,
635
+ failureCategory: 'policy_blocked',
636
+ error: `Plan mode blocked browser_downloads ${action}. Listing downloads is allowed; saving or cancelling one changes the user's disk. Switch to Default mode to decide on a download.`,
637
+ };
638
+ }
639
+ const guard = await notConnected(context);
640
+ if (guard.ok === false)
641
+ return guard;
642
+ if (action === 'list') {
643
+ const result = await call(context, 'downloads');
644
+ const downloads = Array.isArray(result?.downloads) ? result.downloads : [];
645
+ return {
646
+ ok: true,
647
+ downloads,
648
+ ...(downloads.length
649
+ ? {
650
+ instructions: 'Each of these is paused and nothing is on disk yet. Tell the user the filename, the size and the site it came from, and only call accept after they say yes.',
651
+ }
652
+ : {}),
653
+ };
654
+ }
655
+ if (action !== 'accept' && action !== 'cancel') {
656
+ return {
657
+ ok: false,
658
+ error: 'browser_downloads action must be "list", "accept" or "cancel".',
659
+ failureCategory: 'invalid_argument',
660
+ };
661
+ }
662
+ const downloadId = Number(args.downloadId ?? args.download_id);
663
+ if (!Number.isInteger(downloadId))
664
+ return missing('downloadId', 'browser_downloads');
665
+ if (action === 'accept') {
666
+ const listed = await call(context, 'downloads');
667
+ const record = (Array.isArray(listed?.downloads) ? listed.downloads : []).find((entry) => Number(entry?.downloadId) === downloadId);
668
+ const size = record?.bytes ? `${(record.bytes / (1024 * 1024)).toFixed(1)} MB` : 'unknown size';
669
+ if (!context.autoYes && context.requestPermission) {
670
+ const decision = await context.requestPermission({
671
+ bucket: 'browse',
672
+ title: 'TheGitAI wants to save a file to this machine',
673
+ body: `"${record?.filename ?? downloadId}" (${size}) from ${record?.url ?? 'an unknown source'}.`,
674
+ options: [
675
+ { label: 'Save this file', decision: { kind: 'once' } },
676
+ { label: 'No, cancel the download', decision: { kind: 'deny' } },
677
+ ],
678
+ });
679
+ if (decision?.kind !== 'once' && decision?.kind !== 'always-bucket') {
680
+ await call(context, 'download.decide', { downloadId, accept: false });
681
+ return {
682
+ ok: false,
683
+ error: 'The user declined the download. It was cancelled and nothing was saved.',
684
+ failureCategory: 'user_declined',
685
+ };
686
+ }
687
+ }
688
+ }
689
+ const result = await call(context, 'download.decide', {
690
+ downloadId,
691
+ accept: action === 'accept',
692
+ });
693
+ return { ok: true, ...result };
694
+ }
695
+ const RESTORE_MIN_EXTENSION_VERSION = [0, 1, 7];
696
+ export function extensionPredates(version, minimum) {
697
+ if (!version)
698
+ return false;
699
+ const parts = version.split('.').map((part) => Number.parseInt(part, 10) || 0);
700
+ for (let index = 0; index < minimum.length; index += 1) {
701
+ const have = parts[index] ?? 0;
702
+ if (have !== minimum[index])
703
+ return have < minimum[index];
704
+ }
705
+ return false;
706
+ }
707
+ function connectedExtensionVersion(context) {
708
+ const availability = browserAvailability({ cwd: context.rootDir, env: context.env });
709
+ const key = profileChoiceFor(context)?.key ?? availability.selected;
710
+ return availability.browsers.find((browser) => browser.key === key)?.extensionVersion;
711
+ }
712
+ export function browserResize(context, args) {
713
+ if (args.restore === true) {
714
+ const version = connectedExtensionVersion(context);
715
+ if (extensionPredates(version, RESTORE_MIN_EXTENSION_VERSION)) {
716
+ return Promise.resolve({
717
+ ok: false,
718
+ error: `Restoring the window needs the TheGitAI Chrome extension ${RESTORE_MIN_EXTENSION_VERSION.join('.')} or later; this browser has ${version}. Resize it back with the width and height it had before, and tell the user the extension has an update.`,
719
+ failureCategory: 'invalid_argument',
720
+ });
721
+ }
722
+ return gatedTabCall(context, {
723
+ tool: 'browser_resize',
724
+ op: 'resize',
725
+ args: { tabId: args.tabId ?? args.tab_id, restore: true },
726
+ summary: () => 'Put the browser window back to its size before resizing.',
727
+ });
728
+ }
729
+ const width = Number(args.width);
730
+ const height = Number(args.height);
731
+ if (!Number.isFinite(width) || !Number.isFinite(height)) {
732
+ return Promise.resolve(missing('width and height', 'browser_resize'));
733
+ }
734
+ return gatedTabCall(context, {
735
+ tool: 'browser_resize',
736
+ op: 'resize',
737
+ args: { tabId: args.tabId ?? args.tab_id, width, height },
738
+ summary: () => `Resize the browser window to ${width}x${height}.`,
739
+ }).then((result) => withResizeWarning(result, width, height));
740
+ }
741
+ const RESIZE_TOLERANCE_PX = 24;
742
+ export function withResizeWarning(result, width, height) {
743
+ const viewport = result.viewport;
744
+ if (result.ok === false || !viewport)
745
+ return result;
746
+ const actualWidth = Number(viewport.cssWidth);
747
+ const actualHeight = Number(viewport.cssHeight);
748
+ if (!Number.isFinite(actualWidth) || !Number.isFinite(actualHeight))
749
+ return result;
750
+ if (Math.abs(actualWidth - width) <= RESIZE_TOLERANCE_PX &&
751
+ Math.abs(actualHeight - height) <= RESIZE_TOLERANCE_PX) {
752
+ return result;
753
+ }
754
+ return {
755
+ ...result,
756
+ warning: `The page is ${Math.round(actualWidth)}x${Math.round(actualHeight)} CSS pixels, not the ${width}x${height} you asked for. ` +
757
+ 'The window may be maximized, tiled or full screen in a way this system does not let a program change, or the size may be outside what the screen and Chrome allow. ' +
758
+ 'Do not assume the layout changed. If the user needs this size, ask them to un-maximize the window; otherwise check the page at the size it has.',
759
+ };
760
+ }
761
+ export async function browserFileUpload(context, args) {
762
+ const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
763
+ if (guard.ok === false)
764
+ return guard;
765
+ const ref = String(args.ref ?? '').trim();
766
+ if (!ref)
767
+ return missing('ref', 'browser_file_upload');
768
+ const rawPaths = Array.isArray(args.paths)
769
+ ? args.paths
770
+ : args.path
771
+ ? [args.path]
772
+ : [];
773
+ if (!rawPaths.length)
774
+ return missing('paths', 'browser_file_upload');
775
+ const files = [];
776
+ let total = 0;
777
+ for (const raw of rawPaths) {
778
+ const candidate = String(raw ?? '').trim();
779
+ if (!candidate)
780
+ continue;
781
+ let resolved;
782
+ if (path.isAbsolute(candidate)) {
783
+ resolved = candidate;
784
+ }
785
+ else if (normalizeProjectRelativePath(context.rootDir, candidate)) {
786
+ resolved = path.resolve(context.rootDir, candidate);
787
+ }
788
+ else {
789
+ return {
790
+ ok: false,
791
+ error: `Refusing to upload a path outside the project root: ${candidate}`,
792
+ failureCategory: 'permission_denied',
793
+ };
794
+ }
795
+ let stat;
796
+ try {
797
+ stat = fs.statSync(resolved);
798
+ }
799
+ catch {
800
+ return {
801
+ ok: false,
802
+ error: `No such file: ${resolved}`,
803
+ failureCategory: 'not_found',
804
+ };
805
+ }
806
+ if (!stat.isFile()) {
807
+ return {
808
+ ok: false,
809
+ error: `Not a file: ${resolved}`,
810
+ failureCategory: 'invalid_argument',
811
+ };
812
+ }
813
+ total += stat.size;
814
+ if (total > MAX_UPLOAD_BYTES) {
815
+ return {
816
+ ok: false,
817
+ error: `Uploads are capped at ${MAX_UPLOAD_BYTES / (1024 * 1024)} MB in total; these files exceed it.`,
818
+ failureCategory: 'budget_exceeded',
819
+ };
820
+ }
821
+ files.push({
822
+ name: path.basename(resolved),
823
+ mimeType: guessMimeType(resolved),
824
+ base64: fs.readFileSync(resolved).toString('base64'),
825
+ });
826
+ }
827
+ const tabId = Number(args.tabId ?? args.tab_id);
828
+ if (!Number.isInteger(tabId))
829
+ return missing('tabId', 'browser_file_upload');
830
+ try {
831
+ const tab = await currentTab(context, tabId);
832
+ const denied = await ensureSiteAllowed(context, {
833
+ url: tab?.url,
834
+ tool: 'browser_file_upload',
835
+ summary: `Upload ${files.map((file) => file.name).join(', ')} to ${tab?.url ?? 'the page'}.`,
836
+ });
837
+ if (denied)
838
+ return denied;
839
+ const result = await call(context, 'upload', { tabId, ref, files }, NAVIGATE_TIMEOUT_MS);
840
+ return attachEvents({ ok: true, ...result, files: files.map((file) => file.name) });
841
+ }
842
+ catch (error) {
843
+ return bridgeFailure(error);
844
+ }
845
+ }
846
+ function guessMimeType(file) {
847
+ const extension = path.extname(file).toLowerCase();
848
+ const table = {
849
+ '.png': 'image/png',
850
+ '.jpg': 'image/jpeg',
851
+ '.jpeg': 'image/jpeg',
852
+ '.gif': 'image/gif',
853
+ '.webp': 'image/webp',
854
+ '.svg': 'image/svg+xml',
855
+ '.pdf': 'application/pdf',
856
+ '.json': 'application/json',
857
+ '.csv': 'text/csv',
858
+ '.txt': 'text/plain',
859
+ '.md': 'text/markdown',
860
+ '.html': 'text/html',
861
+ '.zip': 'application/zip',
862
+ };
863
+ return table[extension] ?? 'application/octet-stream';
864
+ }
865
+ const BATCH_TOOLS = {
866
+ browser_tabs: browserTabs,
867
+ browser_tab_new: (context) => browserTabNew(context),
868
+ browser_tab_close: browserTabClose,
869
+ browser_navigate: browserNavigate,
870
+ browser_read_page: browserReadPage,
871
+ browser_get_page_text: browserGetPageText,
872
+ browser_computer: browserComputer,
873
+ browser_form_input: browserFormInput,
874
+ browser_evaluate: browserEvaluate,
875
+ browser_console: browserConsole,
876
+ browser_network: browserNetwork,
877
+ browser_screenshot: (context, args) => browserComputer(context, { ...args, action: 'screenshot' }),
878
+ browser_resize: browserResize,
879
+ browser_file_upload: browserFileUpload,
880
+ browser_downloads: browserDownloads,
881
+ };
882
+ export async function browserBatch(context, args) {
883
+ const guard = await notConnected(context, { tabId: (Array.isArray(args.actions) ? args.actions[0]?.input?.tabId : undefined) });
884
+ if (guard.ok === false)
885
+ return guard;
886
+ const actions = Array.isArray(args.actions) ? args.actions : [];
887
+ if (!actions.length)
888
+ return missing('actions', 'browser_batch');
889
+ if (actions.length > 20) {
890
+ return {
891
+ ok: false,
892
+ error: 'A batch may hold at most 20 actions.',
893
+ failureCategory: 'invalid_argument',
894
+ };
895
+ }
896
+ const results = [];
897
+ for (const [index, entry] of actions.entries()) {
898
+ const name = String(entry?.name ?? '').trim();
899
+ const input = (entry?.input ?? {});
900
+ const handler = BATCH_TOOLS[name];
901
+ if (!handler) {
902
+ results.push({ step: index + 1, name, ok: false, error: `Unknown browser tool: ${name}` });
903
+ return { ok: false, stoppedAt: index + 1, results, error: `Unknown browser tool: ${name}` };
904
+ }
905
+ if (context.agentMode === 'plan' && !READ_ONLY_BROWSER_TOOLS.has(name)) {
906
+ results.push({ step: index + 1, name, ok: false, error: 'Plan mode blocks this action.' });
907
+ return {
908
+ ok: false,
909
+ stoppedAt: index + 1,
910
+ results,
911
+ error: `Plan mode allows only read-only browser actions; ${name} changes the page.`,
912
+ failureCategory: 'policy_blocked',
913
+ };
914
+ }
915
+ const result = await handler(context, input);
916
+ results.push({ step: index + 1, name, ...result });
917
+ if (result.ok === false) {
918
+ return {
919
+ ok: false,
920
+ stoppedAt: index + 1,
921
+ results,
922
+ error: `Batch stopped at step ${index + 1} (${name}): ${result.error ?? 'failed'}`,
923
+ failureCategory: result.failureCategory,
924
+ };
925
+ }
926
+ }
927
+ return { ok: true, results };
928
+ }