@thegitai/cli 1.0.0-preview.6 → 1.0.0-preview.61

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 (91) hide show
  1. package/README.md +232 -7
  2. package/dist/bin/ai.js +140 -111
  3. package/dist/bin/browser-host.js +284 -0
  4. package/dist/src/agent-mode.js +32 -7
  5. package/dist/src/api/auth.js +8 -2
  6. package/dist/src/api/browser-login.js +147 -35
  7. package/dist/src/api/chat.js +691 -166
  8. package/dist/src/api/contracts.js +55 -1
  9. package/dist/src/api/default-host.js +1 -0
  10. package/dist/src/api/http.js +139 -8
  11. package/dist/src/api/models.js +34 -9
  12. package/dist/src/api/startup-handshake.js +36 -0
  13. package/dist/src/api/turn-recovery.js +189 -0
  14. package/dist/src/background-jobs.js +8 -2
  15. package/dist/src/browser/bridge.js +268 -0
  16. package/dist/src/browser/chrome-profiles.js +73 -0
  17. package/dist/src/browser/framing.js +42 -0
  18. package/dist/src/browser/native-host.js +219 -0
  19. package/dist/src/browser/protocol.js +46 -0
  20. package/dist/src/browser/session-bridge.js +130 -0
  21. package/dist/src/cli-args.js +19 -5
  22. package/dist/src/client-environment.js +2 -0
  23. package/dist/src/core/clipboard.js +7 -13
  24. package/dist/src/core/image-limits.js +56 -0
  25. package/dist/src/core/image-path-extractor.js +70 -3
  26. package/dist/src/core/session-image-store.js +246 -0
  27. package/dist/src/edit-journal.js +33 -2
  28. package/dist/src/executor.js +25 -3
  29. package/dist/src/help-text.js +128 -22
  30. package/dist/src/job-follow-up.js +40 -0
  31. package/dist/src/mcp-client.js +335 -0
  32. package/dist/src/mcp-command.js +176 -0
  33. package/dist/src/mcp-config.js +123 -0
  34. package/dist/src/mcp-sdk.js +3 -0
  35. package/dist/src/mcp-types.js +26 -0
  36. package/dist/src/patcher.js +43 -4
  37. package/dist/src/permissions.js +301 -0
  38. package/dist/src/preferences.js +39 -0
  39. package/dist/src/project-key.js +11 -0
  40. package/dist/src/project-model-preferences.js +74 -0
  41. package/dist/src/quota-notice.js +35 -0
  42. package/dist/src/reasoning-effort.js +27 -0
  43. package/dist/src/session-safety.js +0 -12
  44. package/dist/src/session-store.js +123 -30
  45. package/dist/src/session.js +20 -4
  46. package/dist/src/signin.js +58 -0
  47. package/dist/src/tool-executor.js +26 -49
  48. package/dist/src/tools/browser.js +872 -0
  49. package/dist/src/tools/delete-file.js +20 -4
  50. package/dist/src/tools/index.js +32 -10
  51. package/dist/src/tools/patch-file.js +12 -26
  52. package/dist/src/tools/read-file.js +5 -0
  53. package/dist/src/tools/read-image-file.js +85 -0
  54. package/dist/src/tools/replace-document-text.js +28 -18
  55. package/dist/src/tools/restore-checkpoint.js +0 -1
  56. package/dist/src/tools/run-command.js +14 -71
  57. package/dist/src/tools/run-node-script.js +12 -81
  58. package/dist/src/tools/save-generated-image.js +120 -0
  59. package/dist/src/tools/str-replace.js +12 -26
  60. package/dist/src/tools/undo-edit.js +1 -6
  61. package/dist/src/tools/write-file.js +67 -11
  62. package/dist/src/ui/prompt-history-store.js +1 -1
  63. package/dist/src/ui/repl.js +1017 -299
  64. package/dist/src/ui/slash-commands.js +122 -0
  65. package/dist/src/ui/tui/attention.js +25 -0
  66. package/dist/src/ui/tui/bridge.js +38 -5
  67. package/dist/src/ui/tui/build-frame.js +807 -270
  68. package/dist/src/ui/tui/composer-layout.js +76 -0
  69. package/dist/src/ui/tui/desktop-notification.js +118 -0
  70. package/dist/src/ui/tui/markdown-render.js +21 -11
  71. package/dist/src/ui/tui/model-label.js +13 -0
  72. package/dist/src/ui/tui/shell-input.js +275 -73
  73. package/dist/src/ui/tui/shortcuts.js +61 -0
  74. package/dist/src/ui/tui/terminal-theme.js +28 -0
  75. package/dist/src/ui/tui/text.js +31 -6
  76. package/dist/src/ui/tui/user-input.js +593 -0
  77. package/dist/src/update-check.js +205 -0
  78. package/dist/src/usage-notice.js +52 -0
  79. package/dist/src/usage.js +5 -2
  80. package/dist/src/utils.js +13 -0
  81. package/dist/src/version.js +52 -2
  82. package/dist/vendor/mcp/LICENSES.txt +414 -0
  83. package/dist/vendor/mcp/client.cjs +82 -0
  84. package/package.json +22 -9
  85. package/dist/src/project-index.js +0 -233
  86. package/dist/src/tools/code-intel.js +0 -472
  87. package/dist/src/tools/find-symbol.js +0 -70
  88. package/dist/src/tools/hover-symbol.js +0 -95
  89. package/dist/src/tools/list-symbols.js +0 -55
  90. package/dist/src/tools/search-code.js +0 -37
  91. package/dist/src/tools/signature-help.js +0 -118
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # TheGitAI — AI coding agent for your terminal
2
2
 
3
- TheGitAI is an AI coding agent for your terminal. It indexes your repository,
3
+ TheGitAI is an AI coding agent for your terminal. It reads and searches your repository,
4
4
  writes and edits files, runs commands, and builds features with you.
5
5
 
6
6
  Talk to your repo in plain English. TheGitAI can keep long-running processes
@@ -12,14 +12,26 @@ going while you work, all with your approval.
12
12
  npm i -g @thegitai/cli
13
13
  ```
14
14
 
15
- Requires Node.js 24 or newer.
15
+ Supports Node.js 22 and newer. Node.js 24 is recommended.
16
+
17
+ This installs the `ai` command. If `ai` is already taken by another command on
18
+ your machine, `thegitai` starts the same CLI.
19
+
20
+ ## Updates
21
+
22
+ `ai` checks for a newer release each time it starts, and offers to install it
23
+ for you. TheGitAI works best on the latest version, and an older CLI may not
24
+ work optimally. **Update now** is already selected, so Enter takes it — the CLI
25
+ installs the update and asks you to start `ai` again, so the whole session runs
26
+ one version — while ↑/↓ moves to **Skip** to go on with the version you have. Skipping lasts for that session
27
+ only; the next start asks again. Ctrl+C quits without installing anything.
16
28
 
17
29
  ## Usage
18
30
 
19
31
  ```text
20
- ai start an interactive session in the current repo
32
+ ai sign in if needed, then start a session in the current repo
21
33
  ai "<request>" start a session with <request> as the first message
22
- ai login sign in via your browser (--no-browser for SSH/headless)
34
+ ai login the same as `ai`; kept for muscle memory
23
35
  ai whoami show the signed-in account
24
36
  ai --usage show account usage and reset times
25
37
  ai logout sign out
@@ -28,15 +40,226 @@ ai --version print the version and exit
28
40
 
29
41
  Run `ai --help` for sessions, modes, keys, and chat commands.
30
42
 
43
+ The CLI shows a usage notice at 80% and 95% of your 5-hour, weekly, or monthly
44
+ allowance while work continues. Notices include when usage starts resetting in
45
+ your local time and a reminder to run `/usage`. When more than one allowance is
46
+ nearly used, the notice names only the most urgent one; `/usage` shows them
47
+ all. While the CLI stays open, the 80% notice rearms only
48
+ below 75% usage and the 95% notice only below 90%, so small fluctuations stay
49
+ quiet. Restarting the CLI can show a notice again. A nearly exhausted allowance
50
+ displays "over 99%". Live notices clear when a turn ends or is cancelled, and
51
+ remain in the transcript. Usage updates arrive when a turn starts and after
52
+ usage is saved during and at the end of the turn. An exhausted allowance still
53
+ shows `Usage limit reached`.
54
+
31
55
  Coding sessions require an interactive terminal on stdin and stdout. Piped
32
56
  one-shot prompts are not supported. Saved history is local to the repo and can
33
57
  always be viewed or resumed from that computer. Continuing it through the
34
58
  service requires the TheGitAI account used for that session. Local sessions can
35
59
  also be listed while signed out or offline.
36
60
 
37
- CLI login tokens use a rolling 24-hour inactivity timeout. If one expires during
38
- any server request, the CLI saves the local session, removes the expired
39
- credential, and asks you to run `ai login` before resuming.
61
+ Signing in opens your browser. The same screen also prints a URL you can open on
62
+ any other device and a box for an authorization code, so SSH and headless
63
+ machines need no separate command: open the URL wherever you have a browser,
64
+ choose "On another computer" on that page, and paste the code it shows.
65
+
66
+ CLI login tokens use a rolling 48-hour inactivity timeout. If one expires during
67
+ any server request, the CLI removes the expired credential and signs you in
68
+ again on the next run.
69
+
70
+ ## Models and reasoning effort
71
+
72
+ Type `/model` to choose with **↑ / ↓**. The **Auto** options come first: Cost
73
+ Efficient, Fastest and Most Intelligent. Auto picks the model and its reasoning
74
+ effort for each session, and new installs start on Auto (Cost Efficient). The
75
+ named models follow under **Models**; for one of them, adjust its reasoning
76
+ effort with **← / →** in the same panel: **Default / Low / Balanced / Deep**.
77
+ **Enter** saves the selected model's choice for this project; **Esc** cancels.
78
+ Each model remembers its own choice across new and resumed sessions.
79
+ The picker shows a model's effort beside its name when it is not Default, and
80
+ the footer always shows it, except on Auto, which sets its own. The footer labels
81
+ agent mode separately as `Mode: ...`; narrow terminals place it on the next
82
+ line, keeping both settings visible while idle and working.
83
+
84
+ Default uses TheGitAI's current recommended setting for the model. Low favors
85
+ quicker responses, Balanced balances depth and speed, and Deep favors thorough
86
+ reasoning and may take longer and cost more. Choosing Default again clears your
87
+ override. Switching models preserves your conversation.
88
+ An invalid project preference file loads Default effort; saving refuses to
89
+ overwrite it until the file is repaired or removed.
90
+
91
+ ## When the connection drops
92
+
93
+ A dropped connection does not end your turn. The CLI shows
94
+ `Connection interrupted · retrying in 10s · retry 1/3` under the working timer,
95
+ waits ten seconds, and reconnects to the same turn — it never starts the request
96
+ over, and a command, edit or browser action that already ran is not run again.
97
+ It tries three times. Once it is back, the turn simply continues and a short
98
+ `Connection restored` note stays in the transcript.
99
+
100
+ The same applies when you start `ai` while TheGitAI is briefly unavailable:
101
+ startup shows `Couldn't reach TheGitAI (…) · retrying in 10s · retry 1/3` and
102
+ waits up to three times before giving up.
103
+
104
+ If TheGitAI itself restarted while it was working, the turn cannot resume
105
+ where it was. It continues instead: the CLI sends your request once more with
106
+ the steps that already finished on your machine and everything you told it
107
+ during the turn, and the work picks up from there — a command that already ran
108
+ is not run again, and a correction you made still stands — with a short
109
+ `Server restarted` note in the transcript.
110
+
111
+ Press Esc at any point to stop the turn instead. If all three retries fail, the
112
+ turn ends with an error that names what was interrupted, notes that some actions
113
+ may already have completed, and leaves anything you had queued in the composer
114
+ rather than sending it on top of a turn whose outcome is unknown.
115
+
116
+ ## MCP servers
117
+
118
+ Connect external tools with the Model Context Protocol (MCP). TheGitAI supports
119
+ local **stdio** servers and remote **Streamable HTTP** servers through the
120
+ official MCP SDK. Setup uses familiar `mcp` commands:
121
+
122
+ ```bash
123
+ # Remote documentation tools
124
+ ai mcp add --transport http context7 https://mcp.context7.com/mcp
125
+
126
+ # Local browser tools in a separate, temporary browser profile
127
+ ai mcp add playwright -- npx -y @playwright/mcp@latest --headless --isolated
128
+
129
+ ai mcp list
130
+ ai mcp get context7
131
+ ai mcp disable playwright
132
+ ai mcp enable playwright
133
+ ai mcp remove playwright
134
+ ```
135
+
136
+ Inside a chat, run **`/mcp`** to connect and see each server's status and tools.
137
+ Configured tools are connected in parallel and made available to the active
138
+ model. Tool lists are cached for one minute and refreshed when the server reports
139
+ a change. Failed connections wait one minute before retrying; `/mcp` retries
140
+ immediately, and a check you cancel is retried on the next turn. Ask normally, or name the server when you want it used—for
141
+ example, “Use Context7 to check the current API for this library.” Configuration
142
+ changes apply on the next turn or `/mcp`; they do not change an in-flight turn.
143
+ `ai mcp list` shows configuration without starting servers. `get` shows metadata
144
+ without printing URLs, arguments, or credential values.
145
+
146
+ For authentication, use headers or explicitly pass environment variables:
147
+
148
+ ```bash
149
+ # Set CONTEXT7_API_KEY in your environment first. Single quotes keep the
150
+ # placeholder in the config instead of saving the secret itself.
151
+ ai mcp add --transport http docs https://mcp.context7.com/mcp \
152
+ --header 'Authorization: Bearer ${CONTEXT7_API_KEY}'
153
+
154
+ ai mcp add --env SERVICE_TOKEN='${SERVICE_TOKEN}' local-tools -- my-mcp-server
155
+ ```
156
+
157
+ The short flags `-t`, `-e` and `-H` mean `--transport`, `--env` and `--header`.
158
+ `-s user` / `--scope user` is accepted; project and local scopes are unavailable.
159
+
160
+ Values support `${VARIABLE}` and `${VARIABLE:-default}` expansion when connecting.
161
+ Missing variables produce a visible connection error. Local servers inherit a
162
+ small standard environment (such as PATH and HOME); explicitly pass service
163
+ credentials with `--env`. A local server starts in the current repository.
164
+
165
+ To reuse a server's JSON setup instructions:
166
+
167
+ ```bash
168
+ ai mcp add-json docs '{"type":"http","url":"https://mcp.context7.com/mcp"}'
169
+ ai mcp add-json local-tools '{"command":"my-mcp-server","args":[],"env":{}}'
170
+ ```
171
+
172
+ Configuration is saved for your user on this machine, in `mcp.json` under the
173
+ TheGitAI state directory. `ai mcp list` prints the exact path. On Linux and macOS,
174
+ the default is `~/.local/state/thegitai/mcp.json` (or under `XDG_STATE_HOME`);
175
+ on Windows it is `%LOCALAPPDATA%\thegitai\mcp.json`. The file uses an
176
+ `mcpServers` object keyed by server name; each
177
+ entry accepts `disabled` and an optional `timeout` in milliseconds (1,000–300,000,
178
+ default 60,000). The CLI does not load project `.mcp.json` files.
179
+
180
+ **Approvals and limits:** Default mode asks before each MCP call; you can approve
181
+ one call or allow that specific server/tool for the session. `/new` clears these
182
+ grants. Bypass mode approves MCP calls automatically. Plan mode blocks MCP calls,
183
+ including tools a server labels read-only. Adding a local server authorizes
184
+ starting its configured program; only add servers you trust. MCP servers can
185
+ access files or external services using their own permissions, and their changes
186
+ are not covered by TheGitAI's file-edit undo.
187
+
188
+ Server credentials and connection settings stay on your machine. Discovered tool
189
+ names, descriptions and schemas, call arguments, and results are used for your
190
+ model requests. Text, structured results, and images are supported. Audio and
191
+ binary resources are reported as unsupported. Timeouts or disconnects can leave
192
+ an action's outcome unknown; TheGitAI does not automatically repeat MCP calls.
193
+
194
+ This release supports MCP **tools**, up to 128 tools / 100 KiB of definitions per
195
+ turn (about 25,600 estimated tokens). Tool descriptions can contain up to 4,096
196
+ characters. Servers are admitted in configuration order; a server exceeding a
197
+ limit is shown as unavailable in `/mcp` while chat continues with the other tools.
198
+ Invalid server entries are shown individually and can be disabled or removed with
199
+ `ai mcp`. Invalid JSON disables MCP tools for the turn and is shown by `/mcp`;
200
+ repair the file before using configuration commands.
201
+
202
+ MCP results share a 25,000 estimated-token limit across text and structured
203
+ content, enough for a typical browser page snapshot to arrive whole. Larger
204
+ results keep the start and end of their long text blocks, mark the omitted
205
+ middle and report the original size, so the agent can request a narrower query;
206
+ short blocks stay whole. Duplicate JSON text accompanying a structured result is
207
+ included once.
208
+
209
+ The SDK client runtime is bundled with the CLI at reviewed versions; installing
210
+ MCP support adds no runtime npm dependencies.
211
+
212
+ Browser-based OAuth login, standalone MCP resources/prompts, older SSE-only
213
+ servers, and plugin installation are not included. Context7 may require an API key
214
+ or impose rate limits; Playwright requires a supported installed browser.
215
+
216
+ Run `ai mcp --help` for the command reference.
217
+
218
+ ## Chrome browser control
219
+
220
+ The TheGitAI Chrome extension is separately installed. After installing it,
221
+ start `ai` normally and ask about your current tab or a website task. It uses
222
+ your existing Chrome profile, website sessions, and terminal login. Connection
223
+ is automatic; no setup/start command, second sign-in, or manual tab attachment
224
+ is required. Tabs used by the agent join a TheGitAI tab group in an existing
225
+ window. The conversation stays in your terminal. With more than one Chrome
226
+ profile connected, TheGitAI asks which one to use the first time it acts in
227
+ the browser, with the one you used last as the default, and keeps that profile
228
+ for the conversation, including after `/resume`.
229
+
230
+ Default mode asks before using a website and can remember that site for the
231
+ session. Bypass all permissions allows browser actions; Plan mode reads pages
232
+ without clicking, typing, or navigating. Use Stop/Resume in the extension popup to
233
+ pause browser control, or Disable to disconnect it. Chrome's protected pages,
234
+ including browser settings and extension management, cannot be controlled.
235
+
236
+ The extension is currently a development download and is not yet listed in the
237
+ Chrome Web Store. Its version and distribution are independent of this npm
238
+ package. Ubuntu with Chrome is the initial validation target.
239
+
240
+ ## Structured questions
241
+
242
+
243
+ The agent can pause its current turn to ask up to four related questions in one
244
+ form. Use **↑ / ↓**, the displayed option number, or **Enter** to choose, and
245
+ **← / →** to move between questions. **Something else / add details** is the
246
+ numbered final option; focus it and type, paste, or press **Enter** to add a
247
+ single-line note; **Enter** commits it and moves on the way any other choice
248
+ does — to the next question, or to **Submit answers** on the last one — without
249
+ submitting the form. On single-select questions it is mutually exclusive with
250
+ the listed choices, and **↑ / ↓** leaves its editor when the note is empty.
251
+ Multi-select questions toggle choices. The last question has an explicit
252
+ **Submit answers** row. **Esc** closes an open note first and otherwise cancels
253
+ the form; **Ctrl+C** cancels the whole turn.
254
+
255
+ Only the option you are on shows its description, so the whole form — every
256
+ option, the note row, **Submit answers**, and the key hints — stays on screen
257
+ without scrolling. Move between options to read the others.
258
+
259
+ Answers return to the same turn, and completed question/answer records remain
260
+ readable when the session is resumed. Default, Bypass all permissions, and Plan
261
+ modes all support the form; Bypass all permissions does not choose answers for
262
+ you.
40
263
 
41
264
  ## Visible to-do list
42
265
 
@@ -67,6 +290,8 @@ work against it live, and stop it when the task is done, all in one session.
67
290
  read its output inline, **k** to stop it, **Esc** to close.
68
291
  - `/jobs output <id>` prints a job's full output, and `/jobs kill <id>` stops one
69
292
  by id.
293
+ - When waiting for a job is all that's left, the agent can hand control back to
294
+ you and continue automatically once the job finishes on its own.
70
295
  - When you end the session, TheGitAI stops its background jobs for you.
71
296
 
72
297
  Full documentation: <https://thegit.ai/docs>
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,48 +176,77 @@ 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
237
  console.error(chalk.yellow(`⚠ Couldn't reach TheGitAI (${offlineNotice}). Starting with cached settings — it will reconnect on your next message.`));
223
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;
249
+ }
224
250
  const selectedModelId = models.selectServerModel({
225
251
  requestedModelId: sourceSnapshot?.modelId ?? null,
226
252
  cached: cachedModels,
@@ -239,35 +265,38 @@ 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
+ serverModels,
276
+ serverSessionClient,
277
+ session,
278
+ initialPrompt,
279
+ usageText: async () => formatUsageText(await auth.fetchWhoamiResponse({ config: authConfig })),
280
+ });
281
+ if (outcome.signedOut) {
282
+ if (sessionHasUserMessage(session)) {
283
+ saveSessionState(session);
284
+ }
285
+ console.log(chalk.green('\n✓ Logged out.\n'));
286
+ return;
287
+ }
288
+ await saveSessionBoth({ session, serverSessionClient });
289
+ printSessionExit(session);
290
+ }
291
+ finally {
292
+ await disposeSession(session);
293
+ }
269
294
  }
270
295
  main().catch((error) => {
296
+ if (isSignInCancelled(error)) {
297
+ console.error(chalk.dim('\nSign-in cancelled. Nothing was saved.\n'));
298
+ process.exit(130);
299
+ }
271
300
  if (isAuthenticationError(error)) {
272
301
  auth.clearCliAuthConfig();
273
302
  console.error(chalk.red(`\n✖ Error: ${authenticationErrorMessage(error)}\n`));