@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
@@ -1,5 +1,5 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { existsSync, readFileSync } from 'node:fs';
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync, readFileSync, statSync } from 'node:fs';
3
3
  import { builtinModules } from 'node:module';
4
4
  import path from 'node:path';
5
5
  const CHECK_TIMEOUT = 60000;
@@ -36,37 +36,34 @@ function detectLanguageFromProject(rootDir) {
36
36
  return 'python';
37
37
  return null;
38
38
  }
39
- function commandExists(cmd) {
40
- try {
41
- execFileSync(cmd, ['--version'], {
42
- timeout: 5000,
43
- stdio: 'pipe',
39
+ function execCheck(cmd, args, options) {
40
+ return new Promise((resolve) => {
41
+ execFile(cmd, args, {
42
+ cwd: options.cwd,
44
43
  encoding: 'utf-8',
44
+ maxBuffer: MAX_RAW_OUTPUT,
45
+ timeout: options.timeout,
46
+ }, (error, stdout, stderr) => {
47
+ const code = error?.code;
48
+ resolve({
49
+ stdout: String(stdout ?? ''),
50
+ stderr: String(stderr ?? ''),
51
+ exitCode: error ? (typeof code === 'number' ? code : 1) : 0,
52
+ });
45
53
  });
46
- return true;
47
- }
48
- catch {
49
- return false;
54
+ });
55
+ }
56
+ const commandChecks = new Map();
57
+ function commandExists(cmd) {
58
+ let check = commandChecks.get(cmd);
59
+ if (!check) {
60
+ check = execCheck(cmd, ['--version'], { timeout: 5000 }).then((result) => result.exitCode === 0);
61
+ commandChecks.set(cmd, check);
50
62
  }
63
+ return check;
51
64
  }
52
65
  function runCheck(cmd, args, rootDir) {
53
- try {
54
- const stdout = execFileSync(cmd, args, {
55
- cwd: rootDir,
56
- encoding: 'utf-8',
57
- maxBuffer: MAX_RAW_OUTPUT,
58
- timeout: CHECK_TIMEOUT,
59
- stdio: ['pipe', 'pipe', 'pipe'],
60
- });
61
- return { stdout, stderr: '', exitCode: 0 };
62
- }
63
- catch (err) {
64
- return {
65
- stdout: err.stdout ?? '',
66
- stderr: err.stderr ?? '',
67
- exitCode: err.status ?? 1,
68
- };
69
- }
66
+ return execCheck(cmd, args, { cwd: rootDir, timeout: CHECK_TIMEOUT });
70
67
  }
71
68
  function parseRustDiagnostics(stdout, rootDir) {
72
69
  const diagnostics = [];
@@ -114,12 +111,12 @@ function parseRustDiagnostics(stdout, rootDir) {
114
111
  }
115
112
  return diagnostics;
116
113
  }
117
- function runRustCheck(rootDir) {
114
+ async function runRustCheck(rootDir) {
118
115
  if (!existsSync(path.join(rootDir, 'Cargo.toml')))
119
116
  return null;
120
- if (!commandExists('cargo'))
117
+ if (!(await commandExists('cargo')))
121
118
  return null;
122
- const result = runCheck('cargo', ['check', '--message-format=json', '--quiet'], rootDir);
119
+ const result = await runCheck('cargo', ['check', '--message-format=json', '--quiet'], rootDir);
123
120
  return parseRustDiagnostics(`${result.stdout}\n${result.stderr}`, rootDir);
124
121
  }
125
122
  const GO_DIAG_RE = /^(.+?):(\d+):(\d+):\s*(.+)$/;
@@ -149,12 +146,12 @@ function parseGoDiagnostics(output, rootDir) {
149
146
  }
150
147
  return diagnostics;
151
148
  }
152
- function runGoCheck(rootDir) {
149
+ async function runGoCheck(rootDir) {
153
150
  if (!existsSync(path.join(rootDir, 'go.mod')))
154
151
  return null;
155
- if (!commandExists('go'))
152
+ if (!(await commandExists('go')))
156
153
  return null;
157
- const result = runCheck('go', ['build', './...'], rootDir);
154
+ const result = await runCheck('go', ['build', './...'], rootDir);
158
155
  return parseGoDiagnostics(`${result.stdout}\n${result.stderr}`, rootDir);
159
156
  }
160
157
  function parseRuffDiagnostics(stdout, rootDir) {
@@ -214,14 +211,14 @@ function parsePyCompileDiagnostics(stderr, rootDir, filePath) {
214
211
  },
215
212
  ];
216
213
  }
217
- function runPythonCheck(rootDir, filePath) {
218
- if (commandExists('ruff')) {
214
+ async function runPythonCheck(rootDir, filePath) {
215
+ if (await commandExists('ruff')) {
219
216
  const target = filePath || '.';
220
- const result = runCheck('ruff', ['check', '--output-format=json', '--', target], rootDir);
217
+ const result = await runCheck('ruff', ['check', '--output-format=json', '--', target], rootDir);
221
218
  return parseRuffDiagnostics(result.stdout, rootDir);
222
219
  }
223
220
  if (filePath) {
224
- const result = runCheck('python', ['-m', 'py_compile', filePath], rootDir);
221
+ const result = await runCheck('python', ['-m', 'py_compile', filePath], rootDir);
225
222
  if (result.exitCode !== 0) {
226
223
  return parsePyCompileDiagnostics(result.stderr, rootDir, filePath);
227
224
  }
@@ -253,10 +250,10 @@ function parseTscDiagnostics(output, rootDir) {
253
250
  }
254
251
  return diagnostics;
255
252
  }
256
- function runTypeScriptCheck(rootDir) {
253
+ async function runTypeScriptCheck(rootDir) {
257
254
  if (!existsSync(path.join(rootDir, 'tsconfig.json')))
258
255
  return null;
259
- const result = runCheck('npx', ['tsc', '--noEmit', '--pretty', 'false'], rootDir);
256
+ const result = await runCheck('npx', ['tsc', '--noEmit', '--pretty', 'false'], rootDir);
260
257
  return parseTscDiagnostics(`${result.stdout}\n${result.stderr}`, rootDir);
261
258
  }
262
259
  const JS_IMPORT_RE = /import\s+(?:type\s+)?([^'"]+?)\s+from\s+['"]([^'"]+)['"]/g;
@@ -415,12 +412,136 @@ function runJavaScriptStaticCheck(rootDir, filePath) {
415
412
  }
416
413
  return diagnostics;
417
414
  }
418
- function runJavaScriptCheck(rootDir, filePath) {
419
- if (existsSync(path.join(rootDir, 'tsconfig.json'))) {
415
+ const NODE_CHECKABLE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']);
416
+ function stripJsonComments(text) {
417
+ let out = '';
418
+ let inString = false;
419
+ for (let index = 0; index < text.length; index += 1) {
420
+ const char = text[index];
421
+ const next = text[index + 1];
422
+ if (inString) {
423
+ out += char;
424
+ if (char === '\\') {
425
+ out += next ?? '';
426
+ index += 1;
427
+ }
428
+ else if (char === '"') {
429
+ inString = false;
430
+ }
431
+ continue;
432
+ }
433
+ if (char === '"') {
434
+ inString = true;
435
+ out += char;
436
+ }
437
+ else if (char === '/' && next === '/') {
438
+ while (index < text.length && text[index] !== '\n')
439
+ index += 1;
440
+ out += '\n';
441
+ }
442
+ else if (char === '/' && next === '*') {
443
+ index += 2;
444
+ while (index < text.length && !(text[index] === '*' && text[index + 1] === '/'))
445
+ index += 1;
446
+ index += 1;
447
+ }
448
+ else {
449
+ out += char;
450
+ }
451
+ }
452
+ return out.replace(/,(\s*[}\]])/g, '$1');
453
+ }
454
+ function readTsconfig(file) {
455
+ try {
456
+ return JSON.parse(stripJsonComments(readFileSync(file, 'utf-8')));
457
+ }
458
+ catch {
459
+ return null;
460
+ }
461
+ }
462
+ function isFile(candidate) {
463
+ try {
464
+ return statSync(candidate).isFile();
465
+ }
466
+ catch {
467
+ return false;
468
+ }
469
+ }
470
+ function resolveTsconfigExtends(fromFile, spec) {
471
+ const fromDir = path.dirname(fromFile);
472
+ const bases = [];
473
+ if (spec.startsWith('.') || path.isAbsolute(spec)) {
474
+ bases.push(path.resolve(fromDir, spec));
475
+ }
476
+ else {
477
+ for (let dir = fromDir;; dir = path.dirname(dir)) {
478
+ bases.push(path.join(dir, 'node_modules', spec));
479
+ if (path.dirname(dir) === dir)
480
+ break;
481
+ }
482
+ }
483
+ for (const base of bases) {
484
+ for (const candidate of [base, `${base}.json`, path.join(base, 'tsconfig.json')]) {
485
+ if (isFile(candidate))
486
+ return candidate;
487
+ }
488
+ }
489
+ return null;
490
+ }
491
+ function effectiveCompilerFlag(configFile, name, seen = new Set()) {
492
+ if (seen.has(configFile) || seen.size > 16)
493
+ return undefined;
494
+ seen.add(configFile);
495
+ const config = readTsconfig(configFile);
496
+ if (!config || typeof config !== 'object')
497
+ return undefined;
498
+ const own = config.compilerOptions?.[name];
499
+ if (typeof own === 'boolean')
500
+ return own;
501
+ const parents = Array.isArray(config.extends)
502
+ ? config.extends
503
+ : typeof config.extends === 'string'
504
+ ? [config.extends]
505
+ : [];
506
+ for (const spec of [...parents].reverse()) {
507
+ if (typeof spec !== 'string')
508
+ continue;
509
+ const parent = resolveTsconfigExtends(configFile, spec);
510
+ const value = parent ? effectiveCompilerFlag(parent, name, seen) : undefined;
511
+ if (value !== undefined)
512
+ return value;
513
+ }
514
+ return undefined;
515
+ }
516
+ function hasTsCheckPragma(rootDir, filePath) {
517
+ try {
518
+ const head = readFileSync(path.join(rootDir, filePath), 'utf-8').slice(0, 2000);
519
+ return /^(?:\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/))*\s*\/\/\s*@ts-check\b/.test(head);
520
+ }
521
+ catch {
522
+ return false;
523
+ }
524
+ }
525
+ function typeScriptChecksJavaScript(rootDir, filePath) {
526
+ const tsconfig = path.join(rootDir, 'tsconfig.json');
527
+ if (effectiveCompilerFlag(tsconfig, 'checkJs') === true)
528
+ return true;
529
+ return effectiveCompilerFlag(tsconfig, 'allowJs') === true && hasTsCheckPragma(rootDir, filePath);
530
+ }
531
+ function javaScriptUsesProjectCheck(rootDir, filePath) {
532
+ if (!existsSync(path.join(rootDir, 'tsconfig.json')))
533
+ return false;
534
+ if (!filePath || !NODE_CHECKABLE_EXTENSIONS.has(path.extname(filePath).toLowerCase())) {
535
+ return true;
536
+ }
537
+ return typeScriptChecksJavaScript(rootDir, filePath);
538
+ }
539
+ async function runJavaScriptCheck(rootDir, filePath) {
540
+ if (javaScriptUsesProjectCheck(rootDir, filePath)) {
420
541
  return runTypeScriptCheck(rootDir);
421
542
  }
422
543
  if (filePath) {
423
- const result = runCheck('node', ['--check', filePath], rootDir);
544
+ const result = await runCheck('node', ['--check', filePath], rootDir);
424
545
  const staticDiagnostics = runJavaScriptStaticCheck(rootDir, filePath);
425
546
  if (result.exitCode !== 0) {
426
547
  const msg = (result.stderr || result.stdout).trim();
@@ -430,7 +551,7 @@ function runJavaScriptCheck(rootDir, filePath) {
430
551
  {
431
552
  filePath,
432
553
  severity: 'error',
433
- message: msg.split('\n').pop() ?? 'Syntax error',
554
+ message: msg.match(/^\w*Error\b.*$/m)?.[0] ?? msg.split('\n').pop() ?? 'Syntax error',
434
555
  source: 'node',
435
556
  startLine: lineNum,
436
557
  startColumn: 1,
@@ -469,7 +590,7 @@ function formatShellDiagnosticsOutput(diagnostics, otherFileErrorCount = 0) {
469
590
  output = `Diagnostics via build check (${diagnostics.length})\n${lines.join('\n')}`;
470
591
  }
471
592
  if (otherFileErrorCount > 0) {
472
- output += `\n\n${otherFileErrorCount} additional error(s) in other project files — call get_diagnostics without a filePath to see the full project picture before declaring success.`;
593
+ output += `\n\n${otherFileErrorCount} additional error(s) in other project files - call get_diagnostics without a filePath to see the full project picture before declaring success.`;
473
594
  }
474
595
  return output;
475
596
  }
@@ -515,6 +636,7 @@ function cloneDiagnostics(diagnostics) {
515
636
  return diagnostics.map((diagnostic) => ({ ...diagnostic }));
516
637
  }
517
638
  export function invalidateShellDiagnosticsCache(rootDir, filePath) {
639
+ diagnosticsGeneration += 1;
518
640
  const prefix = `${rootDir}::`;
519
641
  if (!filePath) {
520
642
  for (const key of shellDiagnosticsCache.keys()) {
@@ -552,12 +674,21 @@ function commandScopeFor(language, rootDir, filePath) {
552
674
  case 'typescript':
553
675
  return 'project';
554
676
  case 'javascript':
555
- return existsSync(path.join(rootDir, 'tsconfig.json')) ? 'project' : 'file';
677
+ return javaScriptUsesProjectCheck(rootDir, filePath) ? 'project' : 'file';
556
678
  case 'python':
557
679
  return filePath ? 'file' : 'project';
558
680
  }
559
681
  }
560
- export function buildDeferredShellDiagnostics(trigger, filePath) {
682
+ export function buildDeferredShellDiagnostics(trigger, filePath, reason) {
683
+ if (reason === 'batch') {
684
+ return {
685
+ provider: 'shell',
686
+ deferred: true,
687
+ trigger,
688
+ filePath: filePath ?? undefined,
689
+ output: `Diagnostics for this edit run with the last edit in this batch, which checks every file the batch changed.`,
690
+ };
691
+ }
561
692
  if (trigger === 'run_command' || trigger === 'run_node_script') {
562
693
  return {
563
694
  provider: 'shell',
@@ -577,6 +708,32 @@ export function buildDeferredShellDiagnostics(trigger, filePath) {
577
708
  `Batch related edits first, then call get_diagnostics (without a filePath for project-wide errors${filePath ? `, or with filePath="${filePath}" for this file only` : ''}) before declaring success.`,
578
709
  };
579
710
  }
711
+ export function readEditDiagnosticsPlan(value) {
712
+ if (!value || typeof value !== 'object')
713
+ return undefined;
714
+ const raw = value;
715
+ if (raw.defer === true)
716
+ return { defer: true };
717
+ if (!Array.isArray(raw.files))
718
+ return undefined;
719
+ const files = raw.files
720
+ .filter((file) => typeof file === 'string' && file.trim() !== '')
721
+ .slice(0, 50);
722
+ return files.length ? { files } : undefined;
723
+ }
724
+ export async function diagnoseEditedFile(rootDir, filePath, trigger, plan) {
725
+ invalidateShellDiagnosticsCache(rootDir, filePath);
726
+ if (plan?.defer)
727
+ return buildDeferredShellDiagnostics(trigger, filePath, 'batch');
728
+ return runShellDiagnostics(rootDir, filePath, 50, projectRelativeFiles(rootDir, plan?.files ?? []));
729
+ }
730
+ function projectRelativeFiles(rootDir, files) {
731
+ return files.map((file) => (path.isAbsolute(file) ? path.relative(rootDir, file) : file));
732
+ }
733
+ export async function runBatchDiagnostics(rootDir, files) {
734
+ const [first, ...rest] = projectRelativeFiles(rootDir, files);
735
+ return runShellDiagnostics(rootDir, first, 50, rest);
736
+ }
580
737
  function buildUnavailableResult(filePath, command, reason) {
581
738
  return {
582
739
  ok: true,
@@ -591,17 +748,16 @@ function buildUnavailableResult(filePath, command, reason) {
591
748
  output: reason,
592
749
  };
593
750
  }
594
- function applyFilePathFilter(diagnostics, filePath) {
751
+ function applyFilePathFilter(diagnostics, filePath, alsoFiles = []) {
595
752
  if (!filePath) {
596
753
  return { focused: diagnostics, otherFileErrorCount: 0 };
597
754
  }
598
- const normalizedTarget = filePath.replace(/^\.\//, '');
755
+ const normalizedTargets = [filePath, ...alsoFiles].map((target) => target.replace(/^\.\//, ''));
599
756
  const focused = [];
600
757
  let otherFileErrorCount = 0;
601
758
  for (const diagnostic of diagnostics) {
602
759
  const normalizedDiag = diagnostic.filePath.replace(/^\.\//, '');
603
- if (normalizedDiag === normalizedTarget ||
604
- normalizedDiag.endsWith(`/${normalizedTarget}`)) {
760
+ if (normalizedTargets.some((target) => normalizedDiag === target || normalizedDiag.endsWith(`/${target}`))) {
605
761
  focused.push(diagnostic);
606
762
  }
607
763
  else if (diagnostic.severity === 'error') {
@@ -610,40 +766,42 @@ function applyFilePathFilter(diagnostics, filePath) {
610
766
  }
611
767
  return { focused, otherFileErrorCount };
612
768
  }
613
- function runDiagnosticsCommand(language, rootDir, filePath) {
769
+ async function runDiagnosticsCommand(language, rootDir, filePath) {
614
770
  switch (language) {
615
771
  case 'rust':
616
772
  return {
617
773
  command: 'cargo check --message-format=json --quiet',
618
- diagnostics: runRustCheck(rootDir),
774
+ diagnostics: await runRustCheck(rootDir),
619
775
  };
620
776
  case 'go':
621
777
  return {
622
778
  command: 'go build ./...',
623
- diagnostics: runGoCheck(rootDir),
779
+ diagnostics: await runGoCheck(rootDir),
624
780
  };
625
781
  case 'python':
626
782
  return {
627
- command: commandExists('ruff')
783
+ command: (await commandExists('ruff'))
628
784
  ? `ruff check ${filePath || '.'}`
629
785
  : `python -m py_compile ${filePath || ''}`,
630
- diagnostics: runPythonCheck(rootDir, filePath),
786
+ diagnostics: await runPythonCheck(rootDir, filePath),
631
787
  };
632
788
  case 'typescript':
633
789
  return {
634
790
  command: 'npx tsc --noEmit',
635
- diagnostics: runTypeScriptCheck(rootDir),
791
+ diagnostics: await runTypeScriptCheck(rootDir),
636
792
  };
637
793
  case 'javascript':
638
794
  return {
639
- command: existsSync(path.join(rootDir, 'tsconfig.json'))
795
+ command: javaScriptUsesProjectCheck(rootDir, filePath)
640
796
  ? 'npx tsc --noEmit'
641
797
  : `node --check ${filePath || ''}`,
642
- diagnostics: runJavaScriptCheck(rootDir, filePath),
798
+ diagnostics: await runJavaScriptCheck(rootDir, filePath),
643
799
  };
644
800
  }
645
801
  }
646
- export function runShellDiagnostics(rootDir, filePath, limit = 50) {
802
+ const diagnosticsRuns = new Map();
803
+ let diagnosticsGeneration = 0;
804
+ export async function runShellDiagnostics(rootDir, filePath, limit = 50, alsoFiles = []) {
647
805
  const language = filePath
648
806
  ? detectLanguageFromFile(filePath)
649
807
  : detectLanguageFromProject(rootDir);
@@ -665,7 +823,21 @@ export function runShellDiagnostics(rootDir, filePath, limit = 50) {
665
823
  available = cached.available;
666
824
  }
667
825
  else {
668
- const outcome = runDiagnosticsCommand(language, rootDir, filePath);
826
+ const generation = diagnosticsGeneration;
827
+ let run = diagnosticsRuns.get(cacheKey);
828
+ if (!run || run.generation !== generation) {
829
+ const started = {
830
+ generation,
831
+ outcome: runDiagnosticsCommand(language, rootDir, filePath),
832
+ };
833
+ run = started;
834
+ diagnosticsRuns.set(cacheKey, started);
835
+ void started.outcome.finally(() => {
836
+ if (diagnosticsRuns.get(cacheKey) === started)
837
+ diagnosticsRuns.delete(cacheKey);
838
+ });
839
+ }
840
+ const outcome = await run.outcome;
669
841
  command = outcome.command;
670
842
  if (outcome.diagnostics === null) {
671
843
  available = false;
@@ -675,21 +847,23 @@ export function runShellDiagnostics(rootDir, filePath, limit = 50) {
675
847
  available = true;
676
848
  rawDiagnostics = outcome.diagnostics;
677
849
  }
678
- shellDiagnosticsCache.set(cacheKey, {
679
- expiresAt: now +
680
- (scope === 'project'
681
- ? PROJECT_DIAGNOSTICS_CACHE_TTL_MS
682
- : FILE_DIAGNOSTICS_CACHE_TTL_MS),
683
- scope,
684
- command,
685
- available,
686
- diagnostics: rawDiagnostics,
687
- });
850
+ if (generation === diagnosticsGeneration) {
851
+ shellDiagnosticsCache.set(cacheKey, {
852
+ expiresAt: Date.now() +
853
+ (scope === 'project'
854
+ ? PROJECT_DIAGNOSTICS_CACHE_TTL_MS
855
+ : FILE_DIAGNOSTICS_CACHE_TTL_MS),
856
+ scope,
857
+ command,
858
+ available,
859
+ diagnostics: rawDiagnostics,
860
+ });
861
+ }
688
862
  }
689
863
  if (!available) {
690
864
  return buildUnavailableResult(filePath, command, `No build check command available${filePath ? ` for ${filePath}` : ''} (no project configuration found).`);
691
865
  }
692
- const { focused, otherFileErrorCount } = applyFilePathFilter(rawDiagnostics, filePath);
866
+ const { focused, otherFileErrorCount } = applyFilePathFilter(rawDiagnostics, filePath, alsoFiles);
693
867
  const limited = focused.slice(0, limit);
694
868
  const counts = countBySeverity(limited);
695
869
  return {
@@ -3,10 +3,10 @@ import path from 'node:path';
3
3
  import { normalizeProjectRelativePath } from '../artifact-policy.js';
4
4
  import { classifyProjectPath, readProjectFile, writeProjectFile, } from '../patcher.js';
5
5
  import { repairFilePath } from './path-suggest.js';
6
- import { upsertIndexFile } from '../project-index.js';
7
6
  import { isTuiMode } from '../runtime-mode.js';
8
7
  import { getCurrentFileHash, resolveRedactionTokens } from '../session-safety.js';
9
- import { invalidateShellDiagnosticsCache, runShellDiagnostics, } from './shell-diagnostics.js';
8
+ import { diagnoseEditedFile } from './shell-diagnostics.js';
9
+ import { ensurePermission } from '../permissions.js';
10
10
  const DOCUMENT_EXTENSIONS = new Set(['.pdf', '.xlsx', '.docx']);
11
11
  function countOccurrences(haystack, needle) {
12
12
  if (needle.length === 0)
@@ -76,7 +76,7 @@ function buildStrReplacePreview(oldString, newString) {
76
76
  return `@@ str_replace @@\n${minus}\n${plus}`;
77
77
  }
78
78
  export async function strReplace(context, args) {
79
- const { rootDir, projectIndex, autoYes, confirmPatch } = context;
79
+ const { rootDir } = context;
80
80
  const filePath = repairFilePath(rootDir, String(args.filePath ?? args.file_path ?? '').trim());
81
81
  let oldString = typeof args.old_string === 'string'
82
82
  ? args.old_string
@@ -175,39 +175,26 @@ export async function strReplace(context, args) {
175
175
  }
176
176
  console.log();
177
177
  }
178
- if (!autoYes && confirmPatch) {
179
- const confirmed = await confirmPatch(filePath, preview);
180
- if (!confirmed) {
178
+ if (!scratchPath) {
179
+ const denied = await ensurePermission(context, {
180
+ bucket: 'edit',
181
+ title: 'Approve patch?',
182
+ body: 'Review changes before applying.',
183
+ filePath,
184
+ diff: preview,
185
+ }, 'str_replace', { filePath });
186
+ if (denied) {
181
187
  if (!isTuiMode())
182
188
  console.log(chalk.dim(` ⏭ str_replace skipped: ${filePath}`));
183
- return {
184
- ok: false,
185
- skipped: true,
186
- filePath,
187
- failureCategory: 'user_declined',
188
- failureDetails: {
189
- category: 'user_declined',
190
- tool: 'str_replace',
191
- action: 'Respect the real user’s decision. Do not retry the same or an equivalent edit; reconsider the approach or ask one specific question if needed.',
192
- },
193
- error: 'The real user rejected this proposed edit. Nothing was changed; this was not a tool failure or an automated system skip.',
194
- };
189
+ return denied;
195
190
  }
196
191
  }
197
192
  const nextContent = originalContent.split(oldString).join(newString);
198
193
  const { changed } = writeProjectFile(rootDir, filePath, nextContent);
199
194
  const replacements = changed ? (replaceAll ? n : 1) : 0;
200
- let indexedChunks = 0;
201
- let retrievalTokensUsed = 0;
202
- if (changed && !scratchPath) {
203
- const indexResult = await upsertIndexFile(projectIndex, filePath);
204
- indexedChunks = indexResult.indexedChunks;
205
- retrievalTokensUsed = indexResult.retrievalTokensUsed ?? 0;
206
- }
207
195
  let diagnostics;
208
196
  if (!scratchPath) {
209
- invalidateShellDiagnosticsCache(rootDir, filePath);
210
- diagnostics = runShellDiagnostics(rootDir, filePath);
197
+ diagnostics = await diagnoseEditedFile(rootDir, filePath, 'str_replace', context.diagnosticsPlan);
211
198
  }
212
199
  const originalLines = originalContent.split('\n').length;
213
200
  const nextLines = nextContent.split('\n').length;
@@ -223,8 +210,6 @@ export async function strReplace(context, args) {
223
210
  operation: 'str_replace',
224
211
  ...(scratchPath ? { scratch: true } : {}),
225
212
  replacements,
226
- indexedChunks,
227
- retrievalTokensUsed,
228
213
  bytesWritten: Buffer.byteLength(nextContent, 'utf-8'),
229
214
  diagnostics,
230
215
  message: changed ? undefined : 'The provided replacement resulted in no changes to the file content.',
@@ -1,7 +1,6 @@
1
1
  import chalk from '../colors.js';
2
2
  import { hashStoredContent, readFileEditSnapshot, storedContentBuffer, } from '../edit-journal.js';
3
3
  import { deleteProjectFile, writeProjectFile, writeProjectFileBuffer, } from '../patcher.js';
4
- import { removeIndexFile, upsertIndexFile, } from '../project-index.js';
5
4
  import { isTuiMode } from '../runtime-mode.js';
6
5
  import { invalidateShellDiagnosticsCache, runShellDiagnostics, } from './shell-diagnostics.js';
7
6
  function normalizeTarget(value) {
@@ -101,10 +100,9 @@ function validateUndoPlan(rootDir, records) {
101
100
  return { ok: true };
102
101
  }
103
102
  async function applyUndo(context, record) {
104
- const { rootDir, projectIndex } = context;
103
+ const { rootDir } = context;
105
104
  if (record.operation === 'create') {
106
105
  deleteProjectFile(rootDir, record.filePath);
107
- await removeIndexFile(projectIndex, record.filePath);
108
106
  return { changed: true };
109
107
  }
110
108
  if (record.beforeContent === null) {
@@ -113,9 +111,6 @@ async function applyUndo(context, record) {
113
111
  const { changed } = record.beforeContentEncoding === 'base64'
114
112
  ? writeProjectFileBuffer(rootDir, record.filePath, storedContentBuffer(record.beforeContent, record.beforeContentEncoding))
115
113
  : writeProjectFile(rootDir, record.filePath, record.beforeContent);
116
- if (changed) {
117
- await upsertIndexFile(projectIndex, record.filePath);
118
- }
119
114
  return { changed };
120
115
  }
121
116
  function summarizeUndoRecord(record) {
@@ -199,6 +194,6 @@ export async function undoEdit(context, args) {
199
194
  previewed,
200
195
  reverted,
201
196
  gitWorkTree: selected.some((record) => record.gitWorkTree),
202
- diagnostics: dryRun ? undefined : runShellDiagnostics(context.rootDir),
197
+ diagnostics: dryRun ? undefined : await runShellDiagnostics(context.rootDir),
203
198
  };
204
199
  }
@@ -0,0 +1,38 @@
1
+ import { bundledSkillNamed, discoverSkills, findSkill, loadSkillContent, skillFolders, } from '../skills/discovery.js';
2
+ import { isValidSkillName } from '../skills/types.js';
3
+ export function useSkill(context, args) {
4
+ const name = String(args.name ?? '').trim().replace(/^\//, '');
5
+ if (!name) {
6
+ return { ok: false, error: 'name is required', failureCategory: 'missing_required_argument' };
7
+ }
8
+ if (!isValidSkillName(name)) {
9
+ return { ok: false, error: `No skill named "${name.slice(0, 80)}" is installed.`, failureCategory: 'not_found' };
10
+ }
11
+ const discovery = discoverSkills(context.rootDir, context.env ?? process.env);
12
+ const skill = findSkill(discovery, name);
13
+ if (!skill) {
14
+ if (bundledSkillNamed(name)) {
15
+ return {
16
+ ok: true,
17
+ name,
18
+ scope: 'bundled',
19
+ ...skillFolders(context.rootDir, context.env ?? process.env),
20
+ };
21
+ }
22
+ return { ok: false, error: `No skill named "${name}" is installed.`, failureCategory: 'not_found' };
23
+ }
24
+ const loaded = loadSkillContent(skill);
25
+ if (!loaded.ok) {
26
+ return { ok: false, error: loaded.error, failureCategory: 'invalid_argument' };
27
+ }
28
+ return {
29
+ ok: true,
30
+ name: skill.name,
31
+ scope: skill.scope,
32
+ dir: skill.dir,
33
+ content: loaded.content,
34
+ ...(loaded.truncated ? { contentTruncated: true } : {}),
35
+ files: loaded.files,
36
+ ...(loaded.filesTruncated ? { filesTruncated: true } : {}),
37
+ };
38
+ }