@thegitai/cli 1.0.0-preview.60 → 1.0.0-preview.62
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/README.md +16 -1
- package/dist/bin/browser-host.js +23 -4
- package/dist/src/api/chat.js +12 -3
- package/dist/src/api/http.js +22 -0
- package/dist/src/api/models.js +13 -0
- package/dist/src/browser/bridge.js +9 -3
- package/dist/src/browser/chrome-profiles.js +73 -0
- package/dist/src/quota-notice.js +31 -4
- package/dist/src/tool-executor.js +3 -0
- package/dist/src/tools/browser.js +265 -34
- package/dist/src/tools/index.js +1 -1
- package/dist/src/ui/repl.js +49 -10
- package/dist/src/ui/tui/build-frame.js +21 -8
- package/dist/src/ui/tui/shell-input.js +1 -1
- package/dist/src/usage.js +20 -0
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -52,6 +52,15 @@ remain in the transcript. Usage updates arrive when a turn starts and after
|
|
|
52
52
|
usage is saved during and at the end of the turn. An exhausted allowance still
|
|
53
53
|
shows `Usage limit reached`.
|
|
54
54
|
|
|
55
|
+
A request your account cannot run right now, such as one for a model your plan
|
|
56
|
+
does not include or one sent after an allowance is used up, is refused before
|
|
57
|
+
it starts. The CLI shows why, with the reset time and, where an upgrade would
|
|
58
|
+
help, a link to the plans page. The refused request is put back in the input
|
|
59
|
+
box so you can switch models and send it again, and it is not saved to the
|
|
60
|
+
session. When your monthly allowance is used up and extra Auto usage is left,
|
|
61
|
+
the Auto options in `/model` keep working on it until it runs out or your plan
|
|
62
|
+
renews; `/usage` shows how much of the extra is left as a percentage.
|
|
63
|
+
|
|
55
64
|
Coding sessions require an interactive terminal on stdin and stdout. Piped
|
|
56
65
|
one-shot prompts are not supported. Saved history is local to the repo and can
|
|
57
66
|
always be viewed or resumed from that computer. Continuing it through the
|
|
@@ -76,6 +85,9 @@ named models follow under **Models**; for one of them, adjust its reasoning
|
|
|
76
85
|
effort with **← / →** in the same panel: **Default / Low / Balanced / Deep**.
|
|
77
86
|
**Enter** saves the selected model's choice for this project; **Esc** cancels.
|
|
78
87
|
Each model remembers its own choice across new and resumed sessions.
|
|
88
|
+
A model your plan does not include stays in the list, grayed out with the
|
|
89
|
+
reason, and **Enter** does not select it. While a paid account is on its extra
|
|
90
|
+
Auto usage, the named models fold into one line until the plan renews.
|
|
79
91
|
The picker shows a model's effort beside its name when it is not Default, and
|
|
80
92
|
the footer always shows it, except on Auto, which sets its own. The footer labels
|
|
81
93
|
agent mode separately as `Mode: ...`; narrow terminals place it on the next
|
|
@@ -222,7 +234,10 @@ start `ai` normally and ask about your current tab or a website task. It uses
|
|
|
222
234
|
your existing Chrome profile, website sessions, and terminal login. Connection
|
|
223
235
|
is automatic; no setup/start command, second sign-in, or manual tab attachment
|
|
224
236
|
is required. Tabs used by the agent join a TheGitAI tab group in an existing
|
|
225
|
-
window. The conversation stays in your terminal.
|
|
237
|
+
window. The conversation stays in your terminal. With more than one Chrome
|
|
238
|
+
profile connected, TheGitAI asks which one to use the first time it acts in
|
|
239
|
+
the browser, with the one you used last as the default, and keeps that profile
|
|
240
|
+
for the conversation, including after `/resume`.
|
|
226
241
|
|
|
227
242
|
Default mode asks before using a website and can remember that site for the
|
|
228
243
|
session. Bypass all permissions allows browser actions; Plan mode reads pages
|
package/dist/bin/browser-host.js
CHANGED
|
@@ -5,6 +5,7 @@ import fs from 'node:fs';
|
|
|
5
5
|
import net from 'node:net';
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { decodeFrames, encodeFrame, fragmentPayload, MAX_FRAME_BYTES } from '../src/browser/framing.js';
|
|
8
|
+
import { chromeProfileLabel } from '../src/browser/chrome-profiles.js';
|
|
8
9
|
import { BROWSER_PROTOCOL_VERSION, browserRuntimeDir, sessionKeyFromRecordFile, sessionSocketPath, socketIsFile, } from '../src/browser/protocol.js';
|
|
9
10
|
const SCAN_INTERVAL_MS = 1000;
|
|
10
11
|
const NUL = String.fromCharCode(0);
|
|
@@ -12,7 +13,9 @@ const sessions = new Map();
|
|
|
12
13
|
const runtimeDir = browserRuntimeDir(process.env);
|
|
13
14
|
let extensionVersion = '';
|
|
14
15
|
let extensionProfileId = '';
|
|
16
|
+
let extensionProfileLabel = '';
|
|
15
17
|
let extensionPlatform = '';
|
|
18
|
+
let extensionLastFocusedAt = 0;
|
|
16
19
|
function log(message) {
|
|
17
20
|
process.stderr.write(`[thegitai-browser-host] ${message}\n`);
|
|
18
21
|
}
|
|
@@ -44,7 +47,11 @@ process.stdin.on('end', () => {
|
|
|
44
47
|
});
|
|
45
48
|
function describeParentBrowser() {
|
|
46
49
|
const cmdline = process.platform === 'win32' ? windowsParentCommandLine() : unixParentCommandLine();
|
|
47
|
-
|
|
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
|
+
};
|
|
48
55
|
}
|
|
49
56
|
function windowsParentCommandLine() {
|
|
50
57
|
const PASS_THROUGH = /^(cmd|conhost|powershell|pwsh|node)\.exe$/i;
|
|
@@ -125,24 +132,36 @@ function identity() {
|
|
|
125
132
|
return {
|
|
126
133
|
key: browserKey(),
|
|
127
134
|
browser: parent.browser,
|
|
128
|
-
profile:
|
|
129
|
-
|
|
130
|
-
|
|
135
|
+
profile: extensionProfileLabel ||
|
|
136
|
+
(parent.profile !== 'Default' || !extensionProfileId
|
|
137
|
+
? parent.profile
|
|
138
|
+
: `profile ${extensionProfileId.slice(0, 6)}`),
|
|
131
139
|
platform: extensionPlatform || process.platform,
|
|
132
140
|
extensionVersion,
|
|
141
|
+
...(extensionLastFocusedAt > 0 ? { lastFocusedAt: extensionLastFocusedAt } : {}),
|
|
133
142
|
};
|
|
134
143
|
}
|
|
135
144
|
function handleExtensionFrame(frame) {
|
|
136
145
|
if (frame?.t === 'hello') {
|
|
137
146
|
extensionVersion = String(frame.extensionVersion ?? '');
|
|
138
147
|
extensionProfileId = String(frame.profileId ?? '');
|
|
148
|
+
extensionProfileLabel = /^[0-9a-f-]{36}$/i.test(extensionProfileId)
|
|
149
|
+
? chromeProfileLabel(extensionProfileId, parent.userDataDir)
|
|
150
|
+
: '';
|
|
139
151
|
extensionPlatform = String(frame.platform ?? '');
|
|
152
|
+
extensionLastFocusedAt = Number(frame.lastFocusedAt) || 0;
|
|
140
153
|
writeToExtension({ t: 'hello', protocol: BROWSER_PROTOCOL_VERSION });
|
|
141
154
|
publishSessions();
|
|
142
155
|
for (const link of sessions.values())
|
|
143
156
|
sendHello(link);
|
|
144
157
|
return;
|
|
145
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
|
+
}
|
|
146
165
|
if (frame?.t === 'res' || frame?.t === 'event') {
|
|
147
166
|
const target = frame.session ? sessions.get(frame.session) : null;
|
|
148
167
|
const { session: _routed, ...rest } = frame;
|
package/dist/src/api/chat.js
CHANGED
|
@@ -8,7 +8,7 @@ import { applySessionSnapshot, saveSessionState, snapshotFromSession, } from '..
|
|
|
8
8
|
import { executeLocalToolCall } from '../tool-executor.js';
|
|
9
9
|
import { saveGeneratedImage } from '../tools/save-generated-image.js';
|
|
10
10
|
import { isUserInputQuestionArray } from './contracts.js';
|
|
11
|
-
import { createTraceContext, gatewayFailureCategory, normalizeServerUrl, QUOTA_EXCEEDED_CODE, readErrorResponse, ServerApiError, transportFailureDetail, } from './http.js';
|
|
11
|
+
import { createTraceContext, gatewayFailureCategory, normalizeServerUrl, QUOTA_EXCEEDED_CODE, PLAN_REQUIRED_CODE, failureDetails, isTurnRefusal, readErrorResponse, ServerApiError, transportFailureDetail, } from './http.js';
|
|
12
12
|
import { createTurnRecovery, fetchTurnAttempt, interruptedStream, isRetryableTurnStatus, isTurnRecoveryExhausted, readTurnChunk, } from './turn-recovery.js';
|
|
13
13
|
import { collectClientEnvironment } from '../client-environment.js';
|
|
14
14
|
import { collectProjectOrientation } from '../project-orientation.js';
|
|
@@ -483,7 +483,10 @@ function terminalFailure(event, traceId) {
|
|
|
483
483
|
return new TurnCancelledError(message);
|
|
484
484
|
}
|
|
485
485
|
if (data.code === QUOTA_EXCEEDED_CODE) {
|
|
486
|
-
return new ServerApiError(message, 429, eventTraceId, QUOTA_EXCEEDED_CODE, data.details
|
|
486
|
+
return new ServerApiError(message, 429, eventTraceId, QUOTA_EXCEEDED_CODE, failureDetails({ error: data.details }));
|
|
487
|
+
}
|
|
488
|
+
if (data.code === PLAN_REQUIRED_CODE) {
|
|
489
|
+
return new ServerApiError(message, 402, eventTraceId, PLAN_REQUIRED_CODE, failureDetails({ error: data.details }));
|
|
487
490
|
}
|
|
488
491
|
return new ChatTurnFailedError(message, typeof data.category === 'string' ? data.category : 'unknown_error', Boolean(data.retryable), eventTraceId, data.snapshot);
|
|
489
492
|
}
|
|
@@ -874,6 +877,9 @@ export async function sendServerUserMessage({ config, session, input, jobFollowU
|
|
|
874
877
|
:
|
|
875
878
|
(gatewayFailureCategory(error) ?? 'unknown_error');
|
|
876
879
|
const partial = error instanceof ChatTurnFailedError ? error.partialSnapshot : undefined;
|
|
880
|
+
const refusedUntouched = !partial && session.history.length === preTurnHistoryLength && isTurnRefusal(error);
|
|
881
|
+
if (refusedUntouched)
|
|
882
|
+
throw error;
|
|
877
883
|
if (partial) {
|
|
878
884
|
applySessionSnapshot(session, partial, { preserveAgentMode: true });
|
|
879
885
|
}
|
|
@@ -964,7 +970,10 @@ function startTurnAttempt({ config, session, turnRequest, input, trace, fetchImp
|
|
|
964
970
|
body: requestBody,
|
|
965
971
|
}, turnSignal);
|
|
966
972
|
if (!response.ok) {
|
|
967
|
-
|
|
973
|
+
const error = await readErrorResponse(response, trace.traceId);
|
|
974
|
+
if (!lastEventId && isTurnRefusal(error))
|
|
975
|
+
serverSettled = true;
|
|
976
|
+
throw error;
|
|
968
977
|
}
|
|
969
978
|
return response;
|
|
970
979
|
};
|
package/dist/src/api/http.js
CHANGED
|
@@ -191,6 +191,8 @@ export function gatewayFailureCategory(error) {
|
|
|
191
191
|
return null;
|
|
192
192
|
if (isQuotaExceededError(error))
|
|
193
193
|
return 'quota_exceeded';
|
|
194
|
+
if (isPlanRequiredError(error))
|
|
195
|
+
return 'plan_required';
|
|
194
196
|
return error.status in GATEWAY_STATUS_MESSAGES ? 'gateway_error' : null;
|
|
195
197
|
}
|
|
196
198
|
export async function readJsonResponse(response) {
|
|
@@ -222,8 +224,21 @@ export function failureDetails(data) {
|
|
|
222
224
|
...(typeof error.percentLeft === 'number'
|
|
223
225
|
? { percentLeft: error.percentLeft }
|
|
224
226
|
: {}),
|
|
227
|
+
...(error.autoAvailable === true ? { autoAvailable: true } : {}),
|
|
228
|
+
...(isWebUrl(error.upgradeUrl) ? { upgradeUrl: error.upgradeUrl } : {}),
|
|
225
229
|
};
|
|
226
230
|
}
|
|
231
|
+
function isWebUrl(value) {
|
|
232
|
+
if (typeof value !== 'string')
|
|
233
|
+
return false;
|
|
234
|
+
try {
|
|
235
|
+
const url = new URL(value);
|
|
236
|
+
return url.protocol === 'https:' || url.protocol === 'http:';
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
227
242
|
export const QUOTA_EXCEEDED_CODE = 'QUOTA_EXCEEDED';
|
|
228
243
|
export function isQuotaExceededError(error) {
|
|
229
244
|
if (!(error instanceof ServerApiError))
|
|
@@ -232,6 +247,13 @@ export function isQuotaExceededError(error) {
|
|
|
232
247
|
return true;
|
|
233
248
|
return error.status === 429 && !error.code;
|
|
234
249
|
}
|
|
250
|
+
export const PLAN_REQUIRED_CODE = 'PLAN_REQUIRED';
|
|
251
|
+
export function isPlanRequiredError(error) {
|
|
252
|
+
return error instanceof ServerApiError && error.code === PLAN_REQUIRED_CODE;
|
|
253
|
+
}
|
|
254
|
+
export function isTurnRefusal(error) {
|
|
255
|
+
return isPlanRequiredError(error) || isQuotaExceededError(error);
|
|
256
|
+
}
|
|
235
257
|
export function isAuthenticationError(error) {
|
|
236
258
|
return error instanceof ServerApiError && error.status === 401;
|
|
237
259
|
}
|
package/dist/src/api/models.js
CHANGED
|
@@ -14,14 +14,19 @@ function sanitizeModelInfo(raw) {
|
|
|
14
14
|
if (!Number.isInteger(id) || id <= 0 || !label || !isCostRating(costRating)) {
|
|
15
15
|
return null;
|
|
16
16
|
}
|
|
17
|
+
const locked = isModelLock(value.locked) ? value.locked : undefined;
|
|
17
18
|
return {
|
|
18
19
|
id,
|
|
19
20
|
label,
|
|
20
21
|
costRating,
|
|
21
22
|
description,
|
|
23
|
+
...(locked ? { locked } : {}),
|
|
22
24
|
...(value.auto === true ? { auto: true } : {}),
|
|
23
25
|
};
|
|
24
26
|
}
|
|
27
|
+
function isModelLock(value) {
|
|
28
|
+
return value === 'plan' || value === 'auto-only';
|
|
29
|
+
}
|
|
25
30
|
function isCostRating(value) {
|
|
26
31
|
return Number.isInteger(value) && value >= 1 && value <= 3;
|
|
27
32
|
}
|
|
@@ -110,6 +115,14 @@ export function selectServerModel({ requestedModelId, cached, serverModels, }) {
|
|
|
110
115
|
}
|
|
111
116
|
throw new Error(`Server does not support model "${requested}".`);
|
|
112
117
|
}
|
|
118
|
+
const unlockedIds = new Set(serverModels.models.filter((model) => !model.locked).map((model) => model.id));
|
|
119
|
+
const firstUnlocked = serverModels.models.find((model) => !model.locked)?.id;
|
|
120
|
+
for (const candidate of [cached?.selectedModelId, serverModels.models[0]?.id, firstUnlocked]) {
|
|
121
|
+
const id = Number(candidate);
|
|
122
|
+
if (Number.isInteger(id) && unlockedIds.has(id)) {
|
|
123
|
+
return id;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
113
126
|
for (const candidate of [cached?.selectedModelId, serverModels.models[0]?.id]) {
|
|
114
127
|
const id = Number(candidate);
|
|
115
128
|
if (Number.isInteger(id) && supportedIds.has(id)) {
|
|
@@ -201,15 +201,21 @@ export function startBrowserBridge({ sessionKey, label, cwd, env = process.env,
|
|
|
201
201
|
return true;
|
|
202
202
|
},
|
|
203
203
|
selectBrowser(key) {
|
|
204
|
-
if (browsers.has(key))
|
|
205
|
-
|
|
204
|
+
if (!browsers.has(key))
|
|
205
|
+
return false;
|
|
206
|
+
selected = key;
|
|
207
|
+
return true;
|
|
206
208
|
},
|
|
207
209
|
onEvent(listener) {
|
|
208
210
|
listeners.add(listener);
|
|
209
211
|
return () => listeners.delete(listener);
|
|
210
212
|
},
|
|
211
213
|
request(op, args = {}, options = {}) {
|
|
212
|
-
const
|
|
214
|
+
const key = options.browser ?? selected;
|
|
215
|
+
const target = key ? browsers.get(key) : null;
|
|
216
|
+
if (!target && options.browser) {
|
|
217
|
+
return Promise.reject(new BrowserBridgeError('The Chrome profile chosen for this conversation is not connected.', 'chosen_profile_missing'));
|
|
218
|
+
}
|
|
213
219
|
if (!target) {
|
|
214
220
|
return Promise.reject(new BrowserBridgeError('No browser is connected to this session.', 'not_connected'));
|
|
215
221
|
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { EXTENSION_IDS } from './protocol.js';
|
|
4
|
+
export function chromeUserDataDirs(userDataDir = '') {
|
|
5
|
+
if (userDataDir)
|
|
6
|
+
return [userDataDir];
|
|
7
|
+
const home = process.env.HOME || process.env.USERPROFILE || '';
|
|
8
|
+
if (process.platform === 'win32') {
|
|
9
|
+
const local = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
|
|
10
|
+
return [
|
|
11
|
+
['Google', 'Chrome'],
|
|
12
|
+
['Google', 'Chrome Beta'],
|
|
13
|
+
['Chromium'],
|
|
14
|
+
['BraveSoftware', 'Brave-Browser'],
|
|
15
|
+
['Microsoft', 'Edge'],
|
|
16
|
+
].map((parts) => path.join(local, ...parts, 'User Data'));
|
|
17
|
+
}
|
|
18
|
+
if (process.platform === 'darwin') {
|
|
19
|
+
const support = path.join(home, 'Library', 'Application Support');
|
|
20
|
+
return ['Google/Chrome', 'Google/Chrome Beta', 'Chromium', 'BraveSoftware/Brave-Browser', 'Microsoft Edge'].map((dir) => path.join(support, dir));
|
|
21
|
+
}
|
|
22
|
+
const config = process.env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
23
|
+
return [
|
|
24
|
+
...['google-chrome', 'google-chrome-beta', 'google-chrome-unstable', 'chromium', 'BraveSoftware/Brave-Browser', 'microsoft-edge'].map((dir) => path.join(config, dir)),
|
|
25
|
+
path.join(home, 'snap', 'chromium', 'common', 'chromium'),
|
|
26
|
+
];
|
|
27
|
+
}
|
|
28
|
+
const UUID_TAIL = '[0-9a-f]{0,8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
|
|
29
|
+
export function chromeProfileLabel(idOrPrefix, userDataDir = '') {
|
|
30
|
+
const wanted = String(idOrPrefix ?? '').toLowerCase();
|
|
31
|
+
if (!/^[0-9a-f]{6}/.test(wanted) || !/^[0-9a-f-]+$/.test(wanted))
|
|
32
|
+
return '';
|
|
33
|
+
const pattern = wanted.length >= 36 ? null : new RegExp(`${wanted}${UUID_TAIL.replace('{0,8}', `{${8 - Math.min(wanted.length, 8)}}`)}`);
|
|
34
|
+
for (const dataDir of chromeUserDataDirs(userDataDir)) {
|
|
35
|
+
let profiles;
|
|
36
|
+
try {
|
|
37
|
+
profiles = JSON.parse(fs.readFileSync(path.join(dataDir, 'Local State'), 'utf8'))?.profile?.info_cache ?? {};
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
for (const [profileDir, info] of Object.entries(profiles)) {
|
|
43
|
+
for (const extensionId of EXTENSION_IDS) {
|
|
44
|
+
const store = path.join(dataDir, profileDir, 'Local Extension Settings', extensionId);
|
|
45
|
+
let files;
|
|
46
|
+
try {
|
|
47
|
+
files = fs.readdirSync(store);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
for (const file of files) {
|
|
53
|
+
if (!/\.(log|ldb)$/.test(file))
|
|
54
|
+
continue;
|
|
55
|
+
try {
|
|
56
|
+
const full = path.join(store, file);
|
|
57
|
+
if (fs.statSync(full).size > 8 * 1024 * 1024)
|
|
58
|
+
continue;
|
|
59
|
+
const text = fs.readFileSync(full).toString('latin1');
|
|
60
|
+
if (pattern ? !pattern.test(text) : !text.includes(wanted))
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const name = String(info?.name ?? '').trim().slice(0, 60);
|
|
67
|
+
return name ? `${name} (${profileDir})` : profileDir;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return '';
|
|
73
|
+
}
|
package/dist/src/quota-notice.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isQuotaExceededError, ServerApiError } from './api/http.js';
|
|
1
|
+
import { isPlanRequiredError, isQuotaExceededError, ServerApiError } from './api/http.js';
|
|
2
2
|
import { USAGE_WINDOWS, formatUtcMinute, usageWindowLabel } from './usage.js';
|
|
3
3
|
export function buildQuotaNotice(error) {
|
|
4
4
|
if (!(error instanceof ServerApiError) || !isQuotaExceededError(error)) {
|
|
@@ -7,21 +7,48 @@ export function buildQuotaNotice(error) {
|
|
|
7
7
|
const label = usageWindowLabel(String(error.details.window ?? ''));
|
|
8
8
|
const inSentence = label.toLowerCase();
|
|
9
9
|
const resetsAt = error.details.resetsAt ?? null;
|
|
10
|
+
const reset = resetsAt ? formatUtcMinute(resetsAt) : '';
|
|
11
|
+
const knownReset = reset && reset !== 'unknown' ? reset : '';
|
|
12
|
+
if (error.details.autoAvailable) {
|
|
13
|
+
return {
|
|
14
|
+
title: 'Usage limit reached',
|
|
15
|
+
body: [
|
|
16
|
+
knownReset
|
|
17
|
+
? `You've used your monthly allowance. Auto options in /model still work on a limited extra allowance until it runs out or your plan renews at ${knownReset}.`
|
|
18
|
+
: "You've used your monthly allowance. Auto options in /model still work on a limited extra allowance until it runs out or your plan renews.",
|
|
19
|
+
'Run /usage for details.',
|
|
20
|
+
].join('\n'),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
10
23
|
const lines = [];
|
|
11
24
|
if (label) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
? `You've used your ${inSentence} limit. It resets at ${reset}.`
|
|
25
|
+
lines.push(knownReset
|
|
26
|
+
? `You've used your ${inSentence} limit. It resets at ${knownReset}.`
|
|
15
27
|
: `You've used your ${inSentence} limit.`);
|
|
16
28
|
}
|
|
17
29
|
else {
|
|
18
30
|
lines.push(firstMessageLine(error));
|
|
19
31
|
}
|
|
32
|
+
if (error.details.upgradeUrl) {
|
|
33
|
+
lines.push(`Upgrade for more usage at ${error.details.upgradeUrl}`);
|
|
34
|
+
}
|
|
20
35
|
lines.push(label
|
|
21
36
|
? `Run /usage to see your ${otherWindowNames(label)} windows.`
|
|
22
37
|
: 'Run /usage to see your remaining usage.');
|
|
23
38
|
return { title: 'Usage limit reached', body: lines.join('\n') };
|
|
24
39
|
}
|
|
40
|
+
export function buildPlanRequiredNotice(error) {
|
|
41
|
+
if (!(error instanceof ServerApiError) || !isPlanRequiredError(error)) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
title: 'Plus or Pro model',
|
|
46
|
+
body: firstMessageLine(error).replace(/\.\s+(?=Upgrade at )/, '.\n'),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export function buildRefusalNotice(error) {
|
|
50
|
+
return buildPlanRequiredNotice(error) ?? buildQuotaNotice(error);
|
|
51
|
+
}
|
|
25
52
|
function otherWindowNames(usedLabel) {
|
|
26
53
|
const names = USAGE_WINDOWS.map(([name]) => name)
|
|
27
54
|
.filter((name) => name !== usedLabel)
|
|
@@ -256,6 +256,9 @@ export async function executeLocalToolCall(session, call) {
|
|
|
256
256
|
grants: session.grants,
|
|
257
257
|
requestPermission: session.requestPermission,
|
|
258
258
|
requestSudoPassword: session.requestSudoPassword,
|
|
259
|
+
requestUserInput: session.requestUserInput
|
|
260
|
+
? (request) => session.requestUserInput(request, session.turnAbortSignal)
|
|
261
|
+
: null,
|
|
259
262
|
onStatus: session.onStatus,
|
|
260
263
|
editJournal: session.clientState.editJournal,
|
|
261
264
|
safety: session.clientState.safety,
|
|
@@ -2,8 +2,10 @@ import fs from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { normalizeProjectRelativePath } from '../artifact-policy.js';
|
|
4
4
|
import { BrowserBridgeError } from '../browser/bridge.js';
|
|
5
|
+
import { chromeProfileLabel } from '../browser/chrome-profiles.js';
|
|
5
6
|
import { storeSessionImageBytes } from '../core/session-image-store.js';
|
|
6
7
|
import { browserAvailability, drainBrowserEvents, ensureBrowserBridge, resyncBrowserBridge, } from '../browser/session-bridge.js';
|
|
8
|
+
import { getClientStateDir } from '../client-state.js';
|
|
7
9
|
import { ensurePermission, originForUrl } from '../permissions.js';
|
|
8
10
|
const READ_TIMEOUT_MS = 20000;
|
|
9
11
|
const NAVIGATE_TIMEOUT_MS = 45000;
|
|
@@ -40,23 +42,202 @@ async function waitForBrowser(options, timeoutMs) {
|
|
|
40
42
|
}
|
|
41
43
|
return browserAvailability(options);
|
|
42
44
|
}
|
|
43
|
-
async function notConnected(context) {
|
|
45
|
+
async function notConnected(context, { allowUnchosen = false, tabId } = {}) {
|
|
44
46
|
const options = { cwd: context.rootDir, env: context.env };
|
|
45
47
|
const status = ensureBrowserBridge(options).status();
|
|
46
|
-
if (status.connected)
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
if (!status.connected) {
|
|
49
|
+
if (status.everConnected)
|
|
50
|
+
resyncBrowserBridge(options);
|
|
51
|
+
const availability = await waitForBrowser(options, DISCOVERY_TIMEOUT_MS);
|
|
52
|
+
if (!availability.connected) {
|
|
53
|
+
return {
|
|
54
|
+
ok: false,
|
|
55
|
+
connected: false,
|
|
56
|
+
browserErrorCode: 'not_connected',
|
|
57
|
+
error: `TheGitAI is not connected to a browser. ${availability.hint ?? ''}`.trim(),
|
|
58
|
+
failureCategory: 'external_service',
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return allowUnchosen ? { ok: true } : profileChosen(context, Number(tabId));
|
|
63
|
+
}
|
|
64
|
+
const resolvedProfileNames = new Map();
|
|
65
|
+
function profileLabel(profile) {
|
|
66
|
+
const unnamed = /^profile ([0-9a-f]{6})$/.exec(profile);
|
|
67
|
+
if (!unnamed)
|
|
68
|
+
return profile;
|
|
69
|
+
if (!resolvedProfileNames.has(unnamed[1])) {
|
|
70
|
+
resolvedProfileNames.set(unnamed[1], chromeProfileLabel(unnamed[1]) || profile);
|
|
71
|
+
}
|
|
72
|
+
return resolvedProfileNames.get(unnamed[1]);
|
|
73
|
+
}
|
|
74
|
+
function describeBrowsers(availability) {
|
|
75
|
+
const latest = Math.max(0, ...availability.browsers.map((browser) => browser.lastFocusedAt ?? 0));
|
|
76
|
+
return [...availability.browsers]
|
|
77
|
+
.sort((a, b) => (b.lastFocusedAt ?? 0) - (a.lastFocusedAt ?? 0))
|
|
78
|
+
.map((browser) => ({
|
|
79
|
+
key: browser.key,
|
|
80
|
+
name: `${browser.browser} - ${profileLabel(browser.profile)}`,
|
|
81
|
+
extensionVersion: browser.extensionVersion,
|
|
82
|
+
...(latest > 0 && browser.lastFocusedAt === latest ? { lastUsed: true } : {}),
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
85
|
+
const BROWSER_CHOICES_FILE = 'browser-choices.json';
|
|
86
|
+
const BROWSER_CHOICES_KEPT = 200;
|
|
87
|
+
const sessionProfiles = new Map();
|
|
88
|
+
function readBrowserChoices(env) {
|
|
89
|
+
try {
|
|
90
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(getClientStateDir(env), BROWSER_CHOICES_FILE), 'utf8'));
|
|
91
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return {};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function profileChoiceFor(context) {
|
|
98
|
+
const session = context.sessionId ?? '';
|
|
99
|
+
const remembered = sessionProfiles.get(session);
|
|
100
|
+
if (remembered)
|
|
101
|
+
return remembered;
|
|
102
|
+
const saved = session ? readBrowserChoices(context.env)[session] : undefined;
|
|
103
|
+
if (!saved?.key)
|
|
104
|
+
return null;
|
|
105
|
+
const choice = { key: String(saved.key), name: String(saved.name ?? saved.key), at: Number(saved.at) || 0 };
|
|
106
|
+
sessionProfiles.set(session, choice);
|
|
107
|
+
return choice;
|
|
108
|
+
}
|
|
109
|
+
function recordProfileChoice(context, browser) {
|
|
110
|
+
const session = context.sessionId ?? '';
|
|
111
|
+
const choice = { key: browser.key, name: browser.name, at: Date.now() };
|
|
112
|
+
sessionProfiles.set(session, choice);
|
|
113
|
+
if (!session)
|
|
114
|
+
return;
|
|
115
|
+
try {
|
|
116
|
+
const choices = readBrowserChoices(context.env);
|
|
117
|
+
choices[session] = choice;
|
|
118
|
+
const kept = Object.fromEntries(Object.entries(choices)
|
|
119
|
+
.sort(([, a], [, b]) => (b?.at ?? 0) - (a?.at ?? 0))
|
|
120
|
+
.slice(0, BROWSER_CHOICES_KEPT));
|
|
121
|
+
const dir = getClientStateDir(context.env);
|
|
122
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
123
|
+
fs.writeFileSync(path.join(dir, BROWSER_CHOICES_FILE), JSON.stringify(kept), { mode: 0o600 });
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async function askForProfile(context, listed, suggested) {
|
|
129
|
+
if (!context.requestUserInput)
|
|
130
|
+
return null;
|
|
131
|
+
const recommended = suggested ?? listed.find((browser) => browser.lastUsed) ?? listed[0];
|
|
132
|
+
const ordered = [recommended, ...listed.filter((browser) => browser.key !== recommended.key)];
|
|
133
|
+
const result = await context.requestUserInput({
|
|
134
|
+
questions: [
|
|
135
|
+
{
|
|
136
|
+
id: 'chrome_profile',
|
|
137
|
+
header: 'Chrome profile',
|
|
138
|
+
question: 'Which Chrome profile should TheGitAI use for this conversation?',
|
|
139
|
+
options: ordered.map((browser, index) => ({
|
|
140
|
+
id: `profile_${index}`,
|
|
141
|
+
label: browser.name,
|
|
142
|
+
description: browser.lastUsed ? 'The profile you used last' : 'Connected',
|
|
143
|
+
})),
|
|
144
|
+
multiSelect: false,
|
|
145
|
+
recommendedOptionId: 'profile_0',
|
|
146
|
+
},
|
|
147
|
+
],
|
|
148
|
+
});
|
|
149
|
+
if (result?.status !== 'submitted')
|
|
150
|
+
return 'cancelled';
|
|
151
|
+
const answer = result.answers?.chrome_profile;
|
|
152
|
+
const option = /^profile_(\d+)$/.exec(answer?.selectedOptionIds?.[0] ?? '');
|
|
153
|
+
if (option && ordered[Number(option[1])])
|
|
154
|
+
return ordered[Number(option[1])];
|
|
155
|
+
const text = String(answer?.customText ?? '').trim();
|
|
156
|
+
return text ? { text } : 'cancelled';
|
|
157
|
+
}
|
|
158
|
+
async function useProfile(context, listed, suggested) {
|
|
159
|
+
const bridge = ensureBrowserBridge({ cwd: context.rootDir, env: context.env });
|
|
160
|
+
const choice = listed.length === 1 ? listed[0] : await askForProfile(context, listed, suggested);
|
|
161
|
+
if (choice === 'cancelled') {
|
|
162
|
+
return {
|
|
163
|
+
ok: false,
|
|
164
|
+
browserErrorCode: 'profile_question_cancelled',
|
|
165
|
+
error: 'The user closed the question about which Chrome profile to use, so nothing was done.',
|
|
166
|
+
failureCategory: 'user_declined',
|
|
167
|
+
browsers: listed,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
if (choice && typeof choice === 'object' && 'text' in choice) {
|
|
171
|
+
return {
|
|
172
|
+
ok: false,
|
|
173
|
+
browserErrorCode: 'profile_answered_in_text',
|
|
174
|
+
error: `Asked which Chrome profile to use, the user answered in their own words instead of picking one: "${choice.text.slice(0, 300)}". Nothing was done.`,
|
|
175
|
+
failureCategory: 'user_declined',
|
|
176
|
+
browsers: listed,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const picked = choice ?? suggested;
|
|
180
|
+
if (!picked) {
|
|
181
|
+
return {
|
|
182
|
+
ok: false,
|
|
183
|
+
browserErrorCode: 'browser_not_chosen',
|
|
184
|
+
error: `${listed.length} Chrome profiles are connected and none has been chosen for this conversation.`,
|
|
185
|
+
failureCategory: 'invalid_argument',
|
|
186
|
+
browsers: listed,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
recordProfileChoice(context, picked);
|
|
190
|
+
if (!bridge.selectBrowser(picked.key)) {
|
|
191
|
+
return {
|
|
192
|
+
ok: false,
|
|
193
|
+
browserErrorCode: 'chosen_profile_missing',
|
|
194
|
+
error: `The Chrome profile chosen for this conversation, ${picked.name}, is not connected.`,
|
|
195
|
+
failureCategory: 'external_service',
|
|
196
|
+
browsers: describeBrowsers(browserAvailability({ cwd: context.rootDir, env: context.env })),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
return { ok: true };
|
|
200
|
+
}
|
|
201
|
+
async function profilesHoldingTab(context, listed, tabId) {
|
|
202
|
+
const bridge = ensureBrowserBridge({ cwd: context.rootDir, env: context.env });
|
|
203
|
+
const holders = await Promise.all(listed.map(async (browser) => {
|
|
204
|
+
try {
|
|
205
|
+
const result = await bridge.request('context', { includeAll: true }, { timeoutMs: READ_TIMEOUT_MS, browser: browser.key });
|
|
206
|
+
const tabs = Array.isArray(result?.tabs) ? result.tabs : [];
|
|
207
|
+
return tabs.some((tab) => Number(tab?.tabId) === tabId) ? browser : null;
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
}));
|
|
213
|
+
return holders.filter((browser) => browser !== null);
|
|
214
|
+
}
|
|
215
|
+
async function profileChosen(context, tabId = NaN) {
|
|
216
|
+
const options = { cwd: context.rootDir, env: context.env };
|
|
217
|
+
const listed = describeBrowsers(browserAvailability(options));
|
|
218
|
+
const choice = profileChoiceFor(context);
|
|
219
|
+
if (choice) {
|
|
220
|
+
if (ensureBrowserBridge(options).selectBrowser(choice.key))
|
|
221
|
+
return { ok: true };
|
|
222
|
+
return {
|
|
223
|
+
ok: false,
|
|
224
|
+
browserErrorCode: 'chosen_profile_missing',
|
|
225
|
+
error: `The Chrome profile chosen for this conversation, ${choice.name}, is not connected.`,
|
|
226
|
+
failureCategory: 'external_service',
|
|
227
|
+
browsers: listed,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
if (!listed.length)
|
|
52
231
|
return { ok: true };
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
232
|
+
if (listed.length > 1 && Number.isInteger(tabId)) {
|
|
233
|
+
const holders = await profilesHoldingTab(context, listed, tabId);
|
|
234
|
+
if (holders.length === 1) {
|
|
235
|
+
ensureBrowserBridge(options).selectBrowser(holders[0].key);
|
|
236
|
+
recordProfileChoice(context, holders[0]);
|
|
237
|
+
return { ok: true };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return useProfile(context, listed);
|
|
60
241
|
}
|
|
61
242
|
function bridgeFailure(error) {
|
|
62
243
|
const code = error instanceof BrowserBridgeError ? error.code : 'browser_error';
|
|
@@ -70,12 +251,15 @@ function bridgeFailure(error) {
|
|
|
70
251
|
}
|
|
71
252
|
async function call(context, op, args = {}, timeoutMs = READ_TIMEOUT_MS) {
|
|
72
253
|
const bridge = ensureBrowserBridge({ cwd: context.rootDir, env: context.env });
|
|
73
|
-
return bridge.request(op, args, { timeoutMs });
|
|
254
|
+
return bridge.request(op, args, { timeoutMs, browser: profileChoiceFor(context)?.key });
|
|
74
255
|
}
|
|
75
256
|
async function currentTab(context, tabId) {
|
|
76
257
|
const result = await call(context, 'context', { includeAll: true });
|
|
77
258
|
const tabs = Array.isArray(result?.tabs) ? result.tabs : [];
|
|
78
|
-
|
|
259
|
+
const tab = tabs.find((entry) => Number(entry.tabId) === tabId);
|
|
260
|
+
if (!tab)
|
|
261
|
+
return null;
|
|
262
|
+
return { ...tab, url: String(tab.url ?? '').replace(/…+$/, '') };
|
|
79
263
|
}
|
|
80
264
|
async function ensureSiteAllowed(context, { url, tool, summary, }) {
|
|
81
265
|
const origin = originForUrl(String(url ?? ''));
|
|
@@ -105,33 +289,80 @@ function attachEvents(result) {
|
|
|
105
289
|
browserNotices: notable.map((entry) => String(entry.data?.message ?? `Browser ${entry.event}.`)),
|
|
106
290
|
};
|
|
107
291
|
}
|
|
108
|
-
export async function browserGateway(context) {
|
|
109
|
-
const guard = await notConnected(context);
|
|
292
|
+
export async function browserGateway(context, args = {}) {
|
|
293
|
+
const guard = await notConnected(context, { allowUnchosen: true });
|
|
110
294
|
if (guard.ok === false)
|
|
111
295
|
return guard;
|
|
112
|
-
const
|
|
296
|
+
const options = { cwd: context.rootDir, env: context.env };
|
|
297
|
+
const requested = String(args.browser ?? '').trim();
|
|
298
|
+
const listed = describeBrowsers(browserAvailability(options));
|
|
299
|
+
if (requested) {
|
|
300
|
+
const wanted = requested.toLowerCase();
|
|
301
|
+
const partial = listed.filter((browser) => browser.name.toLowerCase().includes(wanted));
|
|
302
|
+
const match = listed.find((browser) => browser.key === requested) ??
|
|
303
|
+
listed.find((browser) => browser.name.toLowerCase() === wanted) ??
|
|
304
|
+
listed.find((browser) => browser.name.toLowerCase().endsWith(`(${wanted})`)) ??
|
|
305
|
+
(partial.length === 1 ? partial[0] : undefined);
|
|
306
|
+
if (!match) {
|
|
307
|
+
return {
|
|
308
|
+
ok: false,
|
|
309
|
+
error: partial.length > 1
|
|
310
|
+
? `"${requested}" matches more than one connected browser. Use a key from browsers.`
|
|
311
|
+
: `No connected browser matches "${requested}". Use a key from browsers.`,
|
|
312
|
+
failureCategory: 'invalid_argument',
|
|
313
|
+
browsers: listed,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
if (profileChoiceFor(context)?.key !== match.key) {
|
|
317
|
+
const chosen = await useProfile(context, listed, match);
|
|
318
|
+
if (chosen.ok === false)
|
|
319
|
+
return chosen;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
else if (listed.length === 1 && !profileChoiceFor(context)) {
|
|
323
|
+
await useProfile(context, listed);
|
|
324
|
+
}
|
|
325
|
+
const availability = browserAvailability(options);
|
|
113
326
|
const platform = availability.browsers[0]?.platform ?? process.platform;
|
|
327
|
+
const choice = profileChoiceFor(context);
|
|
328
|
+
const connectedChoice = choice && availability.browsers.some((browser) => browser.key === choice.key) ? choice : null;
|
|
114
329
|
return {
|
|
115
330
|
ok: true,
|
|
116
331
|
connected: true,
|
|
117
|
-
browsers: availability
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
extensionVersion: browser.extensionVersion,
|
|
121
|
-
})),
|
|
122
|
-
selected: availability.selected,
|
|
332
|
+
browsers: describeBrowsers(availability),
|
|
333
|
+
selected: connectedChoice?.key ?? null,
|
|
334
|
+
choiceNeeded: !connectedChoice,
|
|
123
335
|
shortcutModifier: platform === 'darwin' ? 'cmd' : 'ctrl',
|
|
124
336
|
platform,
|
|
125
337
|
};
|
|
126
338
|
}
|
|
127
339
|
export async function browserTabs(context, args) {
|
|
128
|
-
const
|
|
340
|
+
const includeAll = args.include_all === true || args.includeAll === true;
|
|
341
|
+
const guard = await notConnected(context, { allowUnchosen: includeAll });
|
|
129
342
|
if (guard.ok === false)
|
|
130
343
|
return guard;
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
344
|
+
const options = { cwd: context.rootDir, env: context.env };
|
|
345
|
+
const availability = browserAvailability(options);
|
|
346
|
+
if (includeAll && availability.browsers.length > 1) {
|
|
347
|
+
const bridge = ensureBrowserBridge(options);
|
|
348
|
+
const profiles = await Promise.all(describeBrowsers(availability).map(async (browser) => {
|
|
349
|
+
try {
|
|
350
|
+
const result = await bridge.request('context', { includeAll: true }, { timeoutMs: READ_TIMEOUT_MS, browser: browser.key });
|
|
351
|
+
return { ...browser, selected: browser.key === profileChoiceFor(context)?.key, ...result };
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
return { ...browser, selected: browser.key === profileChoiceFor(context)?.key, error: String(error?.message ?? error) };
|
|
355
|
+
}
|
|
356
|
+
}));
|
|
357
|
+
const choice = profileChoiceFor(context);
|
|
358
|
+
return attachEvents({
|
|
359
|
+
ok: true,
|
|
360
|
+
choiceNeeded: !choice || !availability.browsers.some((browser) => browser.key === choice.key),
|
|
361
|
+
profiles,
|
|
134
362
|
});
|
|
363
|
+
}
|
|
364
|
+
try {
|
|
365
|
+
const result = await call(context, 'context', { includeAll });
|
|
135
366
|
return attachEvents({ ok: true, ...result });
|
|
136
367
|
}
|
|
137
368
|
catch (error) {
|
|
@@ -164,7 +395,7 @@ export async function browserTabNew(context, args = {}) {
|
|
|
164
395
|
}
|
|
165
396
|
}
|
|
166
397
|
export async function browserTabClose(context, args) {
|
|
167
|
-
const guard = await notConnected(context);
|
|
398
|
+
const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
|
|
168
399
|
if (guard.ok === false)
|
|
169
400
|
return guard;
|
|
170
401
|
const tabId = Number(args.tabId ?? args.tab_id);
|
|
@@ -179,7 +410,7 @@ export async function browserTabClose(context, args) {
|
|
|
179
410
|
}
|
|
180
411
|
}
|
|
181
412
|
export async function browserNavigate(context, args) {
|
|
182
|
-
const guard = await notConnected(context);
|
|
413
|
+
const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
|
|
183
414
|
if (guard.ok === false)
|
|
184
415
|
return guard;
|
|
185
416
|
const url = String(args.url ?? '').trim();
|
|
@@ -212,7 +443,7 @@ export async function browserNavigate(context, args) {
|
|
|
212
443
|
}
|
|
213
444
|
}
|
|
214
445
|
async function gatedTabCall(context, { tool, op, args, summary, timeoutMs = READ_TIMEOUT_MS, }) {
|
|
215
|
-
const guard = await notConnected(context);
|
|
446
|
+
const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
|
|
216
447
|
if (guard.ok === false)
|
|
217
448
|
return guard;
|
|
218
449
|
const tabId = Number(args.tabId ?? args.tab_id);
|
|
@@ -472,7 +703,7 @@ export function browserResize(context, args) {
|
|
|
472
703
|
});
|
|
473
704
|
}
|
|
474
705
|
export async function browserFileUpload(context, args) {
|
|
475
|
-
const guard = await notConnected(context);
|
|
706
|
+
const guard = await notConnected(context, { tabId: args.tabId ?? args.tab_id });
|
|
476
707
|
if (guard.ok === false)
|
|
477
708
|
return guard;
|
|
478
709
|
const ref = String(args.ref ?? '').trim();
|
|
@@ -593,7 +824,7 @@ const BATCH_TOOLS = {
|
|
|
593
824
|
browser_downloads: browserDownloads,
|
|
594
825
|
};
|
|
595
826
|
export async function browserBatch(context, args) {
|
|
596
|
-
const guard = await notConnected(context);
|
|
827
|
+
const guard = await notConnected(context, { tabId: (Array.isArray(args.actions) ? args.actions[0]?.input?.tabId : undefined) });
|
|
597
828
|
if (guard.ok === false)
|
|
598
829
|
return guard;
|
|
599
830
|
const actions = Array.isArray(args.actions) ? args.actions : [];
|
package/dist/src/tools/index.js
CHANGED
|
@@ -44,7 +44,7 @@ export const TOOL_MAP = {
|
|
|
44
44
|
shell_job_kill: shellJobKill,
|
|
45
45
|
update_todos: updateTodos,
|
|
46
46
|
analyze_image: (context, args) => readImageFile(context, args),
|
|
47
|
-
browser: (context) => browserGateway(context),
|
|
47
|
+
browser: (context, args) => browserGateway(context, args),
|
|
48
48
|
browser_tabs: browserTabs,
|
|
49
49
|
browser_tab_new: (context, args) => browserTabNew(context, args),
|
|
50
50
|
browser_tab_close: browserTabClose,
|
package/dist/src/ui/repl.js
CHANGED
|
@@ -26,7 +26,7 @@ import { cancelActiveCommand } from '../executor.js';
|
|
|
26
26
|
import { isTurnFailureMarker } from '../turn-failure-marker.js';
|
|
27
27
|
import { clearCliAuthConfig, logoutFromServer, } from '../api/auth.js';
|
|
28
28
|
import { authenticationErrorMessage, isAuthenticationError, } from '../api/http.js';
|
|
29
|
-
import {
|
|
29
|
+
import { buildRefusalNotice } from '../quota-notice.js';
|
|
30
30
|
import { createUsageNoticeTracker } from '../usage-notice.js';
|
|
31
31
|
import { createUserInputPromptState, formatUserInputTranscript, } from './tui/user-input.js';
|
|
32
32
|
import { setCommandOutputHook, withTuiMode } from '../runtime-mode.js';
|
|
@@ -1356,23 +1356,51 @@ export function busyElapsedSeconds(state, nowMs) {
|
|
|
1356
1356
|
return Math.floor((busyElapsedMs(state, nowMs) ?? 0) / 1000);
|
|
1357
1357
|
}
|
|
1358
1358
|
export function buildModelPickerOptions(currentModelId, serverModels) {
|
|
1359
|
+
const listed = serverModels.filter((model) => model.locked !== 'auto-only');
|
|
1359
1360
|
return [
|
|
1360
|
-
...
|
|
1361
|
-
...
|
|
1361
|
+
...listed.filter((model) => model.auto),
|
|
1362
|
+
...listed.filter((model) => !model.auto),
|
|
1362
1363
|
].map((model) => ({
|
|
1363
1364
|
id: model.id,
|
|
1364
1365
|
label: model.auto ? autoOptionLabel(model.label) : model.label,
|
|
1365
1366
|
publicId: model.id,
|
|
1366
1367
|
costRating: model.costRating,
|
|
1367
1368
|
current: model.id === currentModelId,
|
|
1368
|
-
disabled:
|
|
1369
|
+
disabled: Boolean(model.locked),
|
|
1369
1370
|
group: model.auto ? 'auto' : 'models',
|
|
1370
|
-
note: model.description,
|
|
1371
|
+
note: model.locked ? MODEL_LOCK_NOTES[model.locked] : model.description,
|
|
1371
1372
|
}));
|
|
1372
1373
|
}
|
|
1374
|
+
export function pausedModelCount(serverModels) {
|
|
1375
|
+
return serverModels.filter((model) => model.locked === 'auto-only').length;
|
|
1376
|
+
}
|
|
1377
|
+
export async function modelsForSwitch(requestedModelId, cached, refresh) {
|
|
1378
|
+
try {
|
|
1379
|
+
return await refresh();
|
|
1380
|
+
}
|
|
1381
|
+
catch (error) {
|
|
1382
|
+
if (cached.models.some((model) => model.id === requestedModelId))
|
|
1383
|
+
return cached;
|
|
1384
|
+
throw error;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
export const PAUSED_MODELS_NOTE = 'Named models return when your plan renews.';
|
|
1373
1388
|
function autoOptionLabel(label) {
|
|
1374
1389
|
return /^Auto \((.+)\)$/.exec(label)?.[1] ?? label;
|
|
1375
1390
|
}
|
|
1391
|
+
const MODEL_LOCK_NOTES = {
|
|
1392
|
+
plan: 'Needs a Plus or Pro plan',
|
|
1393
|
+
'auto-only': 'Auto options only until your plan renews',
|
|
1394
|
+
};
|
|
1395
|
+
export function modelLockMessage(model) {
|
|
1396
|
+
if (model.locked === 'auto-only') {
|
|
1397
|
+
return `Only Auto options run until your plan renews. Pick one of them instead of ${pickerLabel(model.label)}.`;
|
|
1398
|
+
}
|
|
1399
|
+
return `${pickerLabel(model.label)} needs a Plus or Pro plan.`;
|
|
1400
|
+
}
|
|
1401
|
+
function pickerLabel(label) {
|
|
1402
|
+
return label.replace(/\s*\([^)]*\)\s*$/, '');
|
|
1403
|
+
}
|
|
1376
1404
|
function getDefaultModelPickerIndex(currentModelId, serverModels) {
|
|
1377
1405
|
const options = buildModelPickerOptions(currentModelId, serverModels);
|
|
1378
1406
|
const currentIndex = options.findIndex((option) => option.id === currentModelId);
|
|
@@ -2090,11 +2118,11 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
|
|
|
2090
2118
|
}));
|
|
2091
2119
|
};
|
|
2092
2120
|
const switchToModel = async (modelId, effort) => {
|
|
2093
|
-
const
|
|
2094
|
-
const fresh = currentServerModels.models.some((model) => model.id === requested)
|
|
2095
|
-
? currentServerModels
|
|
2096
|
-
: await refreshServerModels();
|
|
2121
|
+
const fresh = await modelsForSwitch(Number(modelId), currentServerModels, refreshServerModels);
|
|
2097
2122
|
const selected = models.validateServerModel(modelId, fresh);
|
|
2123
|
+
const lockedModel = fresh.models.find((model) => model.id === selected && model.locked);
|
|
2124
|
+
if (lockedModel)
|
|
2125
|
+
throw new Error(modelLockMessage(lockedModel));
|
|
2098
2126
|
if (effort !== undefined) {
|
|
2099
2127
|
saveProjectModelEffort(session.rootDir, selected, effort, authConfig.serverUrl, session.env);
|
|
2100
2128
|
}
|
|
@@ -2231,6 +2259,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
|
|
|
2231
2259
|
const options = buildModelPickerOptions(current.currentModelId, current.serverModels);
|
|
2232
2260
|
const selectedIndex = Math.min(current.modelPickerIndex, Math.max(options.length - 1, 0));
|
|
2233
2261
|
const selected = options[selectedIndex];
|
|
2262
|
+
const lockedModel = selected?.disabled
|
|
2263
|
+
? current.serverModels.find((model) => model.id === selected.id)
|
|
2264
|
+
: undefined;
|
|
2265
|
+
if (lockedModel) {
|
|
2266
|
+
showTransientStatus(modelLockMessage(lockedModel));
|
|
2267
|
+
return;
|
|
2268
|
+
}
|
|
2234
2269
|
store.update((next) => ({
|
|
2235
2270
|
...next,
|
|
2236
2271
|
modelPickerOpen: false,
|
|
@@ -2967,9 +3002,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
|
|
|
2967
3002
|
dismissPendingUserInput();
|
|
2968
3003
|
const failedTurnAttachments = activeTurnImageAttachments;
|
|
2969
3004
|
activeTurnImageAttachments = [];
|
|
2970
|
-
const quotaNotice = cancelled ? null :
|
|
3005
|
+
const quotaNotice = cancelled ? null : buildRefusalNotice(error);
|
|
3006
|
+
const restoresPrompt = quotaNotice !== null && !jobFollowUp && !store.getState().input && !store.getState().queuedMessage;
|
|
2971
3007
|
store.update((current) => ({
|
|
2972
3008
|
...current,
|
|
3009
|
+
...(restoresPrompt
|
|
3010
|
+
? { cursor: String(rawInput ?? '').length, input: String(rawInput ?? ''), pastedChunks: chunks }
|
|
3011
|
+
: {}),
|
|
2973
3012
|
activeTurnInput: '',
|
|
2974
3013
|
activeTurnInputPreformatted: false,
|
|
2975
3014
|
busy: false,
|
|
@@ -3,7 +3,7 @@ import { projectModelEffort } from '../../project-model-preferences.js';
|
|
|
3
3
|
import { REASONING_EFFORTS, REASONING_EFFORT_LABELS, REASONING_EFFORT_DESCRIPTIONS } from '../../reasoning-effort.js';
|
|
4
4
|
import { agentModeColor, agentModeLabelTiers, agentModeShortLabel, } from '../../agent-mode.js';
|
|
5
5
|
import { singleLinePreview, truncate } from '../../utils.js';
|
|
6
|
-
import { buildModelPickerOptions, formatClientTokenUsage } from '../repl.js';
|
|
6
|
+
import { buildModelPickerOptions, formatClientTokenUsage, PAUSED_MODELS_NOTE, pausedModelCount, } from '../repl.js';
|
|
7
7
|
import { getHiddenSlashCommandCount, getSlashCommandSuggestions, } from '../slash-commands.js';
|
|
8
8
|
import { renderFormattedBodyLines, renderPreformattedBodyLines, } from './markdown-render.js';
|
|
9
9
|
import { displayWidth, line, padToWidth, plainLine, sliceToWidth, span, wrapText, } from './text.js';
|
|
@@ -932,7 +932,7 @@ function modelPickerHeadingLine(title, innerWidth, withColumns) {
|
|
|
932
932
|
const muted = { color: 'gray' };
|
|
933
933
|
return line(modelPickerCell(title, modelPickerModelWidth(innerWidth), heading), span(MODEL_PICKER_COLUMN_GAP), modelPickerCell('Cost', MODEL_PICKER_COST_WIDTH, muted), span(MODEL_PICKER_COLUMN_GAP), modelPickerCell('Notes', modelPickerNotesWidth(innerWidth), muted));
|
|
934
934
|
}
|
|
935
|
-
function modelPickerDisplayRows(options) {
|
|
935
|
+
function modelPickerDisplayRows(options, pausedCount, innerWidth) {
|
|
936
936
|
const rows = [];
|
|
937
937
|
const autoIndexes = options.flatMap((option, index) => (option.group === 'auto' ? [index] : []));
|
|
938
938
|
const modelIndexes = options.flatMap((option, index) => (option.group === 'models' ? [index] : []));
|
|
@@ -940,18 +940,22 @@ function modelPickerDisplayRows(options) {
|
|
|
940
940
|
rows.push({ kind: 'heading', title: 'Auto', withColumns: true });
|
|
941
941
|
rows.push(...autoIndexes.map((index) => ({ kind: 'option', index })));
|
|
942
942
|
}
|
|
943
|
-
if (modelIndexes.length) {
|
|
943
|
+
if (modelIndexes.length || pausedCount > 0) {
|
|
944
944
|
if (rows.length)
|
|
945
945
|
rows.push({ kind: 'gap' });
|
|
946
946
|
rows.push({ kind: 'heading', title: 'Models', withColumns: rows.length === 0 });
|
|
947
947
|
rows.push(...modelIndexes.map((index) => ({ kind: 'option', index })));
|
|
948
|
+
if (pausedCount > 0) {
|
|
949
|
+
const lines = wrapText(PAUSED_MODELS_NOTE, Math.max(1, innerWidth - 2));
|
|
950
|
+
rows.push(...lines.map((text) => ({ kind: 'paused', text })));
|
|
951
|
+
}
|
|
948
952
|
}
|
|
949
953
|
return rows;
|
|
950
954
|
}
|
|
951
|
-
function buildModelPickerPanel(options, selectedIndex, width, availableHeight, efforts = {}) {
|
|
955
|
+
function buildModelPickerPanel(options, selectedIndex, width, availableHeight, efforts = {}, pausedCount = 0) {
|
|
952
956
|
const panelWidth = Math.max(28, Math.min(width, MODEL_PICKER_PANEL_MAX_WIDTH));
|
|
953
957
|
const innerWidth = Math.max(1, panelWidth - 4);
|
|
954
|
-
const rows = modelPickerDisplayRows(options);
|
|
958
|
+
const rows = modelPickerDisplayRows(options, pausedCount, innerWidth);
|
|
955
959
|
const showEffortDetails = rows.length + 8 <= availableHeight;
|
|
956
960
|
const fixedLineCount = showEffortDetails ? 8 : 5;
|
|
957
961
|
const visibleCount = Math.min(rows.length, Math.max(1, availableHeight - fixedLineCount));
|
|
@@ -969,12 +973,17 @@ function buildModelPickerPanel(options, selectedIndex, width, availableHeight, e
|
|
|
969
973
|
else if (row.kind === 'gap') {
|
|
970
974
|
body.push(modelPickerPanelSideLine(plainLine(''), innerWidth));
|
|
971
975
|
}
|
|
976
|
+
else if (row.kind === 'paused') {
|
|
977
|
+
body.push(modelPickerPanelSideLine(plainLine(fitLine(` ${row.text}`, innerWidth), { color: 'gray' }), innerWidth));
|
|
978
|
+
}
|
|
972
979
|
else {
|
|
973
980
|
const option = options[row.index];
|
|
974
981
|
body.push(...modelPickerItemLines(option, row.index === selectedIndex, projectModelEffort(efforts, option.publicId), innerWidth));
|
|
975
982
|
}
|
|
976
983
|
}
|
|
977
984
|
const selected = options[selectedIndex];
|
|
985
|
+
const lockedSelection = selected?.disabled ? selected : undefined;
|
|
986
|
+
const lockedLines = lockedSelection ? wrapText(lockedSelection.note, innerWidth) : [];
|
|
978
987
|
const selectedEffort = projectModelEffort(efforts, selected?.publicId ?? 0);
|
|
979
988
|
const autoSelected = selected?.group === 'auto';
|
|
980
989
|
const effortChoices = REASONING_EFFORTS.map((effort) => effort === selectedEffort ? `[${REASONING_EFFORT_LABELS[effort]}]` : REASONING_EFFORT_LABELS[effort]).join(' ');
|
|
@@ -992,9 +1001,13 @@ function buildModelPickerPanel(options, selectedIndex, width, availableHeight, e
|
|
|
992
1001
|
: '↑/↓ model • ←/→ effort • Enter select/save • Esc cancel';
|
|
993
1002
|
const compactHint = autoSelected ? '↑↓ · Enter · Esc' : '↑↓ · ←→ · Enter · Esc';
|
|
994
1003
|
const hint = [...fullHint].length <= innerWidth ? fullHint : compactHint;
|
|
995
|
-
body.push(modelPickerDivider(panelWidth),
|
|
1004
|
+
body.push(modelPickerDivider(panelWidth), lockedSelection
|
|
1005
|
+
? modelPickerPanelSideLine(plainLine(fitLine(showEffortDetails ? (lockedLines[0] ?? '') : lockedSelection.note, innerWidth), { color: 'yellow', bold: true }), innerWidth)
|
|
1006
|
+
: modelPickerPanelSideLine(plainLine(fitLine(effortText, innerWidth), { color: 'cyan', bold: true }), innerWidth), ...(showEffortDetails ? [
|
|
996
1007
|
modelPickerPanelSideLine(plainLine(''), innerWidth),
|
|
997
|
-
|
|
1008
|
+
lockedSelection
|
|
1009
|
+
? modelPickerPanelSideLine(plainLine(fitLine(lockedLines.slice(1).join(' '), innerWidth), { color: 'yellow', bold: true }), innerWidth)
|
|
1010
|
+
: modelPickerPanelSideLine(plainLine(fitLine(effortDescription, innerWidth), { color: 'gray' }), innerWidth),
|
|
998
1011
|
modelPickerPanelSideLine(plainLine(''), innerWidth),
|
|
999
1012
|
] : []), modelPickerPanelSideLine(plainLine(fitLine(hint, innerWidth), { color: 'gray' }), innerWidth), plainLine(`╰${'─'.repeat(panelWidth - 2)}╯`, { color: MODEL_PICKER_BORDER_COLOR }));
|
|
1000
1013
|
return [...margin, ...body, ...margin];
|
|
@@ -1317,7 +1330,7 @@ function buildOverlayLines(state, width, height, nowMs) {
|
|
|
1317
1330
|
}
|
|
1318
1331
|
if (state.modelPickerOpen) {
|
|
1319
1332
|
const options = buildModelPickerOptions(state.currentModelId, state.serverModels);
|
|
1320
|
-
lines.push(...buildModelPickerPanel(options, state.modelPickerIndex, width, height, state.modelPickerEfforts));
|
|
1333
|
+
lines.push(...buildModelPickerPanel(options, state.modelPickerIndex, width, height, state.modelPickerEfforts, pausedModelCount(state.serverModels)));
|
|
1321
1334
|
}
|
|
1322
1335
|
if (state.jobsPickerOpen) {
|
|
1323
1336
|
lines.push(...buildJobsPickerLines(state, width, height, nowMs));
|
|
@@ -376,7 +376,7 @@ export function handleShellKeyEvent(store, handlers, event) {
|
|
|
376
376
|
store.update((current) => {
|
|
377
377
|
const options = buildModelPickerOptions(Number(current.currentModelId ?? 0), current.serverModels ?? []);
|
|
378
378
|
const model = options[current.modelPickerIndex];
|
|
379
|
-
if (!model || model.group === 'auto')
|
|
379
|
+
if (!model || model.disabled || model.group === 'auto')
|
|
380
380
|
return current;
|
|
381
381
|
const efforts = current.modelPickerEfforts ?? {};
|
|
382
382
|
return {
|
package/dist/src/usage.js
CHANGED
|
@@ -34,6 +34,11 @@ function formatPercentLeft(value) {
|
|
|
34
34
|
maximumFractionDigits: 1,
|
|
35
35
|
}).format(percent)}% left`;
|
|
36
36
|
}
|
|
37
|
+
const PLAN_NAMES = {
|
|
38
|
+
free: 'Free',
|
|
39
|
+
plus: 'Plus',
|
|
40
|
+
pro: 'Pro',
|
|
41
|
+
};
|
|
37
42
|
export function formatUsageText(response) {
|
|
38
43
|
const { customer, usage } = response;
|
|
39
44
|
const lines = [`Usage for ${customer.email}`, ''];
|
|
@@ -41,10 +46,25 @@ export function formatUsageText(response) {
|
|
|
41
46
|
lines.push('Usage is not available for this account yet.');
|
|
42
47
|
return lines.join('\n');
|
|
43
48
|
}
|
|
49
|
+
if (usage.plan) {
|
|
50
|
+
lines.push(`Plan: ${PLAN_NAMES[usage.plan] ?? usage.plan}`, '');
|
|
51
|
+
}
|
|
44
52
|
lines.push('Window Left Resets');
|
|
45
53
|
for (const [label, key] of USAGE_WINDOWS) {
|
|
46
54
|
const value = formatPercentLeft(Number(usage.percentLeft[key] ?? 0));
|
|
47
55
|
lines.push(`${label.padEnd(10)} ${value.padEnd(11)} ${formatUtcMinute(usage.resetsAt[key])}`);
|
|
48
56
|
}
|
|
57
|
+
if (usage.autoOnly) {
|
|
58
|
+
const value = formatPercentLeft(Number(usage.autoPercentLeft ?? 0));
|
|
59
|
+
lines.push(`${'Auto extra'.padEnd(10)} ${value.padEnd(11)} ${formatUtcMinute(usage.resetsAt.monthly)}`, '', ...(usage.autoExtraSpent
|
|
60
|
+
? [
|
|
61
|
+
'Your monthly allowance and extra Auto usage are used up. Usage',
|
|
62
|
+
'resumes when your plan renews.',
|
|
63
|
+
]
|
|
64
|
+
: [
|
|
65
|
+
'Your monthly allowance is used up. Auto options in /model still work',
|
|
66
|
+
'on extra usage until it runs out or your plan renews.',
|
|
67
|
+
]));
|
|
68
|
+
}
|
|
49
69
|
return lines.join('\n');
|
|
50
70
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thegitai/cli",
|
|
3
|
-
"version": "1.0.0-preview.
|
|
3
|
+
"version": "1.0.0-preview.62",
|
|
4
4
|
"description": "TheGitAI is an agentic AI coding tool for your terminal. It reads and searches your repository, writes and edits files, runs your tests, and verifies the change before handing it back.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentic-ai",
|
|
@@ -45,11 +45,11 @@
|
|
|
45
45
|
"@lydell/node-pty-linux-x64": "1.1.0",
|
|
46
46
|
"@lydell/node-pty-win32-arm64": "1.1.0",
|
|
47
47
|
"@lydell/node-pty-win32-x64": "1.1.0",
|
|
48
|
-
"@thegitai/tui-darwin-arm64": "1.0.0-preview.
|
|
49
|
-
"@thegitai/tui-darwin-x64": "1.0.0-preview.
|
|
50
|
-
"@thegitai/tui-linux-arm64": "1.0.0-preview.
|
|
51
|
-
"@thegitai/tui-linux-x64": "1.0.0-preview.
|
|
52
|
-
"@thegitai/tui-win32-x64": "1.0.0-preview.
|
|
48
|
+
"@thegitai/tui-darwin-arm64": "1.0.0-preview.62",
|
|
49
|
+
"@thegitai/tui-darwin-x64": "1.0.0-preview.62",
|
|
50
|
+
"@thegitai/tui-linux-arm64": "1.0.0-preview.62",
|
|
51
|
+
"@thegitai/tui-linux-x64": "1.0.0-preview.62",
|
|
52
|
+
"@thegitai/tui-win32-x64": "1.0.0-preview.62",
|
|
53
53
|
"@vscode/ripgrep": "1.18.0"
|
|
54
54
|
},
|
|
55
55
|
"repository": {
|