@thegitai/cli 1.0.0-preview.9 → 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 (99) 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 +700 -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 +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 +71 -10
  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/repl.js +1141 -299
  72. package/dist/src/ui/slash-commands.js +140 -0
  73. package/dist/src/ui/tui/attention.js +25 -0
  74. package/dist/src/ui/tui/bridge.js +38 -5
  75. package/dist/src/ui/tui/build-frame.js +858 -303
  76. package/dist/src/ui/tui/composer-layout.js +76 -0
  77. package/dist/src/ui/tui/desktop-notification.js +118 -0
  78. package/dist/src/ui/tui/markdown-render.js +21 -11
  79. package/dist/src/ui/tui/model-label.js +13 -0
  80. package/dist/src/ui/tui/shell-input.js +266 -61
  81. package/dist/src/ui/tui/shortcuts.js +61 -0
  82. package/dist/src/ui/tui/terminal-theme.js +28 -0
  83. package/dist/src/ui/tui/text.js +31 -6
  84. package/dist/src/ui/tui/user-input.js +593 -0
  85. package/dist/src/update-check.js +205 -0
  86. package/dist/src/usage-notice.js +52 -0
  87. package/dist/src/usage.js +25 -2
  88. package/dist/src/utils.js +4 -0
  89. package/dist/src/version.js +52 -2
  90. package/dist/vendor/mcp/LICENSES.txt +414 -0
  91. package/dist/vendor/mcp/client.cjs +82 -0
  92. package/package.json +22 -9
  93. package/dist/src/project-index.js +0 -233
  94. package/dist/src/tools/code-intel.js +0 -472
  95. package/dist/src/tools/find-symbol.js +0 -70
  96. package/dist/src/tools/hover-symbol.js +0 -95
  97. package/dist/src/tools/list-symbols.js +0 -55
  98. package/dist/src/tools/search-code.js +0 -37
  99. 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,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 [];
@@ -153,14 +181,43 @@ function assertSessionNameAvailable(rootDir, name, sessionId, env = process.env)
153
181
  throw new Error(`Session name "${name}" is already used by ${duplicate.id}. Use --session "${name}" to resume it or choose a different name.`);
154
182
  }
155
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
+ }
156
207
  export function pruneSavedSessions(rootDir, env = process.env) {
157
208
  const snapshots = loadAllSnapshots(rootDir, env);
158
209
  const keep = new Set(snapshots.slice(0, MAX_RECENT_SESSIONS).map((snapshot) => snapshot.id));
159
210
  for (const snapshot of snapshots.slice(MAX_RECENT_SESSIONS)) {
160
211
  if (!keep.has(snapshot.id)) {
161
212
  rmSync(getSessionPath(rootDir, snapshot.id, env), { force: true });
213
+ pruneSessionImages(snapshot.id, env);
162
214
  }
163
215
  }
216
+ sweepOrphanSessionImages({
217
+ activeSessionIds: listAllSessionIds(env),
218
+ env,
219
+ });
220
+ sweepGeneratedImages({ env });
164
221
  }
165
222
  export function readGitBranch(rootDir) {
166
223
  try {
@@ -211,6 +268,7 @@ export function saveSessionState(session, env = process.env) {
211
268
  }
212
269
  export function applySessionSnapshot(session, snapshot, options = {}) {
213
270
  const currentAgentMode = session.agentMode;
271
+ const previousSessionId = session.sessionId;
214
272
  session.sessionId = snapshot.id;
215
273
  session.sessionName = snapshot.name;
216
274
  session.sessionCreatedAt = snapshot.createdAt;
@@ -220,6 +278,9 @@ export function applySessionSnapshot(session, snapshot, options = {}) {
220
278
  session.serverState = sanitizeOpaqueState(snapshot.serverState);
221
279
  session.agentMode = options.preserveAgentMode ? currentAgentMode : 'default';
222
280
  session.autoYes = session.agentMode === 'auto-accept';
281
+ if (previousSessionId !== session.sessionId) {
282
+ session.grants = createSessionGrants();
283
+ }
223
284
  session.turnState = {
224
285
  id: null,
225
286
  historyStartIndex: session.history.length,
@@ -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
+ }
@@ -0,0 +1,280 @@
1
+ import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { parseSkillFile } from './frontmatter.js';
5
+ import { BUNDLED_SKILLS, SKILL_ARGUMENT_HINT_MAX_CHARS, SKILL_CONTENT_MAX_CHARS, SKILL_DESCRIPTION_MAX_CHARS, SKILL_FILE_LIST_LIMIT, SKILL_FILE_MAX_BYTES, SKILL_FILE_NAME, SKILL_MAX_ENTRIES, cleanSkillText, isValidSkillName, parseSkillInvocation, } from './types.js';
6
+ const MAX_SKILL_DIRS_PER_ROOT = 300;
7
+ const SKIPPED_LISTING_DIRS = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv']);
8
+ const parsedCache = new Map();
9
+ export function personalSkillsRoot(env = process.env) {
10
+ const home = String(env.THEGITAI_HOME ?? '').trim();
11
+ return path.join(home ? path.resolve(home) : path.join(os.homedir(), '.thegitai'), 'skills');
12
+ }
13
+ export function projectSkillsRoot(rootDir) {
14
+ return path.join(path.resolve(rootDir), '.thegitai', 'skills');
15
+ }
16
+ function safeRealpath(target) {
17
+ try {
18
+ return realpathSync(target);
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ function isInside(parent, child) {
25
+ const relative = path.relative(parent, child);
26
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
27
+ }
28
+ function parseSkill(file, folderName) {
29
+ let stat;
30
+ try {
31
+ stat = statSync(file);
32
+ }
33
+ catch {
34
+ return { ok: false, message: `No ${SKILL_FILE_NAME} in this folder.` };
35
+ }
36
+ if (!stat.isFile())
37
+ return { ok: false, message: `${SKILL_FILE_NAME} is not a file.` };
38
+ if (stat.size > SKILL_FILE_MAX_BYTES) {
39
+ return { ok: false, message: `${SKILL_FILE_NAME} is larger than ${SKILL_FILE_MAX_BYTES / 1024} KB.` };
40
+ }
41
+ const cached = parsedCache.get(file);
42
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
43
+ return cached.result;
44
+ }
45
+ let result;
46
+ try {
47
+ result = interpretSkillFile(readFileSync(file, 'utf8'), folderName);
48
+ }
49
+ catch (error) {
50
+ result = { ok: false, message: `Could not read ${SKILL_FILE_NAME}: ${error.message}` };
51
+ }
52
+ parsedCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, result });
53
+ return result;
54
+ }
55
+ export function interpretSkillFile(text, folderName) {
56
+ const parsed = parseSkillFile(text);
57
+ if (!parsed.ok)
58
+ return { ok: false, message: parsed.error };
59
+ const rawName = parsed.data.name;
60
+ const name = typeof rawName === 'string' && rawName.trim() ? rawName.trim() : folderName;
61
+ if (!isValidSkillName(name)) {
62
+ return {
63
+ ok: false,
64
+ message: `Invalid name "${String(name).slice(0, 80)}": use 1-64 lowercase letters, digits and single hyphens.`,
65
+ };
66
+ }
67
+ if (name !== folderName) {
68
+ return { ok: false, message: `The name "${name}" must match its folder name "${folderName}".` };
69
+ }
70
+ const description = cleanSkillText(parsed.data.description, SKILL_DESCRIPTION_MAX_CHARS);
71
+ if (!description)
72
+ return { ok: false, message: 'Missing description in the frontmatter.' };
73
+ const argumentHint = cleanSkillText(parsed.data['argument-hint'], SKILL_ARGUMENT_HINT_MAX_CHARS);
74
+ return {
75
+ ok: true,
76
+ skill: {
77
+ name,
78
+ description,
79
+ typedOnly: parsed.data['disable-model-invocation'] === true,
80
+ ...(argumentHint ? { argumentHint } : {}),
81
+ },
82
+ body: parsed.body,
83
+ };
84
+ }
85
+ function scanRoot(root, scope, containment) {
86
+ const skills = [];
87
+ const problems = [];
88
+ let entries;
89
+ try {
90
+ entries = readdirSync(root, { withFileTypes: true });
91
+ }
92
+ catch {
93
+ return { skills, problems };
94
+ }
95
+ const folders = entries
96
+ .filter((entry) => !entry.name.startsWith('.'))
97
+ .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
98
+ .map((entry) => entry.name)
99
+ .sort((a, b) => a.localeCompare(b))
100
+ .slice(0, MAX_SKILL_DIRS_PER_ROOT);
101
+ for (const folder of folders) {
102
+ const dir = path.join(root, folder);
103
+ let isDirectory = false;
104
+ try {
105
+ isDirectory = statSync(dir).isDirectory();
106
+ }
107
+ catch {
108
+ isDirectory = false;
109
+ }
110
+ if (!isDirectory)
111
+ continue;
112
+ const file = path.join(dir, SKILL_FILE_NAME);
113
+ if (containment) {
114
+ const realFile = safeRealpath(file);
115
+ if (realFile && !isInside(containment, realFile)) {
116
+ problems.push({ scope, dir, message: `${SKILL_FILE_NAME} links outside the project, so it was not loaded.` });
117
+ continue;
118
+ }
119
+ }
120
+ const parsed = parseSkill(file, folder);
121
+ if (!parsed.ok) {
122
+ problems.push({ scope, dir, message: parsed.message });
123
+ continue;
124
+ }
125
+ skills.push({ ...parsed.skill, scope, dir, file });
126
+ }
127
+ return { skills, problems };
128
+ }
129
+ export function discoverSkills(rootDir, env = process.env) {
130
+ const personalRoot = personalSkillsRoot(env);
131
+ const projectRootCandidate = projectSkillsRoot(rootDir);
132
+ const samePlace = path.resolve(projectRootCandidate) === path.resolve(personalRoot) ||
133
+ (safeRealpath(projectRootCandidate) ?? '') === (safeRealpath(personalRoot) ?? ' ');
134
+ const projectRoot = samePlace ? null : projectRootCandidate;
135
+ const personal = scanRoot(personalRoot, 'personal', null);
136
+ const projectContainment = safeRealpath(path.resolve(rootDir));
137
+ const project = projectRoot
138
+ ? scanRoot(projectRoot, 'project', projectContainment)
139
+ : { skills: [], problems: [] };
140
+ const skills = [];
141
+ const shadowed = [];
142
+ const seen = new Set();
143
+ for (const skill of [...personal.skills, ...project.skills]) {
144
+ if (seen.has(skill.name)) {
145
+ shadowed.push(skill);
146
+ continue;
147
+ }
148
+ seen.add(skill.name);
149
+ skills.push(skill);
150
+ }
151
+ const problems = [...personal.problems, ...project.problems];
152
+ for (const extra of skills.splice(SKILL_MAX_ENTRIES)) {
153
+ problems.push({ scope: extra.scope, dir: extra.dir, message: `Only the first ${SKILL_MAX_ENTRIES} skills are loaded.` });
154
+ }
155
+ return { personalRoot, projectRoot, skills, shadowed, problems };
156
+ }
157
+ export function skillCatalogue(discovery) {
158
+ return discovery.skills.map((skill) => ({
159
+ name: skill.name,
160
+ description: skill.description,
161
+ scope: skill.scope,
162
+ ...(skill.typedOnly ? { typedOnly: true } : {}),
163
+ ...(skill.argumentHint ? { argumentHint: skill.argumentHint } : {}),
164
+ }));
165
+ }
166
+ export function bundledSkillNamed(name) {
167
+ return BUNDLED_SKILLS.find((skill) => skill.name === name) ?? null;
168
+ }
169
+ export function findSkill(discovery, name) {
170
+ return discovery.skills.find((skill) => skill.name === name) ?? null;
171
+ }
172
+ function listSkillFiles(dir) {
173
+ const files = [];
174
+ let truncated = false;
175
+ const walk = (current, depth) => {
176
+ if (truncated)
177
+ return;
178
+ if (depth > 4) {
179
+ truncated = true;
180
+ return;
181
+ }
182
+ let entries;
183
+ try {
184
+ entries = readdirSync(current, { withFileTypes: true });
185
+ }
186
+ catch {
187
+ return;
188
+ }
189
+ entries.sort((a, b) => a.name.localeCompare(b.name));
190
+ for (const entry of entries) {
191
+ if (entry.name.startsWith('.') || SKIPPED_LISTING_DIRS.has(entry.name))
192
+ continue;
193
+ const full = path.join(current, entry.name);
194
+ if (entry.isDirectory()) {
195
+ walk(full, depth + 1);
196
+ continue;
197
+ }
198
+ if (!entry.isFile())
199
+ continue;
200
+ const relative = path.relative(dir, full).split(path.sep).join('/');
201
+ if (relative === SKILL_FILE_NAME)
202
+ continue;
203
+ if (files.length >= SKILL_FILE_LIST_LIMIT) {
204
+ truncated = true;
205
+ return;
206
+ }
207
+ files.push(relative);
208
+ }
209
+ };
210
+ walk(dir, 0);
211
+ return { files, truncated };
212
+ }
213
+ export function loadSkillContent(skill) {
214
+ const parsed = parseSkill(skill.file, path.basename(skill.dir));
215
+ if (!parsed.ok)
216
+ return { ok: false, error: parsed.message };
217
+ const truncated = parsed.body.length > SKILL_CONTENT_MAX_CHARS;
218
+ const listing = listSkillFiles(skill.dir);
219
+ return {
220
+ ok: true,
221
+ content: truncated ? parsed.body.slice(0, SKILL_CONTENT_MAX_CHARS) : parsed.body,
222
+ truncated,
223
+ files: listing.files,
224
+ filesTruncated: listing.truncated,
225
+ };
226
+ }
227
+ export function isSkillsRelativePath(relPath) {
228
+ const normalized = relPath.replace(/\\/g, '/').replace(/^\.\//, '');
229
+ return normalized.startsWith('.thegitai/skills/') && !normalized.split('/').includes('..');
230
+ }
231
+ export function isInsidePersonalSkills(absPath, env = process.env) {
232
+ const root = path.resolve(personalSkillsRoot(env));
233
+ const target = path.resolve(absPath);
234
+ return target !== root && isInside(root, target);
235
+ }
236
+ export function collectSkillRequest(rootDir, env, input) {
237
+ let discovery;
238
+ try {
239
+ discovery = discoverSkills(rootDir, env);
240
+ }
241
+ catch {
242
+ return { skills: [] };
243
+ }
244
+ const skills = skillCatalogue(discovery);
245
+ const invocation = parseSkillInvocation(input);
246
+ let invokedSkill;
247
+ if (invocation) {
248
+ const local = findSkill(discovery, invocation.name);
249
+ if (local) {
250
+ const loaded = loadSkillContent(local);
251
+ if (loaded.ok) {
252
+ invokedSkill = {
253
+ name: local.name,
254
+ arguments: invocation.arguments,
255
+ scope: local.scope,
256
+ dir: local.dir,
257
+ content: loaded.content,
258
+ ...(loaded.truncated ? { contentTruncated: true } : {}),
259
+ files: loaded.files,
260
+ ...(loaded.filesTruncated ? { filesTruncated: true } : {}),
261
+ };
262
+ }
263
+ }
264
+ else if (bundledSkillNamed(invocation.name)) {
265
+ invokedSkill = {
266
+ name: invocation.name,
267
+ arguments: invocation.arguments,
268
+ scope: 'bundled',
269
+ ...skillFolders(rootDir, env),
270
+ };
271
+ }
272
+ }
273
+ return { skills, ...(invokedSkill ? { invokedSkill } : {}) };
274
+ }
275
+ export function skillFolders(rootDir, env) {
276
+ return {
277
+ personalSkillsDir: personalSkillsRoot(env),
278
+ projectSkillsDir: projectSkillsRoot(rootDir),
279
+ };
280
+ }