@ruvnet/open-claude-code 2.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 (63) hide show
  1. package/package.json +27 -0
  2. package/src/agents/loader.mjs +89 -0
  3. package/src/agents/parser.mjs +98 -0
  4. package/src/agents/teams.mjs +123 -0
  5. package/src/auth/oauth.mjs +220 -0
  6. package/src/config/cli-args.mjs +139 -0
  7. package/src/config/env.mjs +261 -0
  8. package/src/config/settings.mjs +119 -0
  9. package/src/core/agent-loop.mjs +462 -0
  10. package/src/core/cache.mjs +105 -0
  11. package/src/core/checkpoints.mjs +141 -0
  12. package/src/core/context-manager.mjs +198 -0
  13. package/src/core/providers.mjs +219 -0
  14. package/src/core/rate-limiter.mjs +119 -0
  15. package/src/core/scheduler.mjs +173 -0
  16. package/src/core/session.mjs +143 -0
  17. package/src/core/streaming.mjs +182 -0
  18. package/src/core/system-prompt.mjs +135 -0
  19. package/src/hooks/engine.mjs +162 -0
  20. package/src/index.mjs +220 -0
  21. package/src/mcp/client.mjs +253 -0
  22. package/src/mcp/transport-shttp.mjs +130 -0
  23. package/src/mcp/transport-sse.mjs +131 -0
  24. package/src/mcp/transport-ws.mjs +134 -0
  25. package/src/permissions/checker.mjs +57 -0
  26. package/src/permissions/injection-check.mjs +60 -0
  27. package/src/permissions/path-check.mjs +102 -0
  28. package/src/permissions/prompt.mjs +73 -0
  29. package/src/permissions/sandbox.mjs +112 -0
  30. package/src/plugins/loader.mjs +138 -0
  31. package/src/skills/loader.mjs +147 -0
  32. package/src/skills/runner.mjs +55 -0
  33. package/src/telemetry/index.mjs +96 -0
  34. package/src/tools/agent.mjs +127 -0
  35. package/src/tools/ask-user.mjs +61 -0
  36. package/src/tools/bash.mjs +148 -0
  37. package/src/tools/cron-create.mjs +120 -0
  38. package/src/tools/cron-delete.mjs +49 -0
  39. package/src/tools/cron-list.mjs +37 -0
  40. package/src/tools/edit.mjs +82 -0
  41. package/src/tools/enter-worktree.mjs +69 -0
  42. package/src/tools/exit-worktree.mjs +57 -0
  43. package/src/tools/glob.mjs +117 -0
  44. package/src/tools/grep.mjs +127 -0
  45. package/src/tools/ls.mjs +58 -0
  46. package/src/tools/lsp.mjs +115 -0
  47. package/src/tools/multi-edit.mjs +94 -0
  48. package/src/tools/notebook-edit.mjs +96 -0
  49. package/src/tools/read-mcp-resource.mjs +57 -0
  50. package/src/tools/read.mjs +138 -0
  51. package/src/tools/registry.mjs +114 -0
  52. package/src/tools/remote-trigger.mjs +84 -0
  53. package/src/tools/send-message.mjs +64 -0
  54. package/src/tools/skill.mjs +52 -0
  55. package/src/tools/todo-write.mjs +68 -0
  56. package/src/tools/tool-search.mjs +77 -0
  57. package/src/tools/web-fetch.mjs +65 -0
  58. package/src/tools/web-search.mjs +89 -0
  59. package/src/tools/write.mjs +55 -0
  60. package/src/ui/commands.mjs +499 -0
  61. package/src/ui/ink-app.mjs +231 -0
  62. package/src/ui/repl.mjs +144 -0
  63. package/test/test.mjs +1857 -0
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Bash Tool — matches Claude Code's exact behavior.
3
+ *
4
+ * Features:
5
+ * - Timeout with SIGTERM -> SIGKILL escalation
6
+ * - run_in_background option
7
+ * - description parameter
8
+ * - 1MB output limit
9
+ * - ANSI code stripping by default
10
+ */
11
+ import { spawn } from 'child_process';
12
+
13
+ // Strip ANSI escape sequences
14
+ function stripAnsi(str) {
15
+ // eslint-disable-next-line no-control-regex
16
+ return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
17
+ }
18
+
19
+ const MAX_OUTPUT_BYTES = 1024 * 1024; // 1MB
20
+
21
+ export const BashTool = {
22
+ name: 'Bash',
23
+ description: 'Execute a bash command and return its output.',
24
+ inputSchema: {
25
+ type: 'object',
26
+ properties: {
27
+ command: { type: 'string', description: 'The command to execute' },
28
+ timeout: { type: 'number', description: 'Timeout in ms (max 600000)', default: 120000 },
29
+ description: { type: 'string', description: 'Description of what this command does' },
30
+ run_in_background: { type: 'boolean', description: 'Run in background', default: false },
31
+ },
32
+ required: ['command'],
33
+ },
34
+ validateInput(input) {
35
+ const errors = [];
36
+ if (!input.command) errors.push('command is required');
37
+ return errors;
38
+ },
39
+ async call(input) {
40
+ const timeout = Math.min(input.timeout || 120000, 600000);
41
+
42
+ if (input.run_in_background) {
43
+ return runBackground(input.command);
44
+ }
45
+
46
+ return new Promise((resolve) => {
47
+ let stdout = '';
48
+ let stderr = '';
49
+ let killed = false;
50
+ let exitCode = null;
51
+
52
+ const proc = spawn('bash', ['-c', input.command], {
53
+ env: { ...process.env },
54
+ stdio: ['pipe', 'pipe', 'pipe'],
55
+ timeout: 0, // we handle timeout ourselves
56
+ });
57
+
58
+ proc.stdout.on('data', (chunk) => {
59
+ if (stdout.length < MAX_OUTPUT_BYTES) {
60
+ stdout += chunk.toString();
61
+ }
62
+ });
63
+
64
+ proc.stderr.on('data', (chunk) => {
65
+ if (stderr.length < MAX_OUTPUT_BYTES) {
66
+ stderr += chunk.toString();
67
+ }
68
+ });
69
+
70
+ // Timeout: SIGTERM first, then SIGKILL after 5s
71
+ const timer = setTimeout(() => {
72
+ killed = true;
73
+ proc.kill('SIGTERM');
74
+ setTimeout(() => {
75
+ try { proc.kill('SIGKILL'); } catch { /* already dead */ }
76
+ }, 5000);
77
+ }, timeout);
78
+
79
+ proc.on('close', (code) => {
80
+ clearTimeout(timer);
81
+ exitCode = code;
82
+
83
+ // Truncate if over limit
84
+ if (stdout.length > MAX_OUTPUT_BYTES) {
85
+ stdout = stdout.slice(0, MAX_OUTPUT_BYTES) + '\n[output truncated at 1MB]';
86
+ }
87
+ if (stderr.length > MAX_OUTPUT_BYTES) {
88
+ stderr = stderr.slice(0, MAX_OUTPUT_BYTES) + '\n[output truncated at 1MB]';
89
+ }
90
+
91
+ // Strip ANSI by default
92
+ stdout = stripAnsi(stdout);
93
+ stderr = stripAnsi(stderr);
94
+
95
+ if (killed) {
96
+ resolve(`Error: Command timed out after ${timeout}ms\n${stdout}\n${stderr}`.trim());
97
+ return;
98
+ }
99
+
100
+ const output = (stdout + (stderr ? '\n' + stderr : '')).trim();
101
+ if (code !== 0) {
102
+ resolve(`Exit code: ${code}\n${output}`.trim());
103
+ } else {
104
+ resolve(output || '(no output)');
105
+ }
106
+ });
107
+
108
+ proc.on('error', (err) => {
109
+ clearTimeout(timer);
110
+ resolve(`Error: ${err.message}`);
111
+ });
112
+
113
+ // Close stdin
114
+ proc.stdin.end();
115
+ });
116
+ },
117
+ };
118
+
119
+ // Background jobs store
120
+ const backgroundJobs = new Map();
121
+ let bgJobId = 0;
122
+
123
+ function runBackground(command) {
124
+ const id = ++bgJobId;
125
+ const proc = spawn('bash', ['-c', command], {
126
+ detached: true,
127
+ stdio: ['ignore', 'pipe', 'pipe'],
128
+ });
129
+
130
+ let stdout = '';
131
+ let stderr = '';
132
+ proc.stdout.on('data', (d) => { stdout += d.toString(); });
133
+ proc.stderr.on('data', (d) => { stderr += d.toString(); });
134
+
135
+ const job = { id, pid: proc.pid, command, status: 'running', stdout: '', stderr: '' };
136
+ backgroundJobs.set(id, job);
137
+
138
+ proc.on('close', (code) => {
139
+ job.status = code === 0 ? 'completed' : `exited(${code})`;
140
+ job.stdout = stripAnsi(stdout.slice(0, MAX_OUTPUT_BYTES));
141
+ job.stderr = stripAnsi(stderr.slice(0, MAX_OUTPUT_BYTES));
142
+ });
143
+
144
+ proc.unref();
145
+ return `Background job started: id=${id}, pid=${proc.pid}`;
146
+ }
147
+
148
+ export { backgroundJobs };
@@ -0,0 +1,120 @@
1
+ /**
2
+ * CronCreate Tool — create a scheduled task.
3
+ *
4
+ * Stores cron definitions in memory and optionally persists them
5
+ * to ~/.claude/cron.json. Uses setTimeout-based scheduling for
6
+ * the duration of the session.
7
+ */
8
+
9
+ import fs from 'fs';
10
+ import path from 'path';
11
+ import os from 'os';
12
+
13
+ // Shared cron store
14
+ export const cronStore = new Map();
15
+ let cronIdCounter = 1;
16
+
17
+ export const CronCreateTool = {
18
+ name: 'CronCreate',
19
+ description: 'Create a scheduled task that runs on a cron schedule.',
20
+ inputSchema: {
21
+ type: 'object',
22
+ properties: {
23
+ name: { type: 'string', description: 'Name for the scheduled task' },
24
+ schedule: {
25
+ type: 'string',
26
+ description: 'Cron expression (e.g., "*/5 * * * *") or interval (e.g., "5m", "1h")',
27
+ },
28
+ command: {
29
+ type: 'string',
30
+ description: 'Command or prompt to execute on schedule',
31
+ },
32
+ type: {
33
+ type: 'string',
34
+ enum: ['command', 'prompt'],
35
+ description: 'Whether to run as shell command or agent prompt',
36
+ },
37
+ },
38
+ required: ['name', 'schedule', 'command'],
39
+ },
40
+
41
+ validateInput(input) {
42
+ const errors = [];
43
+ if (!input.name) errors.push('name is required');
44
+ if (!input.schedule) errors.push('schedule is required');
45
+ if (!input.command) errors.push('command is required');
46
+ return errors;
47
+ },
48
+
49
+ async call(input) {
50
+ if (process.env.CLAUDE_CODE_DISABLE_CRON === '1') {
51
+ return 'Cron tasks are disabled (CLAUDE_CODE_DISABLE_CRON=1)';
52
+ }
53
+
54
+ const id = `cron_${cronIdCounter++}`;
55
+ const intervalMs = parseSchedule(input.schedule);
56
+
57
+ const job = {
58
+ id,
59
+ name: input.name,
60
+ schedule: input.schedule,
61
+ command: input.command,
62
+ type: input.type || 'command',
63
+ intervalMs,
64
+ createdAt: new Date().toISOString(),
65
+ lastRun: null,
66
+ runCount: 0,
67
+ timer: null,
68
+ };
69
+
70
+ // Set up interval timer
71
+ if (intervalMs > 0) {
72
+ job.timer = setInterval(() => {
73
+ job.lastRun = new Date().toISOString();
74
+ job.runCount++;
75
+ // Execution is handled by the cron runner in the main loop
76
+ }, intervalMs);
77
+ }
78
+
79
+ cronStore.set(id, job);
80
+ persistCronJobs();
81
+
82
+ return `Created scheduled task:\n ID: ${id}\n Name: ${input.name}\n Schedule: ${input.schedule}\n Interval: ${intervalMs}ms\n Type: ${job.type}`;
83
+ },
84
+ };
85
+
86
+ /**
87
+ * Parse a schedule string into milliseconds.
88
+ * Supports cron shorthand: "5m", "1h", "30s", "1d"
89
+ */
90
+ function parseSchedule(schedule) {
91
+ const match = schedule.match(/^(\d+)(s|m|h|d)$/);
92
+ if (match) {
93
+ const value = parseInt(match[1], 10);
94
+ const units = { s: 1000, m: 60000, h: 3600000, d: 86400000 };
95
+ return value * (units[match[2]] || 60000);
96
+ }
97
+ // Default: treat as minutes for simple numbers
98
+ const num = parseInt(schedule, 10);
99
+ if (!isNaN(num)) return num * 60000;
100
+ // For full cron expressions, default to 5 minutes
101
+ return 300000;
102
+ }
103
+
104
+ function persistCronJobs() {
105
+ try {
106
+ const cronDir = path.join(os.homedir(), '.claude');
107
+ fs.mkdirSync(cronDir, { recursive: true });
108
+ const jobs = [];
109
+ for (const [, job] of cronStore) {
110
+ const { timer, ...rest } = job;
111
+ jobs.push(rest);
112
+ }
113
+ fs.writeFileSync(
114
+ path.join(cronDir, 'cron.json'),
115
+ JSON.stringify(jobs, null, 2)
116
+ );
117
+ } catch {
118
+ // Best effort
119
+ }
120
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * CronDelete Tool — delete a scheduled task.
3
+ */
4
+
5
+ import { cronStore } from './cron-create.mjs';
6
+
7
+ export const CronDeleteTool = {
8
+ name: 'CronDelete',
9
+ description: 'Delete a scheduled task by ID or name.',
10
+ inputSchema: {
11
+ type: 'object',
12
+ properties: {
13
+ id: { type: 'string', description: 'Cron job ID to delete' },
14
+ name: { type: 'string', description: 'Cron job name to delete (alternative to id)' },
15
+ },
16
+ required: [],
17
+ },
18
+
19
+ validateInput(input) {
20
+ if (!input.id && !input.name) return ['Either id or name is required'];
21
+ return [];
22
+ },
23
+
24
+ async call(input) {
25
+ let target = null;
26
+
27
+ if (input.id) {
28
+ target = cronStore.get(input.id);
29
+ } else if (input.name) {
30
+ for (const [, job] of cronStore) {
31
+ if (job.name === input.name) {
32
+ target = job;
33
+ break;
34
+ }
35
+ }
36
+ }
37
+
38
+ if (!target) {
39
+ return `No cron job found matching ${input.id || input.name}`;
40
+ }
41
+
42
+ if (target.timer) {
43
+ clearInterval(target.timer);
44
+ }
45
+ cronStore.delete(target.id);
46
+
47
+ return `Deleted cron job: ${target.id} (${target.name})`;
48
+ },
49
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * CronList Tool — list all scheduled tasks.
3
+ */
4
+
5
+ import { cronStore } from './cron-create.mjs';
6
+
7
+ export const CronListTool = {
8
+ name: 'CronList',
9
+ description: 'List all scheduled tasks.',
10
+ inputSchema: {
11
+ type: 'object',
12
+ properties: {},
13
+ required: [],
14
+ },
15
+
16
+ validateInput() { return []; },
17
+
18
+ async call() {
19
+ if (cronStore.size === 0) {
20
+ return 'No scheduled tasks.';
21
+ }
22
+
23
+ const lines = [];
24
+ for (const [, job] of cronStore) {
25
+ lines.push(
26
+ ` ${job.id}: ${job.name}\n` +
27
+ ` Schedule: ${job.schedule} (${job.intervalMs}ms)\n` +
28
+ ` Type: ${job.type}\n` +
29
+ ` Runs: ${job.runCount}\n` +
30
+ ` Last: ${job.lastRun || 'never'}\n` +
31
+ ` Created: ${job.createdAt}`
32
+ );
33
+ }
34
+
35
+ return `Scheduled tasks (${cronStore.size}):\n${lines.join('\n\n')}`;
36
+ },
37
+ };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Edit Tool — matches Claude Code's exact behavior.
3
+ *
4
+ * Features:
5
+ * - replace_all parameter for global replacement
6
+ * - Verify old_string is unique (error if not)
7
+ * - Require file was Read first (track read files)
8
+ * - Preserve exact indentation
9
+ */
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import { hasBeenRead, markRead } from './read.mjs';
13
+
14
+ export const EditTool = {
15
+ name: 'Edit',
16
+ description: 'Performs exact string replacements in files.',
17
+ inputSchema: {
18
+ type: 'object',
19
+ properties: {
20
+ file_path: { type: 'string', description: 'Absolute path to the file' },
21
+ old_string: { type: 'string', description: 'The text to replace' },
22
+ new_string: { type: 'string', description: 'The replacement text' },
23
+ replace_all: { type: 'boolean', description: 'Replace all occurrences', default: false },
24
+ },
25
+ required: ['file_path', 'old_string', 'new_string'],
26
+ },
27
+ validateInput(input) {
28
+ const errors = [];
29
+ if (!input.file_path) errors.push('file_path required');
30
+ if (!input.old_string && input.old_string !== '') errors.push('old_string required');
31
+ if (input.old_string === input.new_string) errors.push('old_string must differ from new_string');
32
+ return errors;
33
+ },
34
+ async call(input) {
35
+ const filePath = path.resolve(input.file_path);
36
+
37
+ // Check file exists
38
+ if (!fs.existsSync(filePath)) {
39
+ return `Error: File not found: ${filePath}`;
40
+ }
41
+
42
+ // Require file was read first
43
+ if (!hasBeenRead(filePath)) {
44
+ return `Error: You must Read ${filePath} before editing it. Use the Read tool first.`;
45
+ }
46
+
47
+ let content;
48
+ try {
49
+ content = fs.readFileSync(filePath, 'utf-8');
50
+ } catch (e) {
51
+ return `Error: ${e.message}`;
52
+ }
53
+
54
+ if (!content.includes(input.old_string)) {
55
+ return 'Error: old_string not found in file. Make sure the string matches exactly, including whitespace and indentation.';
56
+ }
57
+
58
+ if (input.replace_all) {
59
+ // Replace all occurrences
60
+ const escaped = input.old_string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
61
+ content = content.replace(new RegExp(escaped, 'g'), input.new_string);
62
+ } else {
63
+ // Check uniqueness: old_string must appear exactly once
64
+ const firstIdx = content.indexOf(input.old_string);
65
+ const secondIdx = content.indexOf(input.old_string, firstIdx + 1);
66
+ if (secondIdx !== -1) {
67
+ const count = content.split(input.old_string).length - 1;
68
+ return `Error: old_string is not unique in the file (found ${count} occurrences). Provide more context to make it unique, or use replace_all to replace all occurrences.`;
69
+ }
70
+ content = content.replace(input.old_string, input.new_string);
71
+ }
72
+
73
+ try {
74
+ fs.writeFileSync(filePath, content);
75
+ // Keep it marked as read
76
+ markRead(filePath);
77
+ return `File updated: ${filePath}`;
78
+ } catch (e) {
79
+ return `Error writing file: ${e.message}`;
80
+ }
81
+ },
82
+ };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * EnterWorktree Tool — create and enter a git worktree for isolation.
3
+ *
4
+ * Creates a temporary worktree branch so edits do not affect the main branch.
5
+ */
6
+
7
+ import { execSync } from 'child_process';
8
+ import path from 'path';
9
+ import os from 'os';
10
+
11
+ export const EnterWorktreeTool = {
12
+ name: 'EnterWorktree',
13
+ description: 'Create a git worktree for isolated file editing.',
14
+ inputSchema: {
15
+ type: 'object',
16
+ properties: {
17
+ branch: {
18
+ type: 'string',
19
+ description: 'Branch name for the worktree (auto-generated if omitted)',
20
+ },
21
+ path: {
22
+ type: 'string',
23
+ description: 'Directory for the worktree (temp dir if omitted)',
24
+ },
25
+ },
26
+ required: [],
27
+ },
28
+
29
+ // Shared state for active worktree
30
+ _activeWorktree: null,
31
+
32
+ validateInput() { return []; },
33
+
34
+ async call(input) {
35
+ if (this._activeWorktree) {
36
+ return `Already in worktree at ${this._activeWorktree.path}. Use ExitWorktree first.`;
37
+ }
38
+
39
+ try {
40
+ // Verify we are in a git repo
41
+ execSync('git rev-parse --is-inside-work-tree', { encoding: 'utf-8' });
42
+ } catch {
43
+ return 'Error: not inside a git repository';
44
+ }
45
+
46
+ const branch = input.branch || `occ-worktree-${Date.now()}`;
47
+ const worktreePath = input.path || path.join(os.tmpdir(), `occ-wt-${Date.now()}`);
48
+ const originalCwd = process.cwd();
49
+
50
+ try {
51
+ execSync(`git worktree add -b "${branch}" "${worktreePath}"`, {
52
+ encoding: 'utf-8',
53
+ stdio: 'pipe',
54
+ });
55
+
56
+ this._activeWorktree = {
57
+ path: worktreePath,
58
+ branch,
59
+ originalCwd,
60
+ };
61
+
62
+ process.chdir(worktreePath);
63
+
64
+ return `Entered worktree:\n Branch: ${branch}\n Path: ${worktreePath}\n Original: ${originalCwd}`;
65
+ } catch (err) {
66
+ return `Error creating worktree: ${err.message}`;
67
+ }
68
+ },
69
+ };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * ExitWorktree Tool — exit and clean up a git worktree.
3
+ */
4
+
5
+ import { execSync } from 'child_process';
6
+
7
+ export const ExitWorktreeTool = {
8
+ name: 'ExitWorktree',
9
+ description: 'Exit the current git worktree and return to the original directory.',
10
+ inputSchema: {
11
+ type: 'object',
12
+ properties: {
13
+ cleanup: {
14
+ type: 'boolean',
15
+ description: 'Remove the worktree branch after exiting (default: true)',
16
+ },
17
+ },
18
+ required: [],
19
+ },
20
+
21
+ validateInput() { return []; },
22
+
23
+ async call(input) {
24
+ const { EnterWorktreeTool } = await import('./enter-worktree.mjs');
25
+ const wt = EnterWorktreeTool._activeWorktree;
26
+
27
+ if (!wt) {
28
+ return 'Not currently in a worktree.';
29
+ }
30
+
31
+ const cleanup = input.cleanup !== false;
32
+
33
+ try {
34
+ process.chdir(wt.originalCwd);
35
+
36
+ if (cleanup) {
37
+ try {
38
+ execSync(`git worktree remove "${wt.path}" --force`, {
39
+ encoding: 'utf-8',
40
+ stdio: 'pipe',
41
+ });
42
+ execSync(`git branch -D "${wt.branch}"`, {
43
+ encoding: 'utf-8',
44
+ stdio: 'pipe',
45
+ });
46
+ } catch {
47
+ // Best effort cleanup
48
+ }
49
+ }
50
+
51
+ EnterWorktreeTool._activeWorktree = null;
52
+ return `Exited worktree. Returned to ${wt.originalCwd}${cleanup ? ' (cleaned up)' : ''}`;
53
+ } catch (err) {
54
+ return `Error exiting worktree: ${err.message}`;
55
+ }
56
+ },
57
+ };
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Glob Tool — matches Claude Code's exact behavior.
3
+ *
4
+ * Features:
5
+ * - Proper glob matching (not shell find)
6
+ * - Sort by modification time
7
+ * - path parameter for directory scoping
8
+ */
9
+ import fs from 'fs';
10
+ import path from 'path';
11
+
12
+ /**
13
+ * Minimal glob implementation without external dependencies.
14
+ * Supports *, **, and ? wildcards.
15
+ */
16
+ function globMatch(pattern, str) {
17
+ const regex = globToRegex(pattern);
18
+ return regex.test(str);
19
+ }
20
+
21
+ function globToRegex(pattern) {
22
+ let regex = '';
23
+ let i = 0;
24
+ while (i < pattern.length) {
25
+ const ch = pattern[i];
26
+ if (ch === '*') {
27
+ if (pattern[i + 1] === '*') {
28
+ // ** matches everything including /
29
+ regex += '.*';
30
+ i += 2;
31
+ if (pattern[i] === '/') i++; // skip trailing /
32
+ continue;
33
+ }
34
+ regex += '[^/]*';
35
+ } else if (ch === '?') {
36
+ regex += '[^/]';
37
+ } else if (ch === '.') {
38
+ regex += '\\.';
39
+ } else if (ch === '{') {
40
+ regex += '(';
41
+ } else if (ch === '}') {
42
+ regex += ')';
43
+ } else if (ch === ',') {
44
+ regex += '|';
45
+ } else {
46
+ regex += ch;
47
+ }
48
+ i++;
49
+ }
50
+ return new RegExp('^' + regex + '$');
51
+ }
52
+
53
+ function walkDir(dir, maxDepth = 20, depth = 0) {
54
+ const results = [];
55
+ if (depth > maxDepth) return results;
56
+ try {
57
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
58
+ for (const entry of entries) {
59
+ // Skip hidden dirs and node_modules
60
+ if (entry.name.startsWith('.') && depth > 0) continue;
61
+ if (entry.name === 'node_modules') continue;
62
+
63
+ const full = path.join(dir, entry.name);
64
+ if (entry.isDirectory()) {
65
+ results.push(...walkDir(full, maxDepth, depth + 1));
66
+ } else {
67
+ results.push(full);
68
+ }
69
+ }
70
+ } catch {
71
+ // Permission denied or other error
72
+ }
73
+ return results;
74
+ }
75
+
76
+ export const GlobTool = {
77
+ name: 'Glob',
78
+ description: 'Find files matching a glob pattern, sorted by modification time.',
79
+ inputSchema: {
80
+ type: 'object',
81
+ properties: {
82
+ pattern: { type: 'string', description: 'Glob pattern (e.g. "**/*.js")' },
83
+ path: { type: 'string', description: 'Directory to search in' },
84
+ },
85
+ required: ['pattern'],
86
+ },
87
+ validateInput(input) { return input.pattern ? [] : ['pattern required']; },
88
+ async call(input) {
89
+ try {
90
+ const baseDir = path.resolve(input.path || '.');
91
+ if (!fs.existsSync(baseDir)) {
92
+ return `Error: Directory not found: ${baseDir}`;
93
+ }
94
+
95
+ const allFiles = walkDir(baseDir);
96
+
97
+ // Match against pattern
98
+ const matches = allFiles.filter(f => {
99
+ const rel = path.relative(baseDir, f);
100
+ return globMatch(input.pattern, rel) || globMatch(input.pattern, path.basename(f));
101
+ });
102
+
103
+ if (matches.length === 0) return 'No matches found.';
104
+
105
+ // Sort by modification time (newest first)
106
+ matches.sort((a, b) => {
107
+ try {
108
+ return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs;
109
+ } catch { return 0; }
110
+ });
111
+
112
+ return matches.join('\n');
113
+ } catch (e) {
114
+ return `Error: ${e.message}`;
115
+ }
116
+ },
117
+ };