@thegitai/cli 1.0.0-preview.9 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +301 -15
- package/dist/bin/ai.js +139 -111
- package/dist/bin/browser-host.js +284 -0
- package/dist/src/agent-mode.js +33 -7
- package/dist/src/api/auth.js +8 -2
- package/dist/src/api/browser-login.js +77 -34
- package/dist/src/api/chat.js +702 -173
- package/dist/src/api/contracts.js +55 -1
- package/dist/src/api/default-host.js +1 -0
- package/dist/src/api/http.js +168 -8
- package/dist/src/api/models.js +75 -10
- package/dist/src/api/startup-handshake.js +36 -0
- package/dist/src/api/turn-recovery.js +189 -0
- package/dist/src/background-jobs.js +14 -4
- package/dist/src/browser/bridge.js +268 -0
- package/dist/src/browser/chrome-profiles.js +73 -0
- package/dist/src/browser/framing.js +42 -0
- package/dist/src/browser/native-host.js +219 -0
- package/dist/src/browser/protocol.js +46 -0
- package/dist/src/browser/session-bridge.js +130 -0
- package/dist/src/cli-args.js +19 -5
- package/dist/src/client-environment.js +2 -0
- package/dist/src/core/clipboard.js +8 -14
- package/dist/src/core/image-limits.js +56 -0
- package/dist/src/core/image-path-extractor.js +70 -3
- package/dist/src/core/session-image-store.js +271 -0
- package/dist/src/edit-journal.js +33 -2
- package/dist/src/executor.js +26 -4
- package/dist/src/help-text.js +152 -41
- package/dist/src/install-id.js +32 -0
- package/dist/src/job-follow-up.js +40 -0
- package/dist/src/mcp-client.js +335 -0
- package/dist/src/mcp-command.js +176 -0
- package/dist/src/mcp-config.js +123 -0
- package/dist/src/mcp-sdk.js +3 -0
- package/dist/src/mcp-types.js +26 -0
- package/dist/src/patcher.js +46 -4
- package/dist/src/permissions.js +301 -0
- package/dist/src/preferences.js +39 -0
- package/dist/src/project-key.js +11 -0
- package/dist/src/project-model-preferences.js +74 -0
- package/dist/src/quota-notice.js +62 -0
- package/dist/src/reasoning-effort.js +27 -0
- package/dist/src/scratch-dir.js +6 -2
- package/dist/src/session-context.js +11 -0
- package/dist/src/session-safety.js +0 -12
- package/dist/src/session-store.js +76 -10
- package/dist/src/session.js +14 -4
- package/dist/src/signin.js +58 -0
- package/dist/src/skills/discovery.js +280 -0
- package/dist/src/skills/frontmatter.js +192 -0
- package/dist/src/skills/install.js +394 -0
- package/dist/src/skills/types.js +43 -0
- package/dist/src/skills-command.js +71 -0
- package/dist/src/todo-list.js +16 -9
- package/dist/src/tool-executor.js +42 -51
- package/dist/src/tools/browser.js +928 -0
- package/dist/src/tools/delete-file.js +21 -5
- package/dist/src/tools/index.js +34 -10
- package/dist/src/tools/patch-file.js +14 -29
- package/dist/src/tools/read-file.js +7 -1
- package/dist/src/tools/read-image-file.js +85 -0
- package/dist/src/tools/replace-document-text.js +28 -18
- package/dist/src/tools/restore-checkpoint.js +1 -2
- package/dist/src/tools/run-command.js +14 -71
- package/dist/src/tools/run-node-script.js +13 -82
- package/dist/src/tools/save-generated-image.js +120 -0
- package/dist/src/tools/shell-diagnostics.js +248 -72
- package/dist/src/tools/str-replace.js +14 -29
- package/dist/src/tools/undo-edit.js +2 -7
- package/dist/src/tools/use-skill.js +38 -0
- package/dist/src/tools/write-file.js +69 -14
- package/dist/src/ui/repl.js +1141 -299
- package/dist/src/ui/slash-commands.js +140 -0
- package/dist/src/ui/tui/attention.js +25 -0
- package/dist/src/ui/tui/bridge.js +38 -5
- package/dist/src/ui/tui/build-frame.js +858 -303
- package/dist/src/ui/tui/composer-layout.js +76 -0
- package/dist/src/ui/tui/desktop-notification.js +118 -0
- package/dist/src/ui/tui/markdown-render.js +21 -11
- package/dist/src/ui/tui/model-label.js +13 -0
- package/dist/src/ui/tui/shell-input.js +266 -61
- package/dist/src/ui/tui/shortcuts.js +61 -0
- package/dist/src/ui/tui/terminal-theme.js +28 -0
- package/dist/src/ui/tui/text.js +31 -6
- package/dist/src/ui/tui/user-input.js +593 -0
- package/dist/src/update-check.js +205 -0
- package/dist/src/usage-notice.js +52 -0
- package/dist/src/usage.js +25 -2
- package/dist/src/utils.js +4 -0
- package/dist/src/version.js +52 -2
- package/dist/vendor/mcp/LICENSES.txt +414 -0
- package/dist/vendor/mcp/client.cjs +82 -0
- package/package.json +22 -9
- package/dist/src/project-index.js +0 -233
- package/dist/src/tools/code-intel.js +0 -472
- package/dist/src/tools/find-symbol.js +0 -70
- package/dist/src/tools/hover-symbol.js +0 -95
- package/dist/src/tools/list-symbols.js +0 -55
- package/dist/src/tools/search-code.js +0 -37
- package/dist/src/tools/signature-help.js +0 -118
package/dist/bin/ai.js
CHANGED
|
@@ -1,68 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { runMcpCommand } from '../src/mcp-command.js';
|
|
2
3
|
import chalk from '../src/colors.js';
|
|
3
|
-
import { stdin as input, stdout as output } from 'node:process';
|
|
4
|
-
import readline from 'node:readline/promises';
|
|
5
4
|
import { ServerApi } from '../src/api/index.js';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
5
|
+
import { DEFAULT_THEGITAI_HOST } from '../src/api/default-host.js';
|
|
6
|
+
import { isSignInCancelled } from '../src/api/browser-login.js';
|
|
7
|
+
import { runSignIn } from '../src/signin.js';
|
|
8
|
+
import { ServerApiError, authenticationErrorMessage, isAuthenticationError, isTransientNetworkError, } from '../src/api/http.js';
|
|
9
|
+
import { loadStartupHandshake } from '../src/api/startup-handshake.js';
|
|
10
|
+
import { TURN_RECOVERY_DELAY_MS, TURN_RECOVERY_RETRIES, } from '../src/api/turn-recovery.js';
|
|
8
11
|
import { formatCliHelpText } from '../src/help-text.js';
|
|
9
|
-
import {
|
|
10
|
-
import { createSession } from '../src/session.js';
|
|
12
|
+
import { createSession, disposeSession } from '../src/session.js';
|
|
11
13
|
import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, saveSessionState, sessionHasUserMessage, } from '../src/session-store.js';
|
|
12
14
|
import { runClientInteractive } from '../src/ui/repl.js';
|
|
15
|
+
import { startBrowserDiscoveryInBackground } from '../src/browser/session-bridge.js';
|
|
13
16
|
import { appendPromptToFile } from '../src/ui/prompt-history-store.js';
|
|
14
17
|
import { formatSessionExitNotice } from '../src/session-exit.js';
|
|
15
18
|
import { formatUsageText } from '../src/usage.js';
|
|
16
|
-
import { formatVersionLine } from '../src/version.js';
|
|
19
|
+
import { getCliVersion, formatVersionLine } from '../src/version.js';
|
|
20
|
+
import { offerUpdateAtStartup } from '../src/update-check.js';
|
|
17
21
|
import { parseArgs } from '../src/cli-args.js';
|
|
18
|
-
const DEFAULT_SERVER_URL = 'https://thegit.ai';
|
|
19
22
|
const { auth, chat, models, sessions } = ServerApi;
|
|
20
23
|
function printUsage() {
|
|
21
24
|
console.log(formatCliHelpText({ color: process.stdout.isTTY === true }));
|
|
22
25
|
}
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return answer.trim() || fallback || '';
|
|
29
|
-
}
|
|
30
|
-
finally {
|
|
31
|
-
rl.close();
|
|
26
|
+
function unreachableReason(error) {
|
|
27
|
+
const err = error;
|
|
28
|
+
const code = err?.code ?? err?.cause?.code;
|
|
29
|
+
if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
|
|
30
|
+
return 'network timeout';
|
|
32
31
|
}
|
|
32
|
+
if (code === 'ENOTFOUND' || code === 'EAI_AGAIN')
|
|
33
|
+
return 'DNS lookup failed';
|
|
34
|
+
if (code === 'ECONNREFUSED')
|
|
35
|
+
return 'connection refused';
|
|
36
|
+
if (code === 'ECONNRESET' || code === 'EPIPE')
|
|
37
|
+
return 'connection reset';
|
|
38
|
+
return err?.message ? String(err.message) : 'network error';
|
|
33
39
|
}
|
|
34
40
|
function appendPromptHistory(prompt, env = process.env) {
|
|
35
41
|
appendPromptToFile(prompt, env);
|
|
36
42
|
}
|
|
37
|
-
async function runAuthCommand(command
|
|
38
|
-
if (command === 'login') {
|
|
39
|
-
const serverUrl = DEFAULT_SERVER_URL;
|
|
40
|
-
const noBrowser = args.includes('--no-browser');
|
|
41
|
-
console.log(chalk.dim(noBrowser
|
|
42
|
-
? 'Sign in on the website, then paste the authorization code here.'
|
|
43
|
-
: 'Opening your browser to sign in…'));
|
|
44
|
-
const result = await loginViaBrowser({
|
|
45
|
-
serverUrl,
|
|
46
|
-
noBrowser,
|
|
47
|
-
onUrl: (url) => {
|
|
48
|
-
console.log(chalk.dim(noBrowser ? 'Open this URL to sign in:' : 'If your browser did not open, visit:'));
|
|
49
|
-
console.log(` ${url}`);
|
|
50
|
-
},
|
|
51
|
-
onWaiting: () => console.log(chalk.dim('Waiting for you to finish signing in…')),
|
|
52
|
-
promptCode: noBrowser
|
|
53
|
-
? () => promptText('Paste the authorization code')
|
|
54
|
-
: undefined,
|
|
55
|
-
deviceName: process.env.THEGITAI_DEVICE_NAME?.trim() || undefined,
|
|
56
|
-
});
|
|
57
|
-
auth.writeCliAuthConfig(result);
|
|
58
|
-
console.log(chalk.green(`✓ Logged in as ${result.customer.email}`));
|
|
59
|
-
console.log(chalk.dim(`Server: ${result.serverUrl}`));
|
|
60
|
-
console.log(chalk.dim('You can close the browser tab. Run `ai` in a repo to start.'));
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
43
|
+
async function runAuthCommand(command) {
|
|
63
44
|
const config = auth.readCliAuthConfig();
|
|
64
45
|
if (!config) {
|
|
65
|
-
|
|
46
|
+
if (command === 'logout') {
|
|
47
|
+
console.log(chalk.green('Already signed out.'));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
throw new Error('Not signed in. Run `ai` to sign in.');
|
|
66
51
|
}
|
|
67
52
|
if (command === 'whoami') {
|
|
68
53
|
const customer = await auth.fetchWhoami({ config });
|
|
@@ -70,19 +55,25 @@ async function runAuthCommand(command, args) {
|
|
|
70
55
|
return;
|
|
71
56
|
}
|
|
72
57
|
if (command === 'logout') {
|
|
73
|
-
|
|
58
|
+
try {
|
|
59
|
+
await auth.logoutFromServer({ config });
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
}
|
|
74
63
|
auth.clearCliAuthConfig();
|
|
75
64
|
console.log(chalk.green('Logged out.'));
|
|
76
65
|
return;
|
|
77
66
|
}
|
|
78
67
|
throw new Error(`Unknown auth command: ${command}`);
|
|
79
68
|
}
|
|
80
|
-
function
|
|
69
|
+
async function ensureCliAuthConfig() {
|
|
81
70
|
const config = auth.readCliAuthConfig();
|
|
82
|
-
if (
|
|
83
|
-
|
|
71
|
+
if (config)
|
|
72
|
+
return config;
|
|
73
|
+
if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
|
|
74
|
+
throw new Error('Not signed in. Run `ai login` on a terminal to sign in.');
|
|
84
75
|
}
|
|
85
|
-
return
|
|
76
|
+
return await runSignIn();
|
|
86
77
|
}
|
|
87
78
|
function formatSessionName(name) {
|
|
88
79
|
return name ? `"${name}"` : '(unnamed)';
|
|
@@ -140,7 +131,11 @@ function requireInteractiveTerminal() {
|
|
|
140
131
|
return true;
|
|
141
132
|
}
|
|
142
133
|
export async function main() {
|
|
143
|
-
|
|
134
|
+
if (process.argv[2] === 'mcp') {
|
|
135
|
+
console.log(runMcpCommand(process.argv.slice(3)));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const { autoYes, help, version, usage, command, session: sessionIdentifier, listSessions, unknownOption, prompt, } = parseArgs(process.argv);
|
|
144
139
|
if (version) {
|
|
145
140
|
console.log(formatVersionLine());
|
|
146
141
|
return;
|
|
@@ -155,18 +150,18 @@ export async function main() {
|
|
|
155
150
|
process.exitCode = 2;
|
|
156
151
|
return;
|
|
157
152
|
}
|
|
158
|
-
if (command) {
|
|
159
|
-
await runAuthCommand(command
|
|
153
|
+
if (command && command !== 'login') {
|
|
154
|
+
await runAuthCommand(command);
|
|
160
155
|
return;
|
|
161
156
|
}
|
|
162
157
|
if (usage) {
|
|
163
|
-
const authConfig =
|
|
158
|
+
const authConfig = await ensureCliAuthConfig();
|
|
164
159
|
console.log(formatUsageText(await auth.fetchWhoamiResponse({ config: authConfig })));
|
|
165
160
|
return;
|
|
166
161
|
}
|
|
167
162
|
const rootDir = process.cwd();
|
|
168
163
|
if (listSessions) {
|
|
169
|
-
const activeServerUrl = auth.readCliAuthConfig()?.serverUrl ??
|
|
164
|
+
const activeServerUrl = auth.readCliAuthConfig()?.serverUrl ?? DEFAULT_THEGITAI_HOST;
|
|
170
165
|
printSessionList(rootDir, listSessionMetadata(rootDir), models.selectCacheForServer(models.readCachedServerModels(), activeServerUrl));
|
|
171
166
|
return;
|
|
172
167
|
}
|
|
@@ -181,47 +176,76 @@ export async function main() {
|
|
|
181
176
|
if (!requireInteractiveTerminal()) {
|
|
182
177
|
return;
|
|
183
178
|
}
|
|
184
|
-
const authConfig =
|
|
179
|
+
const authConfig = await ensureCliAuthConfig();
|
|
185
180
|
const serverSessionClient = sessions.createServerSessionClient({ config: authConfig });
|
|
186
181
|
const cachedModels = models.selectCacheForServer(models.readCachedServerModels(), authConfig.serverUrl);
|
|
182
|
+
const { models: modelsOutcome, whoami: whoamiOutcome } = await loadStartupHandshake({
|
|
183
|
+
config: authConfig,
|
|
184
|
+
canStartOffline: Boolean(cachedModels?.models.length),
|
|
185
|
+
onStatus: (status, lastFailure) => {
|
|
186
|
+
if (status.phase === 'waiting') {
|
|
187
|
+
const reason = lastFailure instanceof ServerApiError
|
|
188
|
+
? `HTTP ${lastFailure.status}`
|
|
189
|
+
: unreachableReason(lastFailure);
|
|
190
|
+
console.error(chalk.yellow(`⚠ Couldn't reach TheGitAI (${reason}) · retrying in ${TURN_RECOVERY_DELAY_MS / 1000}s · retry ${status.retry}/${TURN_RECOVERY_RETRIES}`));
|
|
191
|
+
}
|
|
192
|
+
else if (status.phase === 'reconnecting') {
|
|
193
|
+
console.error(chalk.dim(` Reconnecting · retry ${status.retry}/${TURN_RECOVERY_RETRIES}`));
|
|
194
|
+
}
|
|
195
|
+
else if (status.phase === 'restored') {
|
|
196
|
+
console.error(chalk.green('✓ Reconnected to TheGitAI'));
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
});
|
|
187
200
|
let offlineNotice = null;
|
|
188
201
|
let serverModels;
|
|
189
|
-
|
|
190
|
-
serverModels =
|
|
202
|
+
if (modelsOutcome.status === 'fulfilled') {
|
|
203
|
+
serverModels = modelsOutcome.value;
|
|
191
204
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
205
|
+
else if (isTransientNetworkError(modelsOutcome.reason) &&
|
|
206
|
+
cachedModels?.models.length) {
|
|
207
|
+
serverModels = { models: cachedModels.models };
|
|
208
|
+
offlineNotice = unreachableReason(modelsOutcome.reason);
|
|
209
|
+
}
|
|
210
|
+
else if (isTransientNetworkError(modelsOutcome.reason)) {
|
|
211
|
+
throw new Error(`Couldn't reach TheGitAI to load your models (${unreachableReason(modelsOutcome.reason)}).\nCheck your internet connection and run \`ai\` again.`);
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
throw modelsOutcome.reason;
|
|
200
215
|
}
|
|
201
216
|
let whoami;
|
|
202
|
-
|
|
203
|
-
whoami =
|
|
217
|
+
if (whoamiOutcome.status === 'fulfilled') {
|
|
218
|
+
whoami = whoamiOutcome.value;
|
|
204
219
|
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
throw error;
|
|
221
|
-
}
|
|
220
|
+
else if (isTransientNetworkError(whoamiOutcome.reason)) {
|
|
221
|
+
whoami = {
|
|
222
|
+
customer: {
|
|
223
|
+
id: '',
|
|
224
|
+
uuid: '',
|
|
225
|
+
email: authConfig.email,
|
|
226
|
+
customer_type: authConfig.customerType ?? 'USER',
|
|
227
|
+
scopes: [],
|
|
228
|
+
},
|
|
229
|
+
debugUi: { showSessionId: false },
|
|
230
|
+
};
|
|
231
|
+
offlineNotice ??= unreachableReason(whoamiOutcome.reason);
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
throw whoamiOutcome.reason;
|
|
222
235
|
}
|
|
223
236
|
if (offlineNotice) {
|
|
224
|
-
console.error(chalk.yellow(`⚠ Couldn't reach TheGitAI (${offlineNotice}). Starting with cached settings
|
|
237
|
+
console.error(chalk.yellow(`⚠ Couldn't reach TheGitAI (${offlineNotice}). Starting with cached settings - it will reconnect on your next message.`));
|
|
238
|
+
}
|
|
239
|
+
const updateOutcome = await offerUpdateAtStartup({
|
|
240
|
+
currentVersion: getCliVersion(),
|
|
241
|
+
latestVersion: whoami.release?.latestVersion ?? null,
|
|
242
|
+
});
|
|
243
|
+
if (updateOutcome === 'updated') {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (updateOutcome === 'cancelled') {
|
|
247
|
+
process.exitCode = 130;
|
|
248
|
+
return;
|
|
225
249
|
}
|
|
226
250
|
const selectedModelId = models.selectServerModel({
|
|
227
251
|
requestedModelId: sourceSnapshot?.modelId ?? null,
|
|
@@ -241,35 +265,39 @@ export async function main() {
|
|
|
241
265
|
if (sourceSnapshot) {
|
|
242
266
|
applySessionSnapshot(session, sourceSnapshot);
|
|
243
267
|
}
|
|
244
|
-
|
|
245
|
-
rootDir,
|
|
246
|
-
onStatus: (message) => {
|
|
247
|
-
if (message.trim()) {
|
|
248
|
-
console.log(chalk.dim(` ${message}`));
|
|
249
|
-
}
|
|
250
|
-
},
|
|
251
|
-
onContextLog: (message) => {
|
|
252
|
-
if (message.trim()) {
|
|
253
|
-
console.log(chalk.cyan(` ${message}`));
|
|
254
|
-
}
|
|
255
|
-
},
|
|
256
|
-
});
|
|
268
|
+
startBrowserDiscoveryInBackground({ cwd: rootDir, env: session.env });
|
|
257
269
|
const initialPrompt = prompt || undefined;
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
270
|
+
try {
|
|
271
|
+
const outcome = await runClientInteractive({
|
|
272
|
+
appendPromptHistory: (value) => appendPromptHistory(value, session.env),
|
|
273
|
+
authConfig,
|
|
274
|
+
debugUi: whoami.debugUi,
|
|
275
|
+
plan: whoami.usage?.plan,
|
|
276
|
+
serverModels,
|
|
277
|
+
serverSessionClient,
|
|
278
|
+
session,
|
|
279
|
+
initialPrompt,
|
|
280
|
+
usageText: async () => formatUsageText(await auth.fetchWhoamiResponse({ config: authConfig })),
|
|
281
|
+
});
|
|
282
|
+
if (outcome.signedOut) {
|
|
283
|
+
if (sessionHasUserMessage(session)) {
|
|
284
|
+
saveSessionState(session);
|
|
285
|
+
}
|
|
286
|
+
console.log(chalk.green('\n✓ Logged out.\n'));
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
await saveSessionBoth({ session, serverSessionClient });
|
|
290
|
+
printSessionExit(session);
|
|
291
|
+
}
|
|
292
|
+
finally {
|
|
293
|
+
await disposeSession(session);
|
|
294
|
+
}
|
|
271
295
|
}
|
|
272
296
|
main().catch((error) => {
|
|
297
|
+
if (isSignInCancelled(error)) {
|
|
298
|
+
console.error(chalk.dim('\nSign-in cancelled. Nothing was saved.\n'));
|
|
299
|
+
process.exit(130);
|
|
300
|
+
}
|
|
273
301
|
if (isAuthenticationError(error)) {
|
|
274
302
|
auth.clearCliAuthConfig();
|
|
275
303
|
console.error(chalk.red(`\n✖ Error: ${authenticationErrorMessage(error)}\n`));
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { decodeFrames, encodeFrame, fragmentPayload, MAX_FRAME_BYTES } from '../src/browser/framing.js';
|
|
8
|
+
import { chromeProfileLabel } from '../src/browser/chrome-profiles.js';
|
|
9
|
+
import { BROWSER_PROTOCOL_VERSION, browserRuntimeDir, sessionKeyFromRecordFile, sessionSocketPath, socketIsFile, } from '../src/browser/protocol.js';
|
|
10
|
+
const SCAN_INTERVAL_MS = 1000;
|
|
11
|
+
const NUL = String.fromCharCode(0);
|
|
12
|
+
const sessions = new Map();
|
|
13
|
+
const runtimeDir = browserRuntimeDir(process.env);
|
|
14
|
+
let extensionVersion = '';
|
|
15
|
+
let extensionProfileId = '';
|
|
16
|
+
let extensionProfileLabel = '';
|
|
17
|
+
let extensionPlatform = '';
|
|
18
|
+
let extensionLastFocusedAt = 0;
|
|
19
|
+
function log(message) {
|
|
20
|
+
process.stderr.write(`[thegitai-browser-host] ${message}\n`);
|
|
21
|
+
}
|
|
22
|
+
function writeToExtension(frame) {
|
|
23
|
+
const payload = Buffer.from(JSON.stringify(frame), 'utf8');
|
|
24
|
+
if (payload.length > MAX_FRAME_BYTES) {
|
|
25
|
+
for (const fragment of fragmentPayload(payload, crypto.randomUUID())) {
|
|
26
|
+
writeToExtension(fragment);
|
|
27
|
+
}
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
process.stdout.write(encodeFrame(payload));
|
|
31
|
+
}
|
|
32
|
+
let inbound = Buffer.alloc(0);
|
|
33
|
+
process.stdin.on('data', (chunk) => {
|
|
34
|
+
inbound = Buffer.concat([inbound, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8')]);
|
|
35
|
+
const { frames, rest, unparseable } = decodeFrames(inbound);
|
|
36
|
+
inbound = rest;
|
|
37
|
+
for (let i = 0; i < unparseable; i += 1) {
|
|
38
|
+
log('discarded an unparseable frame from the extension');
|
|
39
|
+
}
|
|
40
|
+
for (const frame of frames)
|
|
41
|
+
handleExtensionFrame(frame);
|
|
42
|
+
});
|
|
43
|
+
process.stdin.on('end', () => {
|
|
44
|
+
for (const link of sessions.values())
|
|
45
|
+
link.socket.destroy();
|
|
46
|
+
process.exit(0);
|
|
47
|
+
});
|
|
48
|
+
function describeParentBrowser() {
|
|
49
|
+
const cmdline = process.platform === 'win32' ? windowsParentCommandLine() : unixParentCommandLine();
|
|
50
|
+
const userDataArg = cmdline.find((part) => part.startsWith('--user-data-dir='));
|
|
51
|
+
return {
|
|
52
|
+
...describeFromCommandLine(cmdline),
|
|
53
|
+
userDataDir: userDataArg ? userDataArg.slice('--user-data-dir='.length) : '',
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function windowsParentCommandLine() {
|
|
57
|
+
const PASS_THROUGH = /^(cmd|conhost|powershell|pwsh|node)\.exe$/i;
|
|
58
|
+
try {
|
|
59
|
+
const rows = execFileSync('powershell.exe', [
|
|
60
|
+
'-NoProfile',
|
|
61
|
+
'-NonInteractive',
|
|
62
|
+
'-Command',
|
|
63
|
+
'Get-CimInstance Win32_Process | ForEach-Object {' +
|
|
64
|
+
' "{0}`t{1}`t{2}`t{3}" -f $_.ProcessId, $_.ParentProcessId, $_.Name, $_.CommandLine }',
|
|
65
|
+
], {
|
|
66
|
+
encoding: 'utf8',
|
|
67
|
+
timeout: 15000,
|
|
68
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
69
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
70
|
+
});
|
|
71
|
+
const byPid = new Map();
|
|
72
|
+
for (const line of rows.split(/\r?\n/)) {
|
|
73
|
+
const [pid, parent, name, ...rest] = line.split('\t');
|
|
74
|
+
const id = Number(pid);
|
|
75
|
+
if (!Number.isInteger(id))
|
|
76
|
+
continue;
|
|
77
|
+
byPid.set(id, {
|
|
78
|
+
parent: Number(parent),
|
|
79
|
+
name: String(name ?? ''),
|
|
80
|
+
command: rest.join('\t'),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
let current = byPid.get(process.ppid);
|
|
84
|
+
for (let hop = 0; hop < 4 && current && PASS_THROUGH.test(current.name); hop += 1) {
|
|
85
|
+
current = byPid.get(current.parent);
|
|
86
|
+
}
|
|
87
|
+
if (!current?.command)
|
|
88
|
+
return [];
|
|
89
|
+
return (current.command.match(/"[^"]*"|\S+/g) ?? []).map((token) => token.startsWith('"') && token.endsWith('"') ? token.slice(1, -1) : token);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function unixParentCommandLine() {
|
|
96
|
+
try {
|
|
97
|
+
return fs.readFileSync(`/proc/${process.ppid}/cmdline`, 'utf8').split(NUL);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function describeFromCommandLine(cmdline) {
|
|
104
|
+
try {
|
|
105
|
+
if (cmdline.length === 0)
|
|
106
|
+
throw new Error('no command line');
|
|
107
|
+
const brand = path
|
|
108
|
+
.basename(cmdline[0] ?? '')
|
|
109
|
+
.replace(/\.exe$/i, '')
|
|
110
|
+
.replace(/[-_](browser|stable|beta|dev|unstable|bin)$/i, '')
|
|
111
|
+
.replace(/[-_]+/g, ' ')
|
|
112
|
+
.replace(/\b[a-z]/g, (letter) => letter.toUpperCase())
|
|
113
|
+
.trim() || 'Chrome';
|
|
114
|
+
const profileArg = cmdline.find((part) => part.startsWith('--profile-directory='));
|
|
115
|
+
const userDataArg = cmdline.find((part) => part.startsWith('--user-data-dir='));
|
|
116
|
+
const profile = profileArg ? profileArg.slice('--profile-directory='.length) : 'Default';
|
|
117
|
+
const suffix = userDataArg
|
|
118
|
+
? ` (${path.basename(userDataArg.slice('--user-data-dir='.length))})`
|
|
119
|
+
: '';
|
|
120
|
+
return { browser: brand, profile: `${profile}${suffix}` };
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return { browser: 'Chrome', profile: 'Default' };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const parent = describeParentBrowser();
|
|
127
|
+
function browserKey() {
|
|
128
|
+
const seed = extensionProfileId || `${parent.browser} ${parent.profile}`;
|
|
129
|
+
return crypto.createHash('sha256').update(seed).digest('hex').slice(0, 12);
|
|
130
|
+
}
|
|
131
|
+
function identity() {
|
|
132
|
+
return {
|
|
133
|
+
key: browserKey(),
|
|
134
|
+
browser: parent.browser,
|
|
135
|
+
profile: extensionProfileLabel ||
|
|
136
|
+
(parent.profile !== 'Default' || !extensionProfileId
|
|
137
|
+
? parent.profile
|
|
138
|
+
: `profile ${extensionProfileId.slice(0, 6)}`),
|
|
139
|
+
platform: extensionPlatform || process.platform,
|
|
140
|
+
extensionVersion,
|
|
141
|
+
...(extensionLastFocusedAt > 0 ? { lastFocusedAt: extensionLastFocusedAt } : {}),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
function handleExtensionFrame(frame) {
|
|
145
|
+
if (frame?.t === 'hello') {
|
|
146
|
+
extensionVersion = String(frame.extensionVersion ?? '');
|
|
147
|
+
extensionProfileId = String(frame.profileId ?? '');
|
|
148
|
+
extensionProfileLabel = /^[0-9a-f-]{36}$/i.test(extensionProfileId)
|
|
149
|
+
? chromeProfileLabel(extensionProfileId, parent.userDataDir)
|
|
150
|
+
: '';
|
|
151
|
+
extensionPlatform = String(frame.platform ?? '');
|
|
152
|
+
extensionLastFocusedAt = Number(frame.lastFocusedAt) || 0;
|
|
153
|
+
writeToExtension({ t: 'hello', protocol: BROWSER_PROTOCOL_VERSION });
|
|
154
|
+
publishSessions();
|
|
155
|
+
for (const link of sessions.values())
|
|
156
|
+
sendHello(link);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (frame?.t === 'focus') {
|
|
160
|
+
extensionLastFocusedAt = Number(frame.at) || extensionLastFocusedAt;
|
|
161
|
+
for (const link of sessions.values())
|
|
162
|
+
sendHello(link);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (frame?.t === 'res' || frame?.t === 'event') {
|
|
166
|
+
const target = frame.session ? sessions.get(frame.session) : null;
|
|
167
|
+
const { session: _routed, ...rest } = frame;
|
|
168
|
+
if (target) {
|
|
169
|
+
writeToSession(target, rest);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (frame.t === 'event') {
|
|
173
|
+
for (const link of sessions.values())
|
|
174
|
+
writeToSession(link, rest);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function writeToSession(link, frame) {
|
|
179
|
+
try {
|
|
180
|
+
link.socket.write(`${JSON.stringify(frame)}\n`);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function sendHello(link) {
|
|
186
|
+
writeToSession(link, { t: 'hello', protocol: BROWSER_PROTOCOL_VERSION, browser: identity() });
|
|
187
|
+
}
|
|
188
|
+
function publishSessions() {
|
|
189
|
+
writeToExtension({
|
|
190
|
+
t: 'sessions',
|
|
191
|
+
sessions: [...sessions.values()].map((link) => ({
|
|
192
|
+
session: link.key,
|
|
193
|
+
label: link.record.label,
|
|
194
|
+
cwd: link.record.cwd,
|
|
195
|
+
})),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
function connectToSession(record, socketPath) {
|
|
199
|
+
if (sessions.has(record.session))
|
|
200
|
+
return;
|
|
201
|
+
const socket = net.createConnection(socketPath);
|
|
202
|
+
socket.setNoDelay(true);
|
|
203
|
+
const link = { key: record.session, socket, record };
|
|
204
|
+
socket.on('connect', () => {
|
|
205
|
+
sessions.set(record.session, link);
|
|
206
|
+
sendHello(link);
|
|
207
|
+
publishSessions();
|
|
208
|
+
log(`attached to session ${record.session} (${record.cwd})`);
|
|
209
|
+
});
|
|
210
|
+
let buffer = '';
|
|
211
|
+
socket.on('data', (chunk) => {
|
|
212
|
+
buffer += chunk.toString('utf8');
|
|
213
|
+
let newline = buffer.indexOf('\n');
|
|
214
|
+
while (newline !== -1) {
|
|
215
|
+
const line = buffer.slice(0, newline);
|
|
216
|
+
buffer = buffer.slice(newline + 1);
|
|
217
|
+
newline = buffer.indexOf('\n');
|
|
218
|
+
if (!line.trim())
|
|
219
|
+
continue;
|
|
220
|
+
let frame;
|
|
221
|
+
try {
|
|
222
|
+
frame = JSON.parse(line);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
writeToExtension({ ...frame, session: record.session });
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
const drop = () => {
|
|
231
|
+
if (sessions.get(record.session) === link) {
|
|
232
|
+
sessions.delete(record.session);
|
|
233
|
+
publishSessions();
|
|
234
|
+
}
|
|
235
|
+
socket.destroy();
|
|
236
|
+
};
|
|
237
|
+
socket.on('close', drop);
|
|
238
|
+
socket.on('error', () => {
|
|
239
|
+
drop();
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
function scanForSessions() {
|
|
243
|
+
let entries;
|
|
244
|
+
try {
|
|
245
|
+
entries = fs.readdirSync(runtimeDir);
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
for (const entry of entries) {
|
|
251
|
+
const sessionKey = sessionKeyFromRecordFile(entry);
|
|
252
|
+
if (!sessionKey)
|
|
253
|
+
continue;
|
|
254
|
+
const recordPath = path.join(runtimeDir, entry);
|
|
255
|
+
let record;
|
|
256
|
+
try {
|
|
257
|
+
record = JSON.parse(fs.readFileSync(recordPath, 'utf8'));
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (record.protocol !== BROWSER_PROTOCOL_VERSION)
|
|
263
|
+
continue;
|
|
264
|
+
try {
|
|
265
|
+
process.kill(record.pid, 0);
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
if (error?.code !== 'EPERM') {
|
|
269
|
+
try {
|
|
270
|
+
fs.unlinkSync(recordPath);
|
|
271
|
+
if (socketIsFile())
|
|
272
|
+
fs.unlinkSync(sessionSocketPath(runtimeDir, sessionKey));
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
}
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
connectToSession(record, sessionSocketPath(runtimeDir, sessionKey));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
setInterval(scanForSessions, SCAN_INTERVAL_MS);
|
|
283
|
+
scanForSessions();
|
|
284
|
+
log(`started for ${parent.browser} / ${parent.profile}`);
|