@thegitai/cli 1.0.0-preview.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +301 -15
  3. package/dist/bin/ai.js +142 -112
  4. package/dist/bin/browser-host.js +284 -0
  5. package/dist/src/agent-mode.js +33 -7
  6. package/dist/src/api/auth.js +8 -2
  7. package/dist/src/api/browser-login.js +147 -35
  8. package/dist/src/api/chat.js +703 -166
  9. package/dist/src/api/contracts.js +55 -1
  10. package/dist/src/api/default-host.js +1 -0
  11. package/dist/src/api/http.js +168 -8
  12. package/dist/src/api/models.js +47 -9
  13. package/dist/src/api/startup-handshake.js +36 -0
  14. package/dist/src/api/turn-recovery.js +189 -0
  15. package/dist/src/background-jobs.js +8 -2
  16. package/dist/src/browser/bridge.js +268 -0
  17. package/dist/src/browser/chrome-profiles.js +73 -0
  18. package/dist/src/browser/framing.js +42 -0
  19. package/dist/src/browser/native-host.js +219 -0
  20. package/dist/src/browser/protocol.js +46 -0
  21. package/dist/src/browser/session-bridge.js +130 -0
  22. package/dist/src/cli-args.js +19 -5
  23. package/dist/src/client-environment.js +2 -0
  24. package/dist/src/core/clipboard.js +8 -14
  25. package/dist/src/core/image-limits.js +56 -0
  26. package/dist/src/core/image-path-extractor.js +70 -3
  27. package/dist/src/core/session-image-store.js +246 -0
  28. package/dist/src/edit-journal.js +33 -2
  29. package/dist/src/executor.js +26 -4
  30. package/dist/src/help-text.js +152 -41
  31. package/dist/src/install-id.js +32 -0
  32. package/dist/src/job-follow-up.js +40 -0
  33. package/dist/src/mcp-client.js +335 -0
  34. package/dist/src/mcp-command.js +176 -0
  35. package/dist/src/mcp-config.js +123 -0
  36. package/dist/src/mcp-sdk.js +3 -0
  37. package/dist/src/mcp-types.js +26 -0
  38. package/dist/src/patcher.js +46 -4
  39. package/dist/src/permissions.js +301 -0
  40. package/dist/src/preferences.js +39 -0
  41. package/dist/src/project-key.js +11 -0
  42. package/dist/src/project-model-preferences.js +74 -0
  43. package/dist/src/quota-notice.js +62 -0
  44. package/dist/src/reasoning-effort.js +27 -0
  45. package/dist/src/session-safety.js +0 -12
  46. package/dist/src/session-store.js +123 -30
  47. package/dist/src/session.js +12 -4
  48. package/dist/src/signin.js +58 -0
  49. package/dist/src/skills/discovery.js +280 -0
  50. package/dist/src/skills/frontmatter.js +192 -0
  51. package/dist/src/skills/install.js +394 -0
  52. package/dist/src/skills/types.js +43 -0
  53. package/dist/src/skills-command.js +71 -0
  54. package/dist/src/tool-executor.js +41 -51
  55. package/dist/src/tools/browser.js +928 -0
  56. package/dist/src/tools/delete-file.js +21 -5
  57. package/dist/src/tools/index.js +34 -10
  58. package/dist/src/tools/patch-file.js +14 -29
  59. package/dist/src/tools/read-file.js +7 -1
  60. package/dist/src/tools/read-image-file.js +85 -0
  61. package/dist/src/tools/replace-document-text.js +28 -18
  62. package/dist/src/tools/restore-checkpoint.js +1 -2
  63. package/dist/src/tools/run-command.js +14 -71
  64. package/dist/src/tools/run-node-script.js +12 -81
  65. package/dist/src/tools/save-generated-image.js +120 -0
  66. package/dist/src/tools/shell-diagnostics.js +246 -72
  67. package/dist/src/tools/str-replace.js +14 -29
  68. package/dist/src/tools/undo-edit.js +2 -7
  69. package/dist/src/tools/use-skill.js +38 -0
  70. package/dist/src/tools/write-file.js +69 -14
  71. package/dist/src/ui/prompt-history-store.js +1 -1
  72. package/dist/src/ui/repl.js +1155 -301
  73. package/dist/src/ui/slash-commands.js +140 -0
  74. package/dist/src/ui/tui/attention.js +25 -0
  75. package/dist/src/ui/tui/bridge.js +38 -5
  76. package/dist/src/ui/tui/build-frame.js +903 -304
  77. package/dist/src/ui/tui/composer-layout.js +76 -0
  78. package/dist/src/ui/tui/desktop-notification.js +118 -0
  79. package/dist/src/ui/tui/markdown-render.js +21 -11
  80. package/dist/src/ui/tui/model-label.js +13 -0
  81. package/dist/src/ui/tui/shell-input.js +266 -61
  82. package/dist/src/ui/tui/shortcuts.js +61 -0
  83. package/dist/src/ui/tui/terminal-theme.js +28 -0
  84. package/dist/src/ui/tui/text.js +31 -6
  85. package/dist/src/ui/tui/user-input.js +593 -0
  86. package/dist/src/update-check.js +205 -0
  87. package/dist/src/usage-notice.js +52 -0
  88. package/dist/src/usage.js +25 -2
  89. package/dist/src/utils.js +13 -0
  90. package/dist/src/version.js +52 -2
  91. package/dist/vendor/mcp/LICENSES.txt +414 -0
  92. package/dist/vendor/mcp/client.cjs +82 -0
  93. package/package.json +22 -9
  94. package/dist/src/project-index.js +0 -233
  95. package/dist/src/tools/code-intel.js +0 -472
  96. package/dist/src/tools/find-symbol.js +0 -70
  97. package/dist/src/tools/hover-symbol.js +0 -95
  98. package/dist/src/tools/list-symbols.js +0 -55
  99. package/dist/src/tools/search-code.js +0 -37
  100. package/dist/src/tools/signature-help.js +0 -118
@@ -0,0 +1,62 @@
1
+ import { isPlanRequiredError, isQuotaExceededError, ServerApiError } from './api/http.js';
2
+ import { USAGE_WINDOWS, formatUtcMinute, usageWindowLabel } from './usage.js';
3
+ export function buildQuotaNotice(error) {
4
+ if (!(error instanceof ServerApiError) || !isQuotaExceededError(error)) {
5
+ return null;
6
+ }
7
+ const label = usageWindowLabel(String(error.details.window ?? ''));
8
+ const inSentence = label.toLowerCase();
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
+ }
23
+ const lines = [];
24
+ if (label) {
25
+ lines.push(knownReset
26
+ ? `You've used your ${inSentence} limit. It resets at ${knownReset}.`
27
+ : `You've used your ${inSentence} limit.`);
28
+ }
29
+ else {
30
+ lines.push(firstMessageLine(error));
31
+ }
32
+ if (error.details.upgradeUrl) {
33
+ lines.push(`Upgrade for more usage at ${error.details.upgradeUrl}`);
34
+ }
35
+ lines.push(label
36
+ ? `Run /usage to see your ${otherWindowNames(label)} windows.`
37
+ : 'Run /usage to see your remaining usage.');
38
+ return { title: 'Usage limit reached', body: lines.join('\n') };
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
+ }
52
+ function otherWindowNames(usedLabel) {
53
+ const names = USAGE_WINDOWS.map(([name]) => name)
54
+ .filter((name) => name !== usedLabel)
55
+ .map((name) => name.toLowerCase());
56
+ return names.length > 1
57
+ ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`
58
+ : (names[0] ?? '');
59
+ }
60
+ function firstMessageLine(error) {
61
+ return String(error.message ?? '').split('\n')[0]?.trim() || 'Usage limit reached.';
62
+ }
@@ -0,0 +1,27 @@
1
+ export const REASONING_EFFORTS = ['default', 'low', 'balanced', 'deep'];
2
+ export const REASONING_EFFORT_LABELS = {
3
+ default: 'Default',
4
+ low: 'Low',
5
+ balanced: 'Balanced',
6
+ deep: 'Deep',
7
+ };
8
+ export const REASONING_EFFORT_DESCRIPTIONS = {
9
+ default: 'Uses our recommended setting for this model.',
10
+ low: 'Favors quicker responses and lower reasoning cost.',
11
+ balanced: 'Balances reasoning depth, speed, and cost.',
12
+ deep: 'Favors thorough reasoning; may take longer and cost more.',
13
+ };
14
+ export function isReasoningEffort(value) {
15
+ return REASONING_EFFORTS.some((effort) => effort === value);
16
+ }
17
+ export function normalizeReasoningEffort(value) {
18
+ if (value === undefined)
19
+ return 'default';
20
+ if (isReasoningEffort(value))
21
+ return value;
22
+ throw new Error('Invalid reasoning effort. Choose Default, Low, Balanced, or Deep.');
23
+ }
24
+ export function cycleReasoningEffort(effort, direction) {
25
+ const index = REASONING_EFFORTS.indexOf(effort);
26
+ return REASONING_EFFORTS[(index + direction + REASONING_EFFORTS.length) % REASONING_EFFORTS.length];
27
+ }
@@ -4,7 +4,6 @@ import path from 'node:path';
4
4
  import { ARTIFACT_IGNORE_DIRS, normalizeProjectRelativePath, shouldIgnoreArtifactPath, } from './artifact-policy.js';
5
5
  import { hashBytes, readFileEditSnapshot, storedContentBuffer, } from './edit-journal.js';
6
6
  import { deleteProjectFile, resolveProjectPath, writeProjectFile, writeProjectFileBuffer, } from './patcher.js';
7
- import { removeIndexFile, upsertIndexFile } from './project-index.js';
8
7
  const MAX_CHECKPOINTS = 20;
9
8
  const MAX_SESSION_EDITS = 500;
10
9
  const MAX_READ_RECORDS = 200;
@@ -672,7 +671,6 @@ export async function restoreCheckpointFiles(args) {
672
671
  const restored = [];
673
672
  const applied = [];
674
673
  let changed = false;
675
- const syncPolicy = args.projectIndex.initialized;
676
674
  for (const snapshot of targets) {
677
675
  const before = readFileEditSnapshot(args.rootDir, snapshot.filePath);
678
676
  try {
@@ -680,15 +678,11 @@ export async function restoreCheckpointFiles(args) {
680
678
  const result = writeStoredProjectFile(args.rootDir, snapshot.filePath, snapshot.content ?? '', snapshot.contentEncoding);
681
679
  if (result.changed)
682
680
  changed = true;
683
- if (syncPolicy)
684
- await upsertIndexFile(args.projectIndex, snapshot.filePath);
685
681
  }
686
682
  else {
687
683
  const result = deleteProjectFile(args.rootDir, snapshot.filePath);
688
684
  if (result.deleted)
689
685
  changed = true;
690
- if (syncPolicy)
691
- await removeIndexFile(args.projectIndex, snapshot.filePath);
692
686
  }
693
687
  const after = readFileEditSnapshot(args.rootDir, snapshot.filePath);
694
688
  applied.push({ snapshot, before, after });
@@ -710,15 +704,9 @@ export async function restoreCheckpointFiles(args) {
710
704
  throw new Error('previous file content is unavailable');
711
705
  }
712
706
  writeStoredProjectFile(args.rootDir, item.snapshot.filePath, item.before.content, item.before.contentEncoding);
713
- if (syncPolicy) {
714
- await upsertIndexFile(args.projectIndex, item.snapshot.filePath);
715
- }
716
707
  }
717
708
  else {
718
709
  deleteProjectFile(args.rootDir, item.snapshot.filePath);
719
- if (syncPolicy) {
720
- await removeIndexFile(args.projectIndex, item.snapshot.filePath);
721
- }
722
710
  }
723
711
  rolledBack.push({ filePath: item.snapshot.filePath });
724
712
  }
@@ -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,
@@ -79,6 +83,7 @@ export function startNewConversation(session) {
79
83
  }
80
84
  export function clearConversation(session) {
81
85
  session.history = [];
86
+ session.grants = createSessionGrants();
82
87
  session.serverState = preserveProviderSelection(session.serverState);
83
88
  session.turnState = {
84
89
  id: null,
@@ -94,7 +99,10 @@ export function clearConversation(session) {
94
99
  safety: createSessionSafetyState(),
95
100
  };
96
101
  }
97
- export async function disposeSession(_session) { }
102
+ export async function disposeSession(session) {
103
+ closeBrowserBridge();
104
+ await session.mcp?.close();
105
+ }
98
106
  export function switchModel(session, modelId) {
99
107
  session.modelId = Number(modelId);
100
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
+ }