@yanzc/claude-pro 0.9.1 → 0.9.3
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.
- package/README.md +10 -7
- package/package.json +1 -1
- package/src/agent.js +161 -49
- package/src/api.js +44 -7
- package/src/commands.js +9 -5
- package/src/config.js +22 -12
- package/src/main.js +1 -1
- package/src/prompts.js +1 -1
- package/src/ratelimit.js +1 -1
- package/src/restart.js +3 -0
- package/src/runtime.js +10 -4
- package/src/session.js +47 -34
- package/src/tools/bash.js +1 -1
- package/src/tools/search.js +82 -24
- package/src/ui/ansi.js +11 -2
- package/src/ui/repl.js +61 -15
- package/src/ui/screen.js +75 -22
- package/src/utils/shell.js +9 -10
- package/src/verify.js +0 -57
package/src/config.js
CHANGED
|
@@ -15,7 +15,6 @@ import path from 'node:path';
|
|
|
15
15
|
import os from 'node:os';
|
|
16
16
|
import { fileURLToPath } from 'node:url';
|
|
17
17
|
import { normalizeTtl } from './cache.js';
|
|
18
|
-
import { discoverVerifyCommand } from './verify.js';
|
|
19
18
|
|
|
20
19
|
export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
21
20
|
// A source checkout (a git clone, also when npm links to one), as opposed to a copy installed from npm: the agent
|
|
@@ -34,6 +33,9 @@ export const BASIC_SETTINGS = {
|
|
|
34
33
|
tui: { default: 'fullscreen', legacy: 'CLAUDE_PRO_TUI', description: 'fullscreen or default; /tui switches and remembers it' },
|
|
35
34
|
promptCacheTtl: { default: '1h', legacy: 'CLAUDE_CODE_PROMPT_CACHE_TTL', description: 'Conversation prompt cache: 5m or 1h' },
|
|
36
35
|
subagentPromptCacheTtl: { default: '5m', legacy: 'CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL', description: 'Sub-agent, compaction and side-query prompt cache: 5m or 1h' },
|
|
36
|
+
// `userOnly`: read from ~/.claude-pro/settings.json only. It deletes the data of every project, so a project's
|
|
37
|
+
// settings file (it comes with the repository) must not lower it.
|
|
38
|
+
cleanupPeriodDays: { default: 30, userOnly: true, description: 'Days a conversation is kept after it was last used (then deleted with its traces, as in Claude Code; at least 1)' },
|
|
37
39
|
};
|
|
38
40
|
|
|
39
41
|
// Advanced keys, shown only by /config advanced (or config list --advanced). Settings files may also carry
|
|
@@ -62,6 +64,11 @@ export const KNOWN_KEYS = {
|
|
|
62
64
|
};
|
|
63
65
|
|
|
64
66
|
function basicValue(key, value) {
|
|
67
|
+
if (key === 'cleanupPeriodDays') {
|
|
68
|
+
const days = typeof value === 'number' ? value : /^\s*\d+\s*$/.test(String(value)) ? Number(value) : NaN;
|
|
69
|
+
if (Number.isInteger(days) && days >= 1) return days;
|
|
70
|
+
throw new Error(`Invalid ${key}: ${value}. A whole number of days, at least 1 (e.g. 3650 to keep conversations for years).`);
|
|
71
|
+
}
|
|
65
72
|
if (typeof value !== 'string') throw new Error(`${key} must be a string.`);
|
|
66
73
|
const text = value.trim();
|
|
67
74
|
if (key === 'model') {
|
|
@@ -93,6 +100,7 @@ export function writeConfigSetting(file, key, value) {
|
|
|
93
100
|
key = configKey(key);
|
|
94
101
|
const basic = BASIC_SETTINGS[key];
|
|
95
102
|
const normalized = basic ? basicValue(key, value) : String(value);
|
|
103
|
+
if (basic?.userOnly && path.resolve(file) !== path.resolve(userSettingsFile())) throw new Error(`${key} is read from ${userSettingsFile()} only.`);
|
|
96
104
|
updateSettingsFile(file, (json) => {
|
|
97
105
|
if (basic) {
|
|
98
106
|
json[key] = normalized;
|
|
@@ -154,8 +162,9 @@ export function loadConfig({ cwd = process.cwd(), flags = {} } = {}) {
|
|
|
154
162
|
if (!json) continue;
|
|
155
163
|
set(json.env, file);
|
|
156
164
|
for (const [key, spec] of Object.entries(BASIC_SETTINGS)) {
|
|
165
|
+
if (spec.userOnly && scope !== 'user') continue;
|
|
157
166
|
// A top-level field wins over its legacy spelling in the same file; later files win over earlier ones.
|
|
158
|
-
const value = json[key] ?? json.env?.[spec.legacy];
|
|
167
|
+
const value = json[key] ?? (spec.legacy ? json.env?.[spec.legacy] : undefined);
|
|
159
168
|
if (value == null) continue;
|
|
160
169
|
try { settings[key] = basicValue(key, value); sources[key] = file; } catch { /* invalid: use the earlier value or default */ }
|
|
161
170
|
}
|
|
@@ -279,9 +288,14 @@ export class Config {
|
|
|
279
288
|
get overloadedRetryMaxDelay() { return 32_000; }
|
|
280
289
|
get overloadedMaxWait() { return this.rateLimitMaxWait; }
|
|
281
290
|
|
|
282
|
-
//
|
|
291
|
+
// At the model's input window (only sub-agent definitions may ask for a smaller one), less the room the compaction
|
|
292
|
+
// itself takes: its request is the conversation with the instruction at its end, and its reply (the summary and
|
|
293
|
+
// the thinking before it) counts against the window too. With no room left, the summary request of a
|
|
294
|
+
// conversation at the window was refused as too long and the conversation sent again without its cache (895k
|
|
295
|
+
// tokens of plain input on Opus, 2026-11-02; a request that fits reads them from the cache at a twentieth).
|
|
283
296
|
compactWindow(model = this.model, own = 0) {
|
|
284
|
-
|
|
297
|
+
const window = own > 0 ? Math.min(own, model.contextWindow) : model.contextWindow;
|
|
298
|
+
return window - Math.min(40_000, Math.round(window * 0.05));
|
|
285
299
|
}
|
|
286
300
|
|
|
287
301
|
get bashDefaultTimeout() { return 600_000; }
|
|
@@ -300,18 +314,14 @@ export class Config {
|
|
|
300
314
|
// How deep sub-agents may nest: the main agent is depth 0; an agent below this depth gets the Task tool.
|
|
301
315
|
get maxSubagentDepth() { return 2; }
|
|
302
316
|
|
|
303
|
-
// Verification after edits: session
|
|
304
|
-
//
|
|
317
|
+
// Verification after edits, only when asked for: the session's own (/verify, --verify) wins over the setting.
|
|
318
|
+
// With neither there is none. (Until 2026-11-11 the project's test or check script was found and run by itself:
|
|
319
|
+
// a step after every edit that nobody had asked for, minutes long where the tests are; how to verify is the
|
|
320
|
+
// model's choice, in proportion to the change.)
|
|
305
321
|
get verifyCommand() {
|
|
306
|
-
const explicit = this.verifyOverride != null || Object.prototype.hasOwnProperty.call(this.env, 'CLAUDE_PRO_VERIFY_COMMAND');
|
|
307
|
-
if (!explicit) return this.autoVerifyCommand;
|
|
308
322
|
const v = this.verifyOverride ?? this.env.CLAUDE_PRO_VERIFY_COMMAND ?? '';
|
|
309
323
|
return v.trim() && v.trim() !== 'off' ? v.trim() : null;
|
|
310
324
|
}
|
|
311
|
-
get autoVerifyCommand() { return discoverVerifyCommand(this.cwd); }
|
|
312
|
-
get verifyCommandAuto() {
|
|
313
|
-
return this.verifyOverride == null && !Object.prototype.hasOwnProperty.call(this.env, 'CLAUDE_PRO_VERIFY_COMMAND') && Boolean(this.autoVerifyCommand);
|
|
314
|
-
}
|
|
315
325
|
// How many times a failing verify command is sent back before giving up.
|
|
316
326
|
get verifyMaxRounds() { return 3; }
|
|
317
327
|
get autoMemoryEnabled() { return !/^(1|true|yes)$/i.test(this.env.CLAUDE_PRO_DISABLE_AUTO_MEMORY || ''); }
|
package/src/main.js
CHANGED
|
@@ -114,7 +114,7 @@ async function configCommand(args, cwd) {
|
|
|
114
114
|
const what = Object.entries(remembered).map(([k, v]) => `${k} ${v}`).join(', ');
|
|
115
115
|
console.log(`chosen with /model, /effort: ${what} (kept in ${files.user}; wins over the settings above, --model/--effort win over it)`);
|
|
116
116
|
}
|
|
117
|
-
console.log(`auto-compact at ${cfg.compactWindow().toLocaleString()} tokens (
|
|
117
|
+
console.log(`auto-compact at ${cfg.compactWindow().toLocaleString()} tokens (the window, less room for the summary)`);
|
|
118
118
|
if (!advanced) console.log('More controls: claude-pro config list --advanced');
|
|
119
119
|
}
|
|
120
120
|
return 0;
|
package/src/prompts.js
CHANGED
|
@@ -80,7 +80,7 @@ You run on the user's own test machine with full access: tool calls run without
|
|
|
80
80
|
- Edits made with Write, Edit, MultiEdit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
|
|
81
81
|
|
|
82
82
|
# Tools
|
|
83
|
-
- Call independent tools together in one response so that they run in parallel
|
|
83
|
+
- Call independent tools together in one response so that they run in parallel. Calls that change something (edits, commands) run one after another in the order you wrote them, so steps that depend only on each other's effect go in one response too: the edits of a change and the command that builds or tests it. When an edit fails, the commands after it in that response are not run. Start a new response when what you send next depends on what a result shows.
|
|
84
84
|
- Delegate to sub-agents (Task) when that makes the work better, faster or keeps your context small: broad searches, independent subtasks, a second look at risky work. Weigh what it costs first: each agent builds its own context and spends its own tokens (from the user's usage limit too), it does not see what you or other agents know, and agents that edit related files at the same time get in each other's way. Closely coupled work that needs shared state is usually better done yourself. Use run_in_background for long jobs.
|
|
85
85
|
- For GitHub (repositories, code, issues, pull requests, releases, Actions), use the gh CLI through Bash (gh search repos|code|issues, gh issue view, gh pr view, gh api) rather than fetching github.com pages: it returns exact and complete data, private repositories included. When gh is missing or not logged in, use WebSearch and WebFetch.
|
|
86
86
|
- If a tool call is blocked (by a hook or another control of the program), do not retry it or get around it another way: adjust your approach within what is allowed, or tell the user what is in the way.
|
package/src/ratelimit.js
CHANGED
|
@@ -245,7 +245,7 @@ export function describePause(ev, now = Date.now()) {
|
|
|
245
245
|
// announced for the same pause (null at the first one). Polling repeats every few minutes and the
|
|
246
246
|
// announced reset moves a little between waits: those only continue the pause already announced,
|
|
247
247
|
// unless the reset moved by more than two minutes.
|
|
248
|
-
export const resumeText = (ev) => (ev?.overloaded ? 'The API is answering again; continuing.' : 'The limit has cleared; continuing.');
|
|
248
|
+
export const resumeText = (ev) => (ev?.woken ? 'Going on with the model you chose.' : ev?.overloaded ? 'The API is answering again; continuing.' : 'The limit has cleared; continuing.');
|
|
249
249
|
|
|
250
250
|
export function shouldAnnounce(prev, ev) {
|
|
251
251
|
if (!prev) return true;
|
package/src/restart.js
CHANGED
|
@@ -13,6 +13,9 @@ export { RESTART_EXIT_CODE };
|
|
|
13
13
|
|
|
14
14
|
export const MAX_RESTARTS = 5; // more than this many within RESTART_WINDOW_MS is a loop, not a workflow
|
|
15
15
|
export const RESTART_WINDOW_MS = 5 * 60_000;
|
|
16
|
+
// A change of the source that an idle session sees is loaded once the source has not changed for quietMs (plus up to
|
|
17
|
+
// spreadMs, so that the sessions of a machine do not all check and restart at the same moment): see App.startSourceWatch.
|
|
18
|
+
export const reloadTiming = { quietMs: 3 * 60_000, spreadMs: 10_000 };
|
|
16
19
|
|
|
17
20
|
// True in a session that runs under the supervisor, so that it can restart.
|
|
18
21
|
export function canRestart(env = process.env) {
|
package/src/runtime.js
CHANGED
|
@@ -13,7 +13,7 @@ import { isAbort } from './api.js';
|
|
|
13
13
|
import { McpManager } from './mcp.js';
|
|
14
14
|
import { HookRunner } from './hooks.js';
|
|
15
15
|
import { BackgroundTasks, taskNotification } from './tasks.js';
|
|
16
|
-
import { autoMemoryDir,
|
|
16
|
+
import { autoMemoryDir, sweepOldData, projectDir } from './session.js';
|
|
17
17
|
import { loadAutoMemoryIndex, takeEnvSnapshot, takeEnvSnapshotAsync, localDate } from './context.js';
|
|
18
18
|
import { canRestart } from './restart.js';
|
|
19
19
|
import { RuntimeTrace } from './trace.js';
|
|
@@ -24,9 +24,15 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
|
|
|
24
24
|
const trace = new RuntimeTrace({ cwd, sessionId, enabled: config.traceEnabled });
|
|
25
25
|
applyRememberedChoices(config, flags); // what /model and /effort chose last time
|
|
26
26
|
if (flags.verify) config.verifyOverride = flags.verify;
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
// Old conversations and what goes with them, in the background a while after the start (not in the self-check's
|
|
28
|
+
// throwaway process, nor a test's: CLAUDE_PRO_CONFIG_DIR points elsewhere then anyway)
|
|
29
|
+
if (process.env.CLAUDE_PRO_SELF_CHECK !== '1') {
|
|
30
|
+
setTimeout(() => {
|
|
31
|
+
sweepOldData({ days: config.setting('cleanupPeriodDays'), keep: [sessionId, config.sessionId] })
|
|
32
|
+
.then((done) => { if (done.files) trace.append('cleanup', { conversations: done.conversations, files: done.files, bytes: done.bytes }); })
|
|
33
|
+
.catch(() => {});
|
|
34
|
+
}, 15_000).unref();
|
|
35
|
+
}
|
|
30
36
|
pruneStaleShellFiles();
|
|
31
37
|
// Full access: nothing is ever asked.
|
|
32
38
|
const checkpoints = new CheckpointStore(path.join(projectDir(cwd), 'checkpoints', `${Date.now()}-${crypto.randomBytes(3).toString('hex')}`));
|
package/src/session.js
CHANGED
|
@@ -88,46 +88,59 @@ export function toolResultsDir(cwd) {
|
|
|
88
88
|
return path.join(projectDir(cwd), 'tool-results');
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
// Delete saved tool output older than maxAgeMs (best effort, run at startup).
|
|
92
|
-
export function pruneToolResults(cwd, maxAgeMs = 7 * 24 * 3600_000) {
|
|
93
|
-
const dir = toolResultsDir(cwd);
|
|
94
|
-
let entries = [];
|
|
95
|
-
try { entries = fs.readdirSync(dir); } catch { return; }
|
|
96
|
-
const cutoff = Date.now() - maxAgeMs;
|
|
97
|
-
for (const name of entries) {
|
|
98
|
-
const file = path.join(dir, name);
|
|
99
|
-
try { if (fs.statSync(file).mtimeMs < cutoff) fs.rmSync(file, { force: true }); } catch { /* ignore */ }
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// Delete the traces (see trace.js) of conversations not traced for maxAgeMs: one file a conversation, up to 40 MB
|
|
104
|
-
// with its rotation, kept for good before (best effort, run at startup).
|
|
105
|
-
export function pruneTraces(cwd, maxAgeMs = 30 * 24 * 3600_000) {
|
|
106
|
-
const dir = path.join(projectDir(cwd), 'traces');
|
|
107
|
-
let entries = [];
|
|
108
|
-
try { entries = fs.readdirSync(dir); } catch { return; }
|
|
109
|
-
const cutoff = Date.now() - maxAgeMs;
|
|
110
|
-
for (const name of entries) {
|
|
111
|
-
const file = path.join(dir, name);
|
|
112
|
-
try { if (fs.statSync(file).mtimeMs < cutoff) fs.rmSync(file, { force: true }); } catch { /* ignore */ }
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
91
|
// Where /rewind keeps file snapshots: one sub-directory per run of the program.
|
|
117
92
|
export function checkpointsDir(cwd) {
|
|
118
93
|
return path.join(projectDir(cwd), 'checkpoints');
|
|
119
94
|
}
|
|
120
95
|
|
|
121
|
-
// Delete
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
96
|
+
// Delete what is older than `days` (the cleanupPeriodDays setting, as in Claude Code: 30 by default), in every
|
|
97
|
+
// project: conversations not written to since (they no longer appear in /resume), their traces, saved tool outputs
|
|
98
|
+
// (at most 7 days) and /rewind snapshots (at most 14 days). The memory is never touched. Conversations were kept
|
|
99
|
+
// for good before: 646 MB in 176 files in a month (2026-11-11), of which only the current project's tool outputs,
|
|
100
|
+
// snapshots and traces were deleted, and only when a session started there. Runs in the background, at most once
|
|
101
|
+
// an hour on the machine (`marker`); `keep`: conversation ids not to delete whatever their age. Returns what went.
|
|
102
|
+
export async function sweepOldData({ days, keep = [], root = path.join(CONFIG_DIR, 'projects'), now = Date.now() } = {}) {
|
|
103
|
+
const done = { conversations: 0, files: 0, bytes: 0 };
|
|
104
|
+
if (!(days >= 1)) return done;
|
|
105
|
+
const marker = path.join(root, '.last-sweep');
|
|
106
|
+
try { if (now - fs.statSync(marker).mtimeMs < 3600_000) return done; } catch { /* never swept */ }
|
|
107
|
+
try { fs.mkdirSync(root, { recursive: true }); fs.writeFileSync(marker, ''); } catch { return done; }
|
|
108
|
+
const day = 24 * 3600_000;
|
|
109
|
+
const keepIds = new Set(keep.filter(Boolean));
|
|
110
|
+
const fsp = fs.promises;
|
|
111
|
+
const list = async (dir) => { try { return await fsp.readdir(dir, { withFileTypes: true }); } catch { return []; } };
|
|
112
|
+
const old = async (file, maxAgeMs) => { try { return now - (await fsp.stat(file)).mtimeMs > maxAgeMs; } catch { return false; } };
|
|
113
|
+
const remove = async (file, isDir = false) => {
|
|
114
|
+
try {
|
|
115
|
+
const size = isDir ? 0 : (await fsp.stat(file)).size;
|
|
116
|
+
await fsp.rm(file, { recursive: isDir, force: true });
|
|
117
|
+
done.files++;
|
|
118
|
+
done.bytes += size;
|
|
119
|
+
return true;
|
|
120
|
+
} catch { return false; }
|
|
121
|
+
};
|
|
122
|
+
for (const project of await list(root)) {
|
|
123
|
+
if (!project.isDirectory()) continue;
|
|
124
|
+
const dir = path.join(root, project.name);
|
|
125
|
+
for (const e of await list(dir)) {
|
|
126
|
+
const id = e.name.replace(/\.jsonl$/, '');
|
|
127
|
+
if (!e.isFile() || id === e.name || keepIds.has(id)) continue;
|
|
128
|
+
if (await old(path.join(dir, e.name), days * day) && (await remove(path.join(dir, e.name)))) done.conversations++;
|
|
129
|
+
}
|
|
130
|
+
for (const e of await list(path.join(dir, 'traces'))) { // a conversation's trace is written with it
|
|
131
|
+
const f = path.join(dir, 'traces', e.name);
|
|
132
|
+
if (!keepIds.has(e.name.replace(/\.jsonl(\.\d+)?$/, '')) && (await old(f, days * day))) await remove(f);
|
|
133
|
+
}
|
|
134
|
+
for (const e of await list(path.join(dir, 'tool-results'))) {
|
|
135
|
+
const f = path.join(dir, 'tool-results', e.name);
|
|
136
|
+
if (await old(f, Math.min(days, 7) * day)) await remove(f);
|
|
137
|
+
}
|
|
138
|
+
for (const e of await list(path.join(dir, 'checkpoints'))) { // one directory per run of the program
|
|
139
|
+
const f = path.join(dir, 'checkpoints', e.name);
|
|
140
|
+
if (await old(f, Math.min(days, 14) * day)) await remove(f, true);
|
|
141
|
+
}
|
|
130
142
|
}
|
|
143
|
+
return done;
|
|
131
144
|
}
|
|
132
145
|
|
|
133
146
|
// Persistent, model-maintained memory for this project (MEMORY.md + topic files).
|
package/src/tools/bash.js
CHANGED
|
@@ -62,7 +62,7 @@ export function makeBashTool(config) {
|
|
|
62
62
|
name: 'Bash',
|
|
63
63
|
description: `Executes a given ${isCmd ? 'cmd.exe' : 'bash'} command with an optional timeout. The working directory persists between commands; shell state (variables, functions) does not.
|
|
64
64
|
|
|
65
|
-
This tool is for terminal operations like git, npm, docker, running builds and tests. For file work use the dedicated tools instead of shell commands: Read, not cat/head/tail; Edit, not sed/awk; Write, not echo or heredoc redirection; Glob and Grep, not find and grep. A script is fine for a mechanical change across many files, once you know git can bring them back
|
|
65
|
+
This tool is for terminal operations like git, npm, docker, running builds and tests. For file work use the dedicated tools instead of shell commands: Read, not cat/head/tail; Edit, not sed/awk; Write, not echo or heredoc redirection; Glob and Grep, not find and grep. An edit made with Edit, MultiEdit or Write can be undone with /rewind and is shown to the user as a diff; one made by a command (a script that rewrites the file, sed -i) is neither. To edit and then build or test in one step, put the edit calls and the Bash call in the same response: they run in that order. A script is fine for a mechanical change across many files, once you know git can bring them back.
|
|
66
66
|
|
|
67
67
|
Usage notes:
|
|
68
68
|
- Quote file paths that contain spaces with double quotes.
|
package/src/tools/search.js
CHANGED
|
@@ -11,6 +11,28 @@ import { decodeText as decodeFile } from '../utils/encoding.js';
|
|
|
11
11
|
|
|
12
12
|
const IGNORED_DIRS = new Set(['node_modules', '.git', '.svn', '.hg', '__pycache__', '.venv', 'dist-newstyle']);
|
|
13
13
|
|
|
14
|
+
// How long a search may take. A search of a home directory or a drive (a million files and more) does not end in
|
|
15
|
+
// any useful time: in a month of traces 31 calls took 50 minutes together, a Grep up to 14 minutes, with the turn
|
|
16
|
+
// waiting. Past the limit the search stops and gives what it found, saying that it is not all (Claude Code stops
|
|
17
|
+
// ripgrep after 20 seconds).
|
|
18
|
+
export const searchLimits = { ms: 30_000 };
|
|
19
|
+
const stoppedNote = (what) => `(The search was stopped after ${Math.round(searchLimits.ms / 1000)} s without finishing, so ${what} Search a narrower path${what.includes('match') ? ', or add a glob or type' : ' or use a more specific pattern'}.)`;
|
|
20
|
+
|
|
21
|
+
// When each file was last changed (ms; null: it cannot be read), without blocking: statSync for 20,000 files held
|
|
22
|
+
// the program for a second.
|
|
23
|
+
async function mtimes(files) {
|
|
24
|
+
const out = new Array(files.length).fill(null);
|
|
25
|
+
let next = 0;
|
|
26
|
+
const worker = async () => {
|
|
27
|
+
while (next < files.length) {
|
|
28
|
+
const i = next++;
|
|
29
|
+
try { out[i] = (await fs.promises.stat(files[i])).mtimeMs; } catch { /* vanished */ }
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
await Promise.all(Array.from({ length: Math.min(32, files.length) }, worker));
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
14
36
|
export const GlobTool = {
|
|
15
37
|
name: 'Glob',
|
|
16
38
|
readOnly: true,
|
|
@@ -43,21 +65,24 @@ export const GlobTool = {
|
|
|
43
65
|
const name = path.basename(p);
|
|
44
66
|
return IGNORED_DIRS.has(name) && !explicit.includes(name);
|
|
45
67
|
};
|
|
46
|
-
|
|
68
|
+
let files = [];
|
|
69
|
+
let stopped = false;
|
|
47
70
|
const start = Date.now();
|
|
48
71
|
try {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
72
|
+
const walked = await globFiles(base, pattern, { skip: exclude, signal: ctx.signal, max: 20_000, deadline: start + searchLimits.ms });
|
|
73
|
+
stopped = walked.stopped;
|
|
74
|
+
const times = await mtimes(walked.files);
|
|
75
|
+
files = walked.files.map((abs, i) => ({ abs, mtime: times[i] })).filter((f) => f.mtime !== null);
|
|
52
76
|
} catch (e) {
|
|
53
77
|
return { isError: true, content: `Glob failed: ${e.message}` };
|
|
54
78
|
}
|
|
55
79
|
files.sort((a, b) => b.mtime - a.mtime);
|
|
56
80
|
const limit = 1000;
|
|
57
81
|
const shown = files.slice(0, limit).map((f) => f.abs);
|
|
58
|
-
let content = shown.length ? shown.join('\n') : 'No files found';
|
|
82
|
+
let content = shown.length ? shown.join('\n') : stopped ? 'No files found so far' : 'No files found';
|
|
59
83
|
if (files.length > limit) content += `\n(Results are truncated: showing ${limit} of ${files.length}. Consider using a more specific path or pattern.)`;
|
|
60
|
-
|
|
84
|
+
if (stopped) content += `\n${stoppedNote('there may be more files than these.')}`;
|
|
85
|
+
return { content, display: { summary: `Found ${files.length} file${files.length === 1 ? '' : 's'} in ${Date.now() - start}ms${stopped ? ' (stopped: not finished)' : ''}` } };
|
|
61
86
|
},
|
|
62
87
|
};
|
|
63
88
|
|
|
@@ -65,8 +90,9 @@ export const GlobTool = {
|
|
|
65
90
|
// dot directories too: fs.glob leaves those out of * and ** and has no option for them, so "**/*.yml" missed
|
|
66
91
|
// .github/workflows/ci.yml, which Grep (searching hidden files) found. `skip(name)`: a directory not to go into. The
|
|
67
92
|
// walk starts at the pattern's fixed leading directories, and goes no deeper than its segments without a "**". A
|
|
68
|
-
// linked directory is not entered (it can make a loop).
|
|
69
|
-
|
|
93
|
+
// linked directory is not entered (it can make a loop). Directories are read several at a time; past `deadline`
|
|
94
|
+
// (ms since epoch) the walk ends with what it has. Returns {files, stopped: it ended at the deadline}.
|
|
95
|
+
async function globFiles(base, pattern, { skip, signal, max, deadline = Infinity }) {
|
|
70
96
|
const parts = pattern.replace(/^(?:\.\/)+/, '').split('/');
|
|
71
97
|
const fixed = [];
|
|
72
98
|
while (parts.length > 1 && !/[*?[\]{}]/.test(parts[0])) fixed.push(parts.shift());
|
|
@@ -74,22 +100,40 @@ async function globFiles(base, pattern, { skip, signal, max }) {
|
|
|
74
100
|
const re = globToRegExp(rest, process.platform === 'win32');
|
|
75
101
|
const maxDepth = /\*\*|[{}]/.test(rest) ? Infinity : parts.length;
|
|
76
102
|
const found = [];
|
|
103
|
+
let stopped = false;
|
|
104
|
+
const done = () => signal?.aborted || found.length >= max || (stopped ||= Date.now() > deadline);
|
|
105
|
+
// at most this many directories are being read at once
|
|
106
|
+
let reading = 0;
|
|
107
|
+
const waiting = []; // a stack: the deepest directories first, which keeps it short in a wide tree
|
|
108
|
+
const readDir = async (dir) => {
|
|
109
|
+
if (reading >= 16) await new Promise((go) => waiting.push(go));
|
|
110
|
+
reading++;
|
|
111
|
+
try {
|
|
112
|
+
return done() ? null : await fs.promises.readdir(dir, { withFileTypes: true });
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
} finally {
|
|
116
|
+
reading--;
|
|
117
|
+
waiting.pop()?.();
|
|
118
|
+
}
|
|
119
|
+
};
|
|
77
120
|
const walk = async (dir, rel, depth) => {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
121
|
+
const entries = await readDir(dir);
|
|
122
|
+
if (!entries) return;
|
|
123
|
+
const below = [];
|
|
81
124
|
for (const e of entries) {
|
|
82
|
-
if (
|
|
125
|
+
if (done()) break;
|
|
83
126
|
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
84
127
|
const abs = path.join(dir, e.name);
|
|
85
128
|
let isFile = e.isFile();
|
|
86
129
|
if (e.isSymbolicLink()) { try { isFile = (await fs.promises.stat(abs)).isFile(); } catch { /* a broken link */ } }
|
|
87
|
-
if (isFile) { if (re.test(r)) found.push(abs); }
|
|
88
|
-
else if (e.isDirectory() && depth < maxDepth && !skip(e.name))
|
|
130
|
+
if (isFile) { if (re.test(r) && found.length < max) found.push(abs); }
|
|
131
|
+
else if (e.isDirectory() && depth < maxDepth && !skip(e.name)) below.push(walk(abs, r, depth + 1));
|
|
89
132
|
}
|
|
133
|
+
await Promise.all(below);
|
|
90
134
|
};
|
|
91
135
|
await walk(path.join(base, ...fixed), '', 1);
|
|
92
|
-
return found;
|
|
136
|
+
return { files: found, stopped: stopped && !signal?.aborted };
|
|
93
137
|
}
|
|
94
138
|
|
|
95
139
|
// rg --type names (plus a few aliases) → file extensions, for the JS scanner.
|
|
@@ -272,10 +316,13 @@ const decodeText = (buf) => decodeFile(buf, { writable: false })?.text ?? null;
|
|
|
272
316
|
|
|
273
317
|
const clip = (line) => (line.length > MAX_COLUMNS ? `${line.slice(0, MAX_COLUMNS)} [... omitted end of long line]` : line);
|
|
274
318
|
|
|
275
|
-
|
|
319
|
+
// `timeoutMs`: rg is stopped then, and what it had found by then is given, with `timedOut`.
|
|
320
|
+
function runRg(bin, args, cwd, signal, timeoutMs = searchLimits.ms) {
|
|
276
321
|
return new Promise((resolve) => {
|
|
277
322
|
const child = spawn(bin, args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
278
323
|
let out = '', err = '';
|
|
324
|
+
let timedOut = false;
|
|
325
|
+
const timer = setTimeout(() => { timedOut = true; child.kill(); }, timeoutMs);
|
|
279
326
|
// Decoded as a stream (a Chinese path or line can be split between two chunks), and rg is stopped once
|
|
280
327
|
// there is more than will ever be shown instead of scanning on.
|
|
281
328
|
child.stdout.setEncoding('utf8');
|
|
@@ -288,8 +335,13 @@ function runRg(bin, args, cwd, signal) {
|
|
|
288
335
|
child.stderr.on('data', (d) => { if (err.length < 100_000) err += d; });
|
|
289
336
|
const onAbort = () => child.kill();
|
|
290
337
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
291
|
-
child.on('close', (code) => {
|
|
292
|
-
|
|
338
|
+
child.on('close', (code) => {
|
|
339
|
+
clearTimeout(timer);
|
|
340
|
+
signal?.removeEventListener('abort', onAbort);
|
|
341
|
+
// the last line may have been cut where rg was stopped
|
|
342
|
+
resolve(timedOut ? { code: 0, out: out.slice(0, out.lastIndexOf('\n') + 1), err, timedOut } : { code, out, err });
|
|
343
|
+
});
|
|
344
|
+
child.on('error', (e) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); resolve({ code: 2, out: '', err: e.message, spawnError: true }); });
|
|
293
345
|
});
|
|
294
346
|
}
|
|
295
347
|
|
|
@@ -441,6 +493,7 @@ Usage:
|
|
|
441
493
|
const mode = input.output_mode || 'files_with_matches';
|
|
442
494
|
let lines = null;
|
|
443
495
|
let note = '';
|
|
496
|
+
let stopped = false;
|
|
444
497
|
const rg = ripgrepPath(ctx.config);
|
|
445
498
|
if (rg) {
|
|
446
499
|
// --crlf lets `$` match before \r\n, so line-end anchors also work in Windows (CRLF) files.
|
|
@@ -462,11 +515,14 @@ Usage:
|
|
|
462
515
|
if (!r.spawnError) {
|
|
463
516
|
if (r.code === 2 && !r.out) return { isError: true, content: `ripgrep error: ${r.err.trim()}` };
|
|
464
517
|
lines = r.out.split(/\r?\n/).filter(Boolean);
|
|
518
|
+
stopped = Boolean(r.timedOut);
|
|
465
519
|
}
|
|
466
520
|
}
|
|
467
521
|
if (!lines) {
|
|
468
522
|
try {
|
|
469
|
-
const
|
|
523
|
+
const limit = AbortSignal.timeout(searchLimits.ms);
|
|
524
|
+
const found = await jsGrep(input, base, mode, ctx.signal ? AbortSignal.any([ctx.signal, limit]) : limit);
|
|
525
|
+
stopped = limit.aborted && !ctx.signal?.aborted;
|
|
470
526
|
lines = found.lines;
|
|
471
527
|
if (found.skipped) note = `\n\n(${found.skipped} file${found.skipped === 1 ? '' : 's'} larger than ${MAX_FILE_BYTES / 1024 / 1024}MB not searched; install ripgrep to search them)`;
|
|
472
528
|
} catch (e) {
|
|
@@ -474,9 +530,10 @@ Usage:
|
|
|
474
530
|
}
|
|
475
531
|
}
|
|
476
532
|
if (mode === 'files_with_matches') {
|
|
477
|
-
|
|
478
|
-
|
|
533
|
+
const times = await mtimes(lines);
|
|
534
|
+
lines = lines.map((f, i) => ({ f, t: times[i] ?? 0 })).sort((a, b) => b.t - a.t).map((x) => x.f);
|
|
479
535
|
}
|
|
536
|
+
if (stopped) note += `\n\n${stoppedNote('there may be more matches than these.')}`;
|
|
480
537
|
const total = lines.length;
|
|
481
538
|
const offset = Math.max(0, input.offset || 0);
|
|
482
539
|
const limit = input.head_limit === 0 ? Infinity : (input.head_limit || 1000);
|
|
@@ -484,16 +541,17 @@ Usage:
|
|
|
484
541
|
let content;
|
|
485
542
|
let summary;
|
|
486
543
|
if (mode === 'files_with_matches') {
|
|
487
|
-
content = total ? `Found ${total} file${total === 1 ? '' : 's'}\n${page.join('\n')}` : 'No files found';
|
|
544
|
+
content = total ? `Found ${total} file${total === 1 ? '' : 's'}\n${page.join('\n')}` : stopped ? 'No files found so far' : 'No files found';
|
|
488
545
|
summary = `Found ${total} file${total === 1 ? '' : 's'}`;
|
|
489
546
|
} else if (mode === 'count') {
|
|
490
547
|
const sum = lines.reduce((n, l) => n + (parseInt(l.split(':').pop(), 10) || 0), 0);
|
|
491
|
-
content = total ? page.join('\n') + `\n\nFound ${sum} total occurrences across ${total} files.` : 'No matches found';
|
|
548
|
+
content = total ? page.join('\n') + `\n\nFound ${sum} total occurrences across ${total} files.` : stopped ? 'No matches found so far' : 'No matches found';
|
|
492
549
|
summary = `Found ${sum} match${sum === 1 ? '' : 'es'} in ${total} file${total === 1 ? '' : 's'}`;
|
|
493
550
|
} else {
|
|
494
|
-
content = total ? page.join('\n') : 'No matches found';
|
|
551
|
+
content = total ? page.join('\n') : stopped ? 'No matches found so far' : 'No matches found';
|
|
495
552
|
summary = `Found ${total} line${total === 1 ? '' : 's'}`;
|
|
496
553
|
}
|
|
554
|
+
if (stopped) summary += ' (stopped: not finished)';
|
|
497
555
|
if (total > offset + page.length) content += `\n\n(Showing ${page.length} of ${total} results. Use offset/head_limit to page, or narrow the search.)`;
|
|
498
556
|
return { content: content + note, display: { summary } };
|
|
499
557
|
},
|
package/src/ui/ansi.js
CHANGED
|
@@ -96,11 +96,20 @@ function inRanges(cp, ranges) {
|
|
|
96
96
|
return false;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
// Some Windows conhosts render symbols such as ·, … and ↓ in two cells even in UTF-8. Use the cursor
|
|
100
|
+
// advances measured at startup instead of guessing from the code page (or changing the user's console settings).
|
|
101
|
+
const terminalWidths = new Map();
|
|
102
|
+
export function setTerminalWidths(widths) {
|
|
103
|
+
terminalWidths.clear();
|
|
104
|
+
for (const [char, width] of widths) {
|
|
105
|
+
if (width === 1 || width === 2) terminalWidths.set(char.codePointAt(0), width);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
99
109
|
export function codePointWidth(cp) {
|
|
100
110
|
if (cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0;
|
|
101
111
|
if (inRanges(cp, ZERO)) return 0;
|
|
102
|
-
|
|
103
|
-
return 1;
|
|
112
|
+
return terminalWidths.get(cp) ?? (inRanges(cp, WIDE) ? 2 : 1);
|
|
104
113
|
}
|
|
105
114
|
|
|
106
115
|
const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|