@thegitai/cli 1.0.0-preview.9 → 1.0.1

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 (102) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +301 -15
  3. package/dist/bin/ai.js +139 -111
  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 +77 -34
  8. package/dist/src/api/chat.js +702 -173
  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 +75 -10
  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 +14 -4
  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 +271 -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/scratch-dir.js +6 -2
  46. package/dist/src/session-context.js +11 -0
  47. package/dist/src/session-safety.js +0 -12
  48. package/dist/src/session-store.js +76 -10
  49. package/dist/src/session.js +14 -4
  50. package/dist/src/signin.js +58 -0
  51. package/dist/src/skills/discovery.js +280 -0
  52. package/dist/src/skills/frontmatter.js +192 -0
  53. package/dist/src/skills/install.js +394 -0
  54. package/dist/src/skills/types.js +43 -0
  55. package/dist/src/skills-command.js +71 -0
  56. package/dist/src/todo-list.js +16 -9
  57. package/dist/src/tool-executor.js +42 -51
  58. package/dist/src/tools/browser.js +928 -0
  59. package/dist/src/tools/delete-file.js +21 -5
  60. package/dist/src/tools/index.js +34 -10
  61. package/dist/src/tools/patch-file.js +14 -29
  62. package/dist/src/tools/read-file.js +7 -1
  63. package/dist/src/tools/read-image-file.js +85 -0
  64. package/dist/src/tools/replace-document-text.js +28 -18
  65. package/dist/src/tools/restore-checkpoint.js +1 -2
  66. package/dist/src/tools/run-command.js +14 -71
  67. package/dist/src/tools/run-node-script.js +13 -82
  68. package/dist/src/tools/save-generated-image.js +120 -0
  69. package/dist/src/tools/shell-diagnostics.js +248 -72
  70. package/dist/src/tools/str-replace.js +14 -29
  71. package/dist/src/tools/undo-edit.js +2 -7
  72. package/dist/src/tools/use-skill.js +38 -0
  73. package/dist/src/tools/write-file.js +69 -14
  74. package/dist/src/ui/repl.js +1141 -299
  75. package/dist/src/ui/slash-commands.js +140 -0
  76. package/dist/src/ui/tui/attention.js +25 -0
  77. package/dist/src/ui/tui/bridge.js +38 -5
  78. package/dist/src/ui/tui/build-frame.js +858 -303
  79. package/dist/src/ui/tui/composer-layout.js +76 -0
  80. package/dist/src/ui/tui/desktop-notification.js +118 -0
  81. package/dist/src/ui/tui/markdown-render.js +21 -11
  82. package/dist/src/ui/tui/model-label.js +13 -0
  83. package/dist/src/ui/tui/shell-input.js +266 -61
  84. package/dist/src/ui/tui/shortcuts.js +61 -0
  85. package/dist/src/ui/tui/terminal-theme.js +28 -0
  86. package/dist/src/ui/tui/text.js +31 -6
  87. package/dist/src/ui/tui/user-input.js +593 -0
  88. package/dist/src/update-check.js +205 -0
  89. package/dist/src/usage-notice.js +52 -0
  90. package/dist/src/usage.js +25 -2
  91. package/dist/src/utils.js +4 -0
  92. package/dist/src/version.js +52 -2
  93. package/dist/vendor/mcp/LICENSES.txt +414 -0
  94. package/dist/vendor/mcp/client.cjs +82 -0
  95. package/package.json +22 -9
  96. package/dist/src/project-index.js +0 -233
  97. package/dist/src/tools/code-intel.js +0 -472
  98. package/dist/src/tools/find-symbol.js +0 -70
  99. package/dist/src/tools/hover-symbol.js +0 -95
  100. package/dist/src/tools/list-symbols.js +0 -55
  101. package/dist/src/tools/search-code.js +0 -37
  102. 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
+ }
@@ -1,18 +1,22 @@
1
1
  import { chmodSync, lstatSync, mkdtempSync } from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
+ import { scopedSessionId } from './session-context.js';
4
5
  const scratchDirs = new Map();
5
6
  let activeSessionId = 'default';
6
7
  export function setScratchSession(sessionId) {
7
8
  activeSessionId = String(sessionId ?? '').trim() || 'default';
8
9
  }
10
+ function currentKey() {
11
+ return scopedSessionId() ?? activeSessionId;
12
+ }
9
13
  function allocateSessionScratchDir() {
10
14
  const dir = mkdtempSync(path.join(os.tmpdir(), 'thegitai-'));
11
- scratchDirs.set(activeSessionId, dir);
15
+ scratchDirs.set(currentKey(), dir);
12
16
  return dir;
13
17
  }
14
18
  export function sessionScratchDir() {
15
- return scratchDirs.get(activeSessionId) ?? allocateSessionScratchDir();
19
+ return scratchDirs.get(currentKey()) ?? allocateSessionScratchDir();
16
20
  }
17
21
  function isOwnedDirectory(dir) {
18
22
  try {
@@ -0,0 +1,11 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ const storage = new AsyncLocalStorage();
3
+ export function runWithSession(sessionId, fn) {
4
+ const id = String(sessionId ?? '').trim();
5
+ if (!id)
6
+ return fn();
7
+ return storage.run(id, fn);
8
+ }
9
+ export function scopedSessionId() {
10
+ return storage.getStore() ?? null;
11
+ }
@@ -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,13 +1,17 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
4
3
  import path from 'node:path';
5
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';
6
8
  import { normalizeAssistantEditJournal } from './edit-journal.js';
9
+ import { createSessionGrants } from './permissions.js';
7
10
  import { cloneSessionSafetyState, createSessionSafetyState, mergeLocalSessionSafetyState, normalizeSessionSafetyState, } from './session-safety.js';
8
11
  import { singleLinePreview } from './utils.js';
9
12
  const SESSION_STORE_VERSION = 1;
10
13
  export const MAX_RECENT_SESSIONS = 10;
14
+ export { getSessionProjectKey };
11
15
  function cloneJson(value) {
12
16
  return JSON.parse(JSON.stringify(value ?? null));
13
17
  }
@@ -55,15 +59,6 @@ function safeSessionFileName(id) {
55
59
  function getSessionBaseDir(env = process.env) {
56
60
  return getClientStateDir(env);
57
61
  }
58
- export function getSessionProjectKey(rootDir) {
59
- const resolvedRoot = path.resolve(rootDir);
60
- const projectName = path.basename(resolvedRoot).replace(/[^a-zA-Z0-9._-]/g, '_') || 'project';
61
- const hash = createHash('sha256')
62
- .update(resolvedRoot)
63
- .digest('hex')
64
- .slice(0, 16);
65
- return `${projectName}-${hash}`;
66
- }
67
62
  function getSessionProjectDir(rootDir, env = process.env) {
68
63
  return path.join(getSessionBaseDir(env), 'sessions', 'projects', getSessionProjectKey(rootDir));
69
64
  }
@@ -84,6 +79,39 @@ function normalizeBranch(value) {
84
79
  .trim();
85
80
  return text ? text.slice(0, 120) : null;
86
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
+ }
87
115
  function normalizeHistory(value) {
88
116
  if (!Array.isArray(value))
89
117
  return [];
@@ -115,6 +143,7 @@ function normalizeSnapshot(raw, rootDir) {
115
143
  updatedAt: normalizeIsoDate(raw.updatedAt),
116
144
  modelId,
117
145
  branch: normalizeBranch(raw.branch),
146
+ lastPromptAt: raw.lastPromptAt ? normalizeIsoDate(raw.lastPromptAt) : null,
118
147
  history: cloneJson(normalizeHistory(raw.history)),
119
148
  clientState: sanitizeClientState(raw.clientState),
120
149
  serverState: sanitizeOpaqueState(raw.serverState),
@@ -153,14 +182,43 @@ function assertSessionNameAvailable(rootDir, name, sessionId, env = process.env)
153
182
  throw new Error(`Session name "${name}" is already used by ${duplicate.id}. Use --session "${name}" to resume it or choose a different name.`);
154
183
  }
155
184
  }
185
+ function listAllSessionIds(env = process.env) {
186
+ const ids = new Set();
187
+ const projectsDir = path.join(getSessionBaseDir(env), 'sessions', 'projects');
188
+ if (!existsSync(projectsDir))
189
+ return ids;
190
+ try {
191
+ for (const project of readdirSync(projectsDir)) {
192
+ const dir = path.join(projectsDir, project);
193
+ try {
194
+ for (const file of readdirSync(dir)) {
195
+ if (file.endsWith('.json'))
196
+ ids.add(path.basename(file, '.json'));
197
+ }
198
+ }
199
+ catch {
200
+ }
201
+ }
202
+ }
203
+ catch {
204
+ return ids;
205
+ }
206
+ return ids;
207
+ }
156
208
  export function pruneSavedSessions(rootDir, env = process.env) {
157
209
  const snapshots = loadAllSnapshots(rootDir, env);
158
210
  const keep = new Set(snapshots.slice(0, MAX_RECENT_SESSIONS).map((snapshot) => snapshot.id));
159
211
  for (const snapshot of snapshots.slice(MAX_RECENT_SESSIONS)) {
160
212
  if (!keep.has(snapshot.id)) {
161
213
  rmSync(getSessionPath(rootDir, snapshot.id, env), { force: true });
214
+ pruneSessionImages(snapshot.id, env);
162
215
  }
163
216
  }
217
+ sweepOrphanSessionImages({
218
+ activeSessionIds: listAllSessionIds(env),
219
+ env,
220
+ });
221
+ sweepGeneratedImages({ env });
164
222
  }
165
223
  export function readGitBranch(rootDir) {
166
224
  try {
@@ -192,6 +250,7 @@ export function snapshotFromSession(session) {
192
250
  updatedAt: now,
193
251
  modelId: session.modelId,
194
252
  branch: readGitBranch(session.rootDir),
253
+ lastPromptAt: session.sessionLastPromptAt ?? null,
195
254
  history: cloneJson(session.history),
196
255
  clientState: {
197
256
  editCounter: session.clientState.editCounter,
@@ -211,15 +270,21 @@ export function saveSessionState(session, env = process.env) {
211
270
  }
212
271
  export function applySessionSnapshot(session, snapshot, options = {}) {
213
272
  const currentAgentMode = session.agentMode;
273
+ const previousSessionId = session.sessionId;
214
274
  session.sessionId = snapshot.id;
215
275
  session.sessionName = snapshot.name;
216
276
  session.sessionCreatedAt = snapshot.createdAt;
217
277
  session.sessionUpdatedAt = snapshot.updatedAt;
278
+ session.sessionLastPromptAt =
279
+ snapshot.lastPromptAt ?? session.sessionLastPromptAt ?? null;
218
280
  session.modelId = Number(options.modelOverride ?? snapshot.modelId);
219
281
  session.history = cloneJson(snapshot.history);
220
282
  session.serverState = sanitizeOpaqueState(snapshot.serverState);
221
283
  session.agentMode = options.preserveAgentMode ? currentAgentMode : 'default';
222
284
  session.autoYes = session.agentMode === 'auto-accept';
285
+ if (previousSessionId !== session.sessionId) {
286
+ session.grants = createSessionGrants();
287
+ }
223
288
  session.turnState = {
224
289
  id: null,
225
290
  historyStartIndex: session.history.length,
@@ -281,6 +346,7 @@ function metadataFromSnapshot(snapshot) {
281
346
  lastUserMessage: extractFirstUserPrompt(snapshot.history),
282
347
  summaryPreview: '',
283
348
  branch: snapshot.branch ?? null,
349
+ lastPromptAt: snapshot.lastPromptAt ?? null,
284
350
  };
285
351
  }
286
352
  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,18 +42,21 @@ 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,
52
56
  sessionName,
53
57
  sessionCreatedAt: createdAt,
54
58
  sessionUpdatedAt: createdAt,
59
+ sessionLastPromptAt: null,
55
60
  modelId: Number(modelId),
56
61
  turnState: {
57
62
  id: null,
@@ -76,9 +81,11 @@ export function startNewConversation(session) {
76
81
  session.sessionName = null;
77
82
  session.sessionCreatedAt = createdAt;
78
83
  session.sessionUpdatedAt = createdAt;
84
+ session.sessionLastPromptAt = null;
79
85
  }
80
86
  export function clearConversation(session) {
81
87
  session.history = [];
88
+ session.grants = createSessionGrants();
82
89
  session.serverState = preserveProviderSelection(session.serverState);
83
90
  session.turnState = {
84
91
  id: null,
@@ -94,7 +101,10 @@ export function clearConversation(session) {
94
101
  safety: createSessionSafetyState(),
95
102
  };
96
103
  }
97
- export async function disposeSession(_session) { }
104
+ export async function disposeSession(session) {
105
+ closeBrowserBridge();
106
+ await session.mcp?.close();
107
+ }
98
108
  export function switchModel(session, modelId) {
99
109
  session.modelId = Number(modelId);
100
110
  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
+ }