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

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 (90) hide show
  1. package/README.md +229 -7
  2. package/dist/bin/ai.js +140 -111
  3. package/dist/bin/browser-host.js +265 -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 +262 -0
  16. package/dist/src/browser/framing.js +42 -0
  17. package/dist/src/browser/native-host.js +219 -0
  18. package/dist/src/browser/protocol.js +46 -0
  19. package/dist/src/browser/session-bridge.js +130 -0
  20. package/dist/src/cli-args.js +19 -5
  21. package/dist/src/client-environment.js +2 -0
  22. package/dist/src/core/clipboard.js +7 -13
  23. package/dist/src/core/image-limits.js +56 -0
  24. package/dist/src/core/image-path-extractor.js +70 -3
  25. package/dist/src/core/session-image-store.js +246 -0
  26. package/dist/src/edit-journal.js +33 -2
  27. package/dist/src/executor.js +25 -3
  28. package/dist/src/help-text.js +128 -22
  29. package/dist/src/job-follow-up.js +40 -0
  30. package/dist/src/mcp-client.js +335 -0
  31. package/dist/src/mcp-command.js +176 -0
  32. package/dist/src/mcp-config.js +123 -0
  33. package/dist/src/mcp-sdk.js +3 -0
  34. package/dist/src/mcp-types.js +26 -0
  35. package/dist/src/patcher.js +43 -4
  36. package/dist/src/permissions.js +301 -0
  37. package/dist/src/preferences.js +39 -0
  38. package/dist/src/project-key.js +11 -0
  39. package/dist/src/project-model-preferences.js +74 -0
  40. package/dist/src/quota-notice.js +35 -0
  41. package/dist/src/reasoning-effort.js +27 -0
  42. package/dist/src/session-safety.js +0 -12
  43. package/dist/src/session-store.js +123 -30
  44. package/dist/src/session.js +20 -4
  45. package/dist/src/signin.js +58 -0
  46. package/dist/src/tool-executor.js +23 -49
  47. package/dist/src/tools/browser.js +641 -0
  48. package/dist/src/tools/delete-file.js +20 -4
  49. package/dist/src/tools/index.js +32 -10
  50. package/dist/src/tools/patch-file.js +12 -26
  51. package/dist/src/tools/read-file.js +5 -0
  52. package/dist/src/tools/read-image-file.js +85 -0
  53. package/dist/src/tools/replace-document-text.js +28 -18
  54. package/dist/src/tools/restore-checkpoint.js +0 -1
  55. package/dist/src/tools/run-command.js +14 -71
  56. package/dist/src/tools/run-node-script.js +12 -81
  57. package/dist/src/tools/save-generated-image.js +120 -0
  58. package/dist/src/tools/str-replace.js +12 -26
  59. package/dist/src/tools/undo-edit.js +1 -6
  60. package/dist/src/tools/write-file.js +67 -11
  61. package/dist/src/ui/prompt-history-store.js +1 -1
  62. package/dist/src/ui/repl.js +1017 -299
  63. package/dist/src/ui/slash-commands.js +122 -0
  64. package/dist/src/ui/tui/attention.js +25 -0
  65. package/dist/src/ui/tui/bridge.js +38 -5
  66. package/dist/src/ui/tui/build-frame.js +807 -270
  67. package/dist/src/ui/tui/composer-layout.js +76 -0
  68. package/dist/src/ui/tui/desktop-notification.js +118 -0
  69. package/dist/src/ui/tui/markdown-render.js +21 -11
  70. package/dist/src/ui/tui/model-label.js +13 -0
  71. package/dist/src/ui/tui/shell-input.js +275 -73
  72. package/dist/src/ui/tui/shortcuts.js +61 -0
  73. package/dist/src/ui/tui/terminal-theme.js +28 -0
  74. package/dist/src/ui/tui/text.js +31 -6
  75. package/dist/src/ui/tui/user-input.js +593 -0
  76. package/dist/src/update-check.js +205 -0
  77. package/dist/src/usage-notice.js +52 -0
  78. package/dist/src/usage.js +5 -2
  79. package/dist/src/utils.js +13 -0
  80. package/dist/src/version.js +52 -2
  81. package/dist/vendor/mcp/LICENSES.txt +414 -0
  82. package/dist/vendor/mcp/client.cjs +82 -0
  83. package/package.json +22 -9
  84. package/dist/src/project-index.js +0 -233
  85. package/dist/src/tools/code-intel.js +0 -472
  86. package/dist/src/tools/find-symbol.js +0 -70
  87. package/dist/src/tools/hover-symbol.js +0 -95
  88. package/dist/src/tools/list-symbols.js +0 -55
  89. package/dist/src/tools/search-code.js +0 -37
  90. package/dist/src/tools/signature-help.js +0 -118
@@ -1,12 +1,17 @@
1
- import { createHash } from 'node:crypto';
1
+ import { spawnSync } from 'node:child_process';
2
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { getClientStateDir } from './client-state.js';
5
+ import { getSessionProjectKey } from './project-key.js';
6
+ import { findStoredImageByContent, pruneSessionImages, readSessionImage, sweepOrphanSessionImages, } from './core/session-image-store.js';
7
+ import { sweepGeneratedImages } from './tools/save-generated-image.js';
5
8
  import { normalizeAssistantEditJournal } from './edit-journal.js';
9
+ import { createSessionGrants } from './permissions.js';
6
10
  import { cloneSessionSafetyState, createSessionSafetyState, mergeLocalSessionSafetyState, normalizeSessionSafetyState, } from './session-safety.js';
7
- import { truncate } from './utils.js';
11
+ import { singleLinePreview } from './utils.js';
8
12
  const SESSION_STORE_VERSION = 1;
9
- const MAX_RECENT_SESSIONS = 5;
13
+ export const MAX_RECENT_SESSIONS = 10;
14
+ export { getSessionProjectKey };
10
15
  function cloneJson(value) {
11
16
  return JSON.parse(JSON.stringify(value ?? null));
12
17
  }
@@ -54,15 +59,6 @@ function safeSessionFileName(id) {
54
59
  function getSessionBaseDir(env = process.env) {
55
60
  return getClientStateDir(env);
56
61
  }
57
- export function getSessionProjectKey(rootDir) {
58
- const resolvedRoot = path.resolve(rootDir);
59
- const projectName = path.basename(resolvedRoot).replace(/[^a-zA-Z0-9._-]/g, '_') || 'project';
60
- const hash = createHash('sha256')
61
- .update(resolvedRoot)
62
- .digest('hex')
63
- .slice(0, 16);
64
- return `${projectName}-${hash}`;
65
- }
66
62
  function getSessionProjectDir(rootDir, env = process.env) {
67
63
  return path.join(getSessionBaseDir(env), 'sessions', 'projects', getSessionProjectKey(rootDir));
68
64
  }
@@ -77,6 +73,45 @@ function listSessionFiles(rootDir, env = process.env) {
77
73
  .filter((name) => name.endsWith('.json'))
78
74
  .map((name) => path.join(dir, name));
79
75
  }
76
+ function normalizeBranch(value) {
77
+ const text = String(value ?? '')
78
+ .replace(/[\r\n\t]/g, ' ')
79
+ .trim();
80
+ return text ? text.slice(0, 120) : null;
81
+ }
82
+ function dehydrateHistoryImages(history) {
83
+ return history.map((entry) => ({
84
+ ...entry,
85
+ parts: (entry.parts ?? []).map((part) => {
86
+ if (!part?.inlineData?.data)
87
+ return part;
88
+ const cachePath = part.imageCachePath ?? findStoredImageByContent(part.inlineData.data);
89
+ if (!cachePath)
90
+ return part;
91
+ return {
92
+ imageRef: { cachePath, mimeType: part.inlineData.mimeType },
93
+ text: '[image stored in this session]',
94
+ };
95
+ }),
96
+ }));
97
+ }
98
+ function rehydrateHistoryImages(history) {
99
+ return history.map((entry) => ({
100
+ ...entry,
101
+ parts: (entry.parts ?? []).map((part) => {
102
+ const ref = part?.imageRef;
103
+ if (!ref?.cachePath)
104
+ return part;
105
+ const stored = readSessionImage(String(ref.cachePath));
106
+ if (!stored)
107
+ return { text: part.text ?? '[image no longer available]' };
108
+ return {
109
+ inlineData: { mimeType: stored.mimeType, data: stored.base64Data },
110
+ imageCachePath: ref.cachePath,
111
+ };
112
+ }),
113
+ }));
114
+ }
80
115
  function normalizeHistory(value) {
81
116
  if (!Array.isArray(value))
82
117
  return [];
@@ -107,6 +142,7 @@ function normalizeSnapshot(raw, rootDir) {
107
142
  createdAt: normalizeIsoDate(raw.createdAt),
108
143
  updatedAt: normalizeIsoDate(raw.updatedAt),
109
144
  modelId,
145
+ branch: normalizeBranch(raw.branch),
110
146
  history: cloneJson(normalizeHistory(raw.history)),
111
147
  clientState: sanitizeClientState(raw.clientState),
112
148
  serverState: sanitizeOpaqueState(raw.serverState),
@@ -145,14 +181,58 @@ function assertSessionNameAvailable(rootDir, name, sessionId, env = process.env)
145
181
  throw new Error(`Session name "${name}" is already used by ${duplicate.id}. Use --session "${name}" to resume it or choose a different name.`);
146
182
  }
147
183
  }
184
+ function listAllSessionIds(env = process.env) {
185
+ const ids = new Set();
186
+ const projectsDir = path.join(getSessionBaseDir(env), 'sessions', 'projects');
187
+ if (!existsSync(projectsDir))
188
+ return ids;
189
+ try {
190
+ for (const project of readdirSync(projectsDir)) {
191
+ const dir = path.join(projectsDir, project);
192
+ try {
193
+ for (const file of readdirSync(dir)) {
194
+ if (file.endsWith('.json'))
195
+ ids.add(path.basename(file, '.json'));
196
+ }
197
+ }
198
+ catch {
199
+ }
200
+ }
201
+ }
202
+ catch {
203
+ return ids;
204
+ }
205
+ return ids;
206
+ }
148
207
  export function pruneSavedSessions(rootDir, env = process.env) {
149
208
  const snapshots = loadAllSnapshots(rootDir, env);
150
209
  const keep = new Set(snapshots.slice(0, MAX_RECENT_SESSIONS).map((snapshot) => snapshot.id));
151
210
  for (const snapshot of snapshots.slice(MAX_RECENT_SESSIONS)) {
152
211
  if (!keep.has(snapshot.id)) {
153
212
  rmSync(getSessionPath(rootDir, snapshot.id, env), { force: true });
213
+ pruneSessionImages(snapshot.id, env);
154
214
  }
155
215
  }
216
+ sweepOrphanSessionImages({
217
+ activeSessionIds: listAllSessionIds(env),
218
+ env,
219
+ });
220
+ sweepGeneratedImages({ env });
221
+ }
222
+ export function readGitBranch(rootDir) {
223
+ try {
224
+ const result = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
225
+ cwd: rootDir,
226
+ encoding: 'utf8',
227
+ timeout: 1500,
228
+ stdio: ['ignore', 'pipe', 'ignore'],
229
+ });
230
+ const branch = result.status === 0 ? String(result.stdout ?? '').trim() : '';
231
+ return branch && branch !== 'HEAD' ? branch : null;
232
+ }
233
+ catch {
234
+ return null;
235
+ }
156
236
  }
157
237
  export function snapshotFromSession(session) {
158
238
  const now = new Date().toISOString();
@@ -168,6 +248,7 @@ export function snapshotFromSession(session) {
168
248
  createdAt,
169
249
  updatedAt: now,
170
250
  modelId: session.modelId,
251
+ branch: readGitBranch(session.rootDir),
171
252
  history: cloneJson(session.history),
172
253
  clientState: {
173
254
  editCounter: session.clientState.editCounter,
@@ -187,6 +268,7 @@ export function saveSessionState(session, env = process.env) {
187
268
  }
188
269
  export function applySessionSnapshot(session, snapshot, options = {}) {
189
270
  const currentAgentMode = session.agentMode;
271
+ const previousSessionId = session.sessionId;
190
272
  session.sessionId = snapshot.id;
191
273
  session.sessionName = snapshot.name;
192
274
  session.sessionCreatedAt = snapshot.createdAt;
@@ -196,6 +278,9 @@ export function applySessionSnapshot(session, snapshot, options = {}) {
196
278
  session.serverState = sanitizeOpaqueState(snapshot.serverState);
197
279
  session.agentMode = options.preserveAgentMode ? currentAgentMode : 'default';
198
280
  session.autoYes = session.agentMode === 'auto-accept';
281
+ if (previousSessionId !== session.sessionId) {
282
+ session.grants = createSessionGrants();
283
+ }
199
284
  session.turnState = {
200
285
  id: null,
201
286
  historyStartIndex: session.history.length,
@@ -210,6 +295,9 @@ export function applySessionSnapshot(session, snapshot, options = {}) {
210
295
  safety: mergeLocalSessionSafetyState(session.clientState.safety, snapshot.clientState.safety),
211
296
  };
212
297
  }
298
+ export function sessionHasUserMessage(session) {
299
+ return session.history.some((entry) => Boolean(userPromptText(entry)));
300
+ }
213
301
  function extractMarkedSection(text, marker) {
214
302
  const index = text.indexOf(marker);
215
303
  if (index === -1)
@@ -218,23 +306,27 @@ function extractMarkedSection(text, marker) {
218
306
  const end = after.indexOf('\n\n');
219
307
  return (end === -1 ? after : after.slice(0, end)).trim();
220
308
  }
221
- function extractLastUserMessage(history) {
222
- for (let i = history.length - 1; i >= 0; i--) {
223
- const entry = history[i];
224
- if (!entry || entry.role !== 'user')
225
- continue;
226
- const text = (entry.parts ?? [])
227
- .map((part) => (typeof part?.text === 'string' ? part.text : ''))
228
- .filter(Boolean)
229
- .join('\n')
230
- .trim();
231
- if (!text)
232
- continue;
233
- const request = extractMarkedSection(text, 'Current user request:') ||
234
- extractMarkedSection(text, 'User request:');
235
- const message = extractMarkedSection(text, 'Current user message:') ||
236
- extractMarkedSection(text, 'User message:');
237
- return truncate(request || message || text, 120);
309
+ export function userPromptText(entry) {
310
+ if (!entry || entry.role !== 'user' || entry.kind !== 'turnStart')
311
+ return '';
312
+ const text = (entry.parts ?? [])
313
+ .map((part) => (typeof part?.text === 'string' ? part.text : ''))
314
+ .filter(Boolean)
315
+ .join('\n')
316
+ .trim();
317
+ if (!text)
318
+ return '';
319
+ const request = extractMarkedSection(text, 'Current user request:') ||
320
+ extractMarkedSection(text, 'User request:');
321
+ const message = extractMarkedSection(text, 'Current user message:') ||
322
+ extractMarkedSection(text, 'User message:');
323
+ return (request || message || text).trim();
324
+ }
325
+ function extractFirstUserPrompt(history) {
326
+ for (const entry of history) {
327
+ const text = userPromptText(entry);
328
+ if (text)
329
+ return singleLinePreview(text, 120);
238
330
  }
239
331
  return '';
240
332
  }
@@ -247,8 +339,9 @@ function metadataFromSnapshot(snapshot) {
247
339
  updatedAt: snapshot.updatedAt,
248
340
  modelId: snapshot.modelId,
249
341
  messageCount: snapshot.history.length,
250
- lastUserMessage: extractLastUserMessage(snapshot.history),
342
+ lastUserMessage: extractFirstUserPrompt(snapshot.history),
251
343
  summaryPreview: '',
344
+ branch: snapshot.branch ?? null,
252
345
  };
253
346
  }
254
347
  export function listSessionMetadata(rootDir, env = process.env) {
@@ -1,6 +1,8 @@
1
1
  import path from 'node:path';
2
2
  import { normalizeAgentMode, } from './agent-mode.js';
3
+ import { createSessionGrants, } from './permissions.js';
3
4
  import { createSessionSafetyState, } from './session-safety.js';
5
+ import { closeBrowserBridge } from './browser/session-bridge.js';
4
6
  import { clampInteger } from './utils.js';
5
7
  const DEFAULT_MAX_TOOL_STEPS = 32;
6
8
  function defaultStatus(message) {
@@ -31,7 +33,7 @@ function preserveProviderSelection(serverState) {
31
33
  : null;
32
34
  return providerSelection ? { providerSelection } : {};
33
35
  }
34
- export function createSession({ rootDir, autoYes = false, agentMode, modelId, maxToolSteps = DEFAULT_MAX_TOOL_STEPS, confirmCommand = null, confirmPatch = null, requestSudoPassword = null, onStatus = null, onContextLog = null, onToolEvent = null, env = process.env, sessionId = createSessionId(), sessionName = null, history = [], serverState = null, editJournal = [], stickyFilePaths = [], editCounter = 0, safety = createSessionSafetyState(), }) {
36
+ export function createSession({ rootDir, autoYes = false, agentMode, modelId, maxToolSteps = DEFAULT_MAX_TOOL_STEPS, maxToolStepsWasExplicit = false, requestPermission = null, requestSudoPassword = null, requestUserInput = null, onStatus = null, onContextLog = null, onToolEvent = null, env = process.env, sessionId = createSessionId(), sessionName = null, history = [], serverState = null, editJournal = [], stickyFilePaths = [], editCounter = 0, safety = createSessionSafetyState(), }) {
35
37
  const createdAt = new Date().toISOString();
36
38
  const initialAgentMode = normalizeAgentMode(agentMode ?? (autoYes ? 'auto-accept' : 'default'));
37
39
  return {
@@ -40,12 +42,14 @@ export function createSession({ rootDir, autoYes = false, agentMode, modelId, ma
40
42
  autoYes: initialAgentMode === 'auto-accept',
41
43
  agentMode: initialAgentMode,
42
44
  maxToolSteps: clampInteger(maxToolSteps, DEFAULT_MAX_TOOL_STEPS, 128),
45
+ maxToolStepsWasExplicit: maxToolStepsWasExplicit === true,
43
46
  onStatus: onStatus ?? defaultStatus,
44
47
  onContextLog: onContextLog ?? defaultContextLog,
45
48
  onToolEvent,
46
- confirmCommand,
47
- confirmPatch,
49
+ grants: createSessionGrants(),
50
+ requestPermission,
48
51
  requestSudoPassword,
52
+ requestUserInput,
49
53
  history: JSON.parse(JSON.stringify(history)),
50
54
  initialized: true,
51
55
  sessionId,
@@ -69,8 +73,17 @@ export function createSession({ rootDir, autoYes = false, agentMode, modelId, ma
69
73
  serverState: cloneOpaqueState(serverState),
70
74
  };
71
75
  }
76
+ export function startNewConversation(session) {
77
+ clearConversation(session);
78
+ const createdAt = new Date().toISOString();
79
+ session.sessionId = createSessionId();
80
+ session.sessionName = null;
81
+ session.sessionCreatedAt = createdAt;
82
+ session.sessionUpdatedAt = createdAt;
83
+ }
72
84
  export function clearConversation(session) {
73
85
  session.history = [];
86
+ session.grants = createSessionGrants();
74
87
  session.serverState = preserveProviderSelection(session.serverState);
75
88
  session.turnState = {
76
89
  id: null,
@@ -86,7 +99,10 @@ export function clearConversation(session) {
86
99
  safety: createSessionSafetyState(),
87
100
  };
88
101
  }
89
- export async function disposeSession(_session) { }
102
+ export async function disposeSession(session) {
103
+ closeBrowserBridge();
104
+ await session.mcp?.close();
105
+ }
90
106
  export function switchModel(session, modelId) {
91
107
  session.modelId = Number(modelId);
92
108
  return { id: session.modelId };
@@ -0,0 +1,58 @@
1
+ import { stdin as input, stdout as output } from 'node:process';
2
+ import readline from 'node:readline/promises';
3
+ import chalk from './colors.js';
4
+ import { auth } from './api/index.js';
5
+ import { DEFAULT_THEGITAI_HOST } from './api/default-host.js';
6
+ import { loginViaBrowser } from './api/browser-login.js';
7
+ function hyperlink(url, label) {
8
+ if (process.stdout.isTTY !== true)
9
+ return label;
10
+ return `\x1b]8;;${url}\x07${label}\x1b]8;;\x07`;
11
+ }
12
+ export function formatSignInScreen({ url }) {
13
+ return [
14
+ '',
15
+ ` ${chalk.bold.cyan('TheGitAI')}`,
16
+ '',
17
+ ` ${chalk.bold('Sign in to continue.')}`,
18
+ ' Your browser should open automatically. If not, copy this URL:',
19
+ '',
20
+ ` ${chalk.cyan(url)}`,
21
+ '',
22
+ ` ${hyperlink(url, chalk.cyan('→ Click here to authenticate'))}`,
23
+ '',
24
+ ' If this terminal is not on the computer where that page opened, choose',
25
+ ` ${chalk.bold('"On another computer"')} there and paste the code it gives you below.`,
26
+ '',
27
+ ].join('\n');
28
+ }
29
+ async function promptForCode(signal) {
30
+ const rl = readline.createInterface({ input, output });
31
+ try {
32
+ return await rl.question(` ${chalk.bold('Authorization code:')} `, { signal });
33
+ }
34
+ finally {
35
+ rl.close();
36
+ }
37
+ }
38
+ export async function runSignIn({ env = process.env, login = loginViaBrowser, write = auth.writeCliAuthConfig, log = (line) => console.log(line), } = {}) {
39
+ const result = await login({
40
+ serverUrl: DEFAULT_THEGITAI_HOST,
41
+ deviceName: env.THEGITAI_DEVICE_NAME?.trim() || undefined,
42
+ onUrl: (url) => log(formatSignInScreen({ url })),
43
+ onBrowserOpen: (opened) => {
44
+ if (!opened) {
45
+ log(chalk.dim(' (no browser opened — use the URL or the code box above)'));
46
+ }
47
+ },
48
+ promptCode: promptForCode,
49
+ onPasteRejected: (message) => log(` ${chalk.red('✖')} ${message}\n` +
50
+ ' Codes last 10 minutes. If that page has been open a while, run `ai`\n' +
51
+ ' again for a fresh one.'),
52
+ });
53
+ write(result, env);
54
+ log('');
55
+ log(chalk.green(` ✓ Signed in as ${result.customer.email}`));
56
+ log('');
57
+ return result;
58
+ }
@@ -1,10 +1,11 @@
1
+ import { isMcpToolName } from './mcp-types.js';
2
+ import { sessionMcp } from './mcp-client.js';
1
3
  import { drainBackgroundJobNotifications, getBackgroundJob, } from './background-jobs.js';
2
4
  import { canStoreEditSnapshot, isEditToolName, isGitWorkTree, MAX_EDIT_JOURNAL_RECORDS, operationFromSnapshots, readFileEditSnapshot, } from './edit-journal.js';
3
5
  import { clearEditFailure, collectCommandMutations, captureMutationBaseline, ensureActiveCheckpoint, recordEditFailure, recordSessionEdit, rememberCheckpointFiles, } from './session-safety.js';
4
6
  import { buildAgentModeToolBlockedResult, } from './agent-mode.js';
5
7
  import { classifyProjectPath } from './patcher.js';
6
8
  import { dispatchTool } from './tools/index.js';
7
- import { syncIndexFromDisk } from './project-index.js';
8
9
  import { PATH_REPAIRING_EDIT_TOOLS, repairFilePath } from './tools/path-suggest.js';
9
10
  import { invalidateShellDiagnosticsCache, runShellDiagnostics, } from './tools/shell-diagnostics.js';
10
11
  import { extractTodosArg } from './todo-list.js';
@@ -43,9 +44,9 @@ function toolCallSummary(call) {
43
44
  return args.query.slice(0, 120);
44
45
  return '';
45
46
  }
46
- export function formatToolCallForStatus(call) {
47
+ export function formatToolCallForStatus(call, label = call.name) {
47
48
  const summary = toolCallSummary(call);
48
- return summary ? `Tool: ${call.name} ${summary}` : `Tool: ${call.name}`;
49
+ return summary ? `Tool: ${label} ${summary}` : `Tool: ${label}`;
49
50
  }
50
51
  function getEditToolFilePath(call) {
51
52
  const args = call.args && typeof call.args === 'object' ? call.args : {};
@@ -69,7 +70,7 @@ function editToolWritesSeparateOutput(call) {
69
70
  const output = args.outputPath ?? args.output_path;
70
71
  return typeof output === 'string' && output.trim().length > 0;
71
72
  }
72
- async function collectTrackedCommandMutations({ session, projectIndex, result, tracker, toolName, toolCallId, turnId, }) {
73
+ async function collectTrackedCommandMutations({ session, result, tracker, toolName, toolCallId, turnId, }) {
73
74
  const checkpoint = ensureActiveCheckpoint(session.clientState.safety, turnId);
74
75
  const records = collectCommandMutations({
75
76
  state: session.clientState.safety,
@@ -84,40 +85,11 @@ async function collectTrackedCommandMutations({ session, projectIndex, result, t
84
85
  return;
85
86
  invalidateShellDiagnosticsCache(session.rootDir);
86
87
  rememberCheckpointFiles(session.clientState.safety, session.rootDir, records.map((record) => record.filePath), turnId);
87
- const priorSync = result.repoSync;
88
- if (!(priorSync && (priorSync.added || priorSync.modified || priorSync.removed))) {
89
- const mutationCounts = {
90
- added: records.filter((record) => record.operation === 'create').length,
91
- modified: records.filter((record) => record.operation === 'update').length,
92
- removed: records.filter((record) => record.operation === 'delete').length,
93
- indexedChunks: 0,
94
- retrievalTokensUsed: 0,
95
- };
96
- if (priorSync?.error) {
97
- result.repoSync = {
98
- ...mutationCounts,
99
- indexSyncError: priorSync.error,
100
- skipped: true,
101
- reason: 'local index sync failed after command execution',
102
- };
103
- }
104
- else {
105
- try {
106
- const repoSync = await syncIndexFromDisk(projectIndex);
107
- result.repoSync = {
108
- ...repoSync,
109
- added: Math.max(repoSync.added, mutationCounts.added),
110
- modified: Math.max(repoSync.modified, mutationCounts.modified),
111
- removed: Math.max(repoSync.removed, mutationCounts.removed),
112
- };
113
- }
114
- catch (error) {
115
- const indexSyncError = error instanceof Error ? error.message : String(error);
116
- result.repoSync = { ...mutationCounts, indexSyncError };
117
- session.onStatus(`Repository changes were recorded, but local index sync failed: ${indexSyncError}`);
118
- }
119
- }
120
- }
88
+ result.repoSync = {
89
+ added: records.filter((record) => record.operation === 'create').length,
90
+ modified: records.filter((record) => record.operation === 'update').length,
91
+ removed: records.filter((record) => record.operation === 'delete').length,
92
+ };
121
93
  result.sessionEdits = records.map((record) => ({
122
94
  id: record.id,
123
95
  filePath: record.filePath,
@@ -127,7 +99,7 @@ async function collectTrackedCommandMutations({ session, projectIndex, result, t
127
99
  }));
128
100
  result.diagnostics = runShellDiagnostics(session.rootDir);
129
101
  }
130
- export async function collectBackgroundJobUiKillMutations({ session, projectIndex, jobId, result, }) {
102
+ export async function collectBackgroundJobUiKillMutations({ session, jobId, result, }) {
131
103
  const normalizedJobId = String(jobId ?? result.snapshot?.id ?? '').trim();
132
104
  if (!normalizedJobId || !result.ok)
133
105
  return;
@@ -137,7 +109,6 @@ export async function collectBackgroundJobUiKillMutations({ session, projectInde
137
109
  const mutationResult = result;
138
110
  await collectTrackedCommandMutations({
139
111
  session,
140
- projectIndex,
141
112
  result: mutationResult,
142
113
  tracker: tracked.tracker,
143
114
  toolName: tracked.toolName,
@@ -151,7 +122,7 @@ export async function collectBackgroundJobUiKillMutations({ session, projectInde
151
122
  backgroundCommandTrackers.delete(normalizedJobId);
152
123
  }
153
124
  }
154
- export async function collectBackgroundJobUiOutputMutations({ session, projectIndex, jobId, }) {
125
+ export async function collectBackgroundJobUiOutputMutations({ session, jobId, }) {
155
126
  const normalizedJobId = String(jobId ?? '').trim();
156
127
  if (!normalizedJobId)
157
128
  return;
@@ -165,7 +136,6 @@ export async function collectBackgroundJobUiOutputMutations({ session, projectIn
165
136
  return;
166
137
  await collectTrackedCommandMutations({
167
138
  session,
168
- projectIndex,
169
139
  result: {},
170
140
  tracker: tracked.tracker,
171
141
  toolName: tracked.toolName,
@@ -244,8 +214,9 @@ function recordAssistantEdit(session, call, result, before) {
244
214
  });
245
215
  clearEditFailure(session.clientState.safety, filePath);
246
216
  }
247
- export async function executeLocalToolCall(toolContext, session, call) {
248
- session.onStatus(formatToolCallForStatus(call));
217
+ export async function executeLocalToolCall(session, call) {
218
+ session.turnAbortSignal?.throwIfAborted();
219
+ session.onStatus(formatToolCallForStatus(call, session.mcp?.label(call.name)));
249
220
  try {
250
221
  const agentModeBlocked = buildAgentModeToolBlockedResult(session.agentMode, call);
251
222
  if (agentModeBlocked) {
@@ -253,6 +224,11 @@ export async function executeLocalToolCall(toolContext, session, call) {
253
224
  session.onToolEvent?.({ call, result });
254
225
  return result;
255
226
  }
227
+ if (isMcpToolName(call.name)) {
228
+ const result = await sessionMcp(session).execute(session, call);
229
+ session.onToolEvent?.({ call, result });
230
+ return result;
231
+ }
256
232
  const rawEditFilePath = isEditToolName(call.name)
257
233
  ? getEditToolFilePath(call)
258
234
  : '';
@@ -275,10 +251,10 @@ export async function executeLocalToolCall(toolContext, session, call) {
275
251
  const context = {
276
252
  rootDir: session.rootDir,
277
253
  sessionId: session.sessionId,
278
- projectIndex: toolContext.projectIndex,
279
254
  autoYes: session.autoYes,
280
- confirmCommand: session.confirmCommand,
281
- confirmPatch: session.confirmPatch,
255
+ agentMode: session.agentMode,
256
+ grants: session.grants,
257
+ requestPermission: session.requestPermission,
282
258
  requestSudoPassword: session.requestSudoPassword,
283
259
  onStatus: session.onStatus,
284
260
  editJournal: session.clientState.editJournal,
@@ -299,7 +275,6 @@ export async function executeLocalToolCall(toolContext, session, call) {
299
275
  if (result && typeof result === 'object' && commandTracker) {
300
276
  await collectTrackedCommandMutations({
301
277
  session,
302
- projectIndex: toolContext.projectIndex,
303
278
  result,
304
279
  tracker: commandTracker,
305
280
  toolName: call.name,
@@ -326,7 +301,6 @@ export async function executeLocalToolCall(toolContext, session, call) {
326
301
  if (tracked) {
327
302
  await collectTrackedCommandMutations({
328
303
  session,
329
- projectIndex: toolContext.projectIndex,
330
304
  result,
331
305
  tracker: tracked.tracker,
332
306
  toolName: tracked.toolName,