@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
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 { loginViaBrowser } from '../src/api/browser-login.js';
7
- import { authenticationErrorMessage, isAuthenticationError, isTransientNetworkError, } from '../src/api/http.js';
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 { createIndex } from '../src/project-index.js';
10
- import { createSession } from '../src/session.js';
11
- import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, saveSessionState, } from '../src/session-store.js';
12
+ import { createSession, disposeSession } from '../src/session.js';
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
- async function promptText(question, fallback = null) {
24
- const rl = readline.createInterface({ input, output });
25
- try {
26
- const suffix = fallback ? ` (${fallback})` : '';
27
- const answer = await rl.question(`${question}${suffix}: `);
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, args) {
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
- throw new Error('Not logged in. Run `ai login` first.');
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
- await auth.logoutFromServer({ config });
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 requireCliAuthConfig() {
69
+ async function ensureCliAuthConfig() {
81
70
  const config = auth.readCliAuthConfig();
82
- if (!config) {
83
- throw new Error('Not logged in. Run `ai login` first.');
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 config;
76
+ return await runSignIn();
86
77
  }
87
78
  function formatSessionName(name) {
88
79
  return name ? `"${name}"` : '(unnamed)';
@@ -116,6 +107,8 @@ function modelLabel(serverModels, modelId) {
116
107
  `Model ${modelId}`);
117
108
  }
118
109
  async function saveSessionBoth({ session, serverSessionClient, }) {
110
+ if (!sessionHasUserMessage(session))
111
+ return;
119
112
  saveSessionState(session);
120
113
  try {
121
114
  await serverSessionClient.save(session);
@@ -138,7 +131,11 @@ function requireInteractiveTerminal() {
138
131
  return true;
139
132
  }
140
133
  export async function main() {
141
- const { autoYes, help, version, usage, command, commandArgs, session: sessionIdentifier, listSessions, unknownOption, prompt, } = parseArgs(process.argv);
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);
142
139
  if (version) {
143
140
  console.log(formatVersionLine());
144
141
  return;
@@ -153,18 +150,18 @@ export async function main() {
153
150
  process.exitCode = 2;
154
151
  return;
155
152
  }
156
- if (command) {
157
- await runAuthCommand(command, commandArgs);
153
+ if (command && command !== 'login') {
154
+ await runAuthCommand(command);
158
155
  return;
159
156
  }
160
157
  if (usage) {
161
- const authConfig = requireCliAuthConfig();
158
+ const authConfig = await ensureCliAuthConfig();
162
159
  console.log(formatUsageText(await auth.fetchWhoamiResponse({ config: authConfig })));
163
160
  return;
164
161
  }
165
162
  const rootDir = process.cwd();
166
163
  if (listSessions) {
167
- const activeServerUrl = auth.readCliAuthConfig()?.serverUrl ?? DEFAULT_SERVER_URL;
164
+ const activeServerUrl = auth.readCliAuthConfig()?.serverUrl ?? DEFAULT_THEGITAI_HOST;
168
165
  printSessionList(rootDir, listSessionMetadata(rootDir), models.selectCacheForServer(models.readCachedServerModels(), activeServerUrl));
169
166
  return;
170
167
  }
@@ -179,47 +176,76 @@ export async function main() {
179
176
  if (!requireInteractiveTerminal()) {
180
177
  return;
181
178
  }
182
- const authConfig = requireCliAuthConfig();
179
+ const authConfig = await ensureCliAuthConfig();
183
180
  const serverSessionClient = sessions.createServerSessionClient({ config: authConfig });
184
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
+ });
185
200
  let offlineNotice = null;
186
201
  let serverModels;
187
- try {
188
- serverModels = await models.fetchServerModels({ config: authConfig });
202
+ if (modelsOutcome.status === 'fulfilled') {
203
+ serverModels = modelsOutcome.value;
189
204
  }
190
- catch (error) {
191
- if (isTransientNetworkError(error) && cachedModels?.models.length) {
192
- serverModels = { models: cachedModels.models };
193
- offlineNotice = error?.message ? String(error.message) : 'network error';
194
- }
195
- else {
196
- throw error;
197
- }
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;
198
215
  }
199
216
  let whoami;
200
- try {
201
- whoami = await auth.fetchWhoamiResponse({ config: authConfig });
217
+ if (whoamiOutcome.status === 'fulfilled') {
218
+ whoami = whoamiOutcome.value;
202
219
  }
203
- catch (error) {
204
- if (isTransientNetworkError(error)) {
205
- whoami = {
206
- customer: {
207
- id: '',
208
- uuid: '',
209
- email: authConfig.email,
210
- customer_type: authConfig.customerType ?? 'USER',
211
- scopes: [],
212
- },
213
- debugUi: { showSessionId: false },
214
- };
215
- offlineNotice ??= error?.message ? String(error.message) : 'network error';
216
- }
217
- else {
218
- throw error;
219
- }
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;
220
235
  }
221
236
  if (offlineNotice) {
222
- console.error(chalk.yellow(`⚠ Couldn't reach TheGitAI (${offlineNotice}). Starting with cached settings — it will reconnect on your next message.`));
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;
223
249
  }
224
250
  const selectedModelId = models.selectServerModel({
225
251
  requestedModelId: sourceSnapshot?.modelId ?? null,
@@ -239,35 +265,39 @@ export async function main() {
239
265
  if (sourceSnapshot) {
240
266
  applySessionSnapshot(session, sourceSnapshot);
241
267
  }
242
- const projectIndex = createIndex({
243
- rootDir,
244
- onStatus: (message) => {
245
- if (message.trim()) {
246
- console.log(chalk.dim(` ${message}`));
247
- }
248
- },
249
- onContextLog: (message) => {
250
- if (message.trim()) {
251
- console.log(chalk.cyan(` ${message}`));
252
- }
253
- },
254
- });
268
+ startBrowserDiscoveryInBackground({ cwd: rootDir, env: session.env });
255
269
  const initialPrompt = prompt || undefined;
256
- await runClientInteractive({
257
- appendPromptHistory: (value) => appendPromptHistory(value, session.env),
258
- authConfig,
259
- debugUi: whoami.debugUi,
260
- projectIndex,
261
- serverModels,
262
- serverSessionClient,
263
- session,
264
- initialPrompt,
265
- usageText: async () => formatUsageText(await auth.fetchWhoamiResponse({ config: authConfig })),
266
- });
267
- await saveSessionBoth({ session, serverSessionClient });
268
- printSessionExit(session);
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
+ }
269
295
  }
270
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
+ }
271
301
  if (isAuthenticationError(error)) {
272
302
  auth.clearCliAuthConfig();
273
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}`);