@yanzc/claude-pro 0.9.1 → 0.9.2
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 +4 -4
- 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 +11 -11
- 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/tools/bash.js +1 -1
- package/src/tools/search.js +82 -24
- package/src/ui/repl.js +61 -15
- package/src/utils/shell.js +9 -10
- package/src/verify.js +0 -57
package/README.md
CHANGED
|
@@ -134,7 +134,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
134
134
|
|
|
135
135
|
## 限流:自动暂停,到点自动恢复
|
|
136
136
|
|
|
137
|
-
网关账户的 5 小时和每周限额用完时,不报错停下,而是暂停并显示倒计时(`✻ 5-hour limit reached · resumes at 23:41 (in 2h 13m)`,Esc
|
|
137
|
+
网关账户的 5 小时和每周限额用完时,不报错停下,而是暂停并显示倒计时(`✻ 5-hour limit reached · resumes at 23:41 (in 2h 13m)`,Esc 可取消),到重置时间重发同一个请求,任务接着做完。暂停期间可以直接输入 `/model <另一个模型>`(暂停时唯一能在任务进行中执行的命令):暂停立即结束,这个请求改发给新模型,不用先按 Esc 再说"继续"。暂停超过一小时、提示词缓存已过期时,重发前会先清掉旧的工具结果和旧工具调用里的大段文本(和离开一小时后回来时一样),避免把整段对话原样重写进缓存。网关过载(529)同样先重试、再暂停等它恢复。最多等 6 小时(`CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS`,`0` = 不等直接报错);重置时间更远(比如周限额还有几天)时直接报错,并写明几点重置。
|
|
138
138
|
|
|
139
139
|
## 终端标题、页脚与窗口缩放
|
|
140
140
|
|
|
@@ -148,7 +148,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
148
148
|
交互式会话运行在一个很薄的**监督进程**(`src/supervisor.js`,只用 Node 内置模块)之下,所以程序可以自己重启、加载自己刚改过的代码,不需要你退出再启动:
|
|
149
149
|
|
|
150
150
|
- **模型自己重启**:改完 `src/`、`bin/` 里的代码后,模型调用 `Restart` 工具。它先在一个临时进程里把新代码完整启动一遍(所有模块能加载、界面能画出来、工具定义和系统提示词合法)——**启动不起来就不重启**,把错误还给模型去修,修好再调用;通过后在**本回合结束时**重启,对话、待办列表、`/model`、`/effort`、排队的消息、输入框里没发出去的草稿、`/rewind` 检查点都带过去,新进程里模型收到一条"已重启"的提示后接着做(可用 `then` 指定重启后先验证什么)。只在**源码仓库**(有 `.git` 的克隆,包括 `npm link` 到它)里这样做:从 npm 装的副本没有版本控制、下次更新会被覆盖,那里不给模型 `Restart` 工具,系统提示词改成"不要改自己的文件,绕过问题并在最后说明缺陷,方便用户反馈"。
|
|
151
|
-
-
|
|
151
|
+
- **改了源码自动重启**:`src/`、`bin/` 下的文件变过,就自动做同样的检查并重启。本会话的回合进行中发生的改动(多半是它自己改的)在回合结束时加载;会话空闲时看到的改动是别处做的(另一个会话在改程序、编辑器),要等源码连续 3 分钟没有再变才加载,页脚会提示,急用可以 `/restart`——否则一个会话每改一步,其余打开的会话都跟着检查、重启一次,加载的还是改到一半的代码。npm 装好的新版本是完整的,不用等。检查不通过只提示错误、不重启。按 Esc 打断的那一回合不会触发。源码自动重启固定开启,旧 `CLAUDE_PRO_AUTO_RESTART` 不再生效。
|
|
152
152
|
- **手动**:`/restart`(别名 `/reload`),`/restart force` 跳过检查并无视后台任务。
|
|
153
153
|
- 后台 agent / 后台 shell 会被重启杀掉,所以有它们在跑时拒绝重启(可 `force`)。5 分钟内重启超过 5 次视为死循环,拒绝。
|
|
154
154
|
- 重启之间终端保持原样(不退回 shell 提示符,原始模式不关),重启时敲的键不会丢;标签标题也不闪。
|
|
@@ -220,7 +220,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
220
220
|
- **全屏模式(默认)**:程序画在终端的备用屏幕上(像 vim),输入框固定在窗口最底下,不随输出或终端滚动条移动;对话在程序里滚动:鼠标滚轮(每格 3 行)、`PgUp`/`PgDn`(半屏)、`Ctrl+Home`(对话开头)、`Ctrl+End`(回到最新)。往上翻时新输出不会把画面拉回底部,底部浮着 `Jump to bottom (ctrl+End) ↓ · N new lines`,**点它**或按 `Ctrl+End` 回到底部;发消息时自动回到底部。**选中文字直接用鼠标拖**(不用按 Shift),松开只保留反色选择,不会自动复制;双击选一个词,三击选一整行;拖到对话区上下边缘会跟着滚动。选中的部分反色显示,点一下别处、按 `Esc` 或任意键就消失;有选中时只有 `Ctrl+C` 会复制。**输入框里**单击把光标移到那里,拖动、双击、三击选中正在写的文字,`Ctrl+C` 复制(不会打断任务,也不清空输入框);选中后打字不会替换选中的文字。**引用追问**(像 ChatGPT 的“向 ChatGPT 提问”):选中对话里的内容后按 `Ctrl+Q`(终端占用了 `Ctrl+Q` 时用 `Alt+Q`),选中的内容就以 `[Quote #1 +12 lines]` 插进输入框,光标停在下一行,直接写追问。发给模型的是选中的原文,加上它所在的那条工具调用、回复或消息的首行(`<quote source="⏺ Read(src/api.js)">…</quote>`),模型就知道问的是哪一段、哪个文件;对话里只显示引用的前三行。可以连续引用好几段,退格一次删掉整个引用。`Ctrl+V` 粘贴剪贴板文字(剪贴板里只有图片时作为图片附加),`Alt+V` 优先附加剪贴板图片;右键不执行复制或粘贴。仍可按住 Shift 拖动用终端自己的选中。退出后终端回到启动前的样子(对话不留在终端滚动记录里)。`/tui default` 切回经典模式(对话写进终端自己的滚动记录,输入框在窗口底部、靠空行顶到底),`/tui fullscreen` 切回全屏,选择会记到 `settings.json` 顶层的 `tui`
|
|
221
221
|
- `ctrl+c` 或连按两次 `Esc` 清掉的草稿不会丢:在空输入框按 `↑` 找回(连同粘贴的文本和图片),中间发过别的消息也可以
|
|
222
222
|
- `@` 同时补全文件和本机/远程会话:文件引用走 `Read` 工具,等于模型自己读了这个文件。最多带前 2000 行(被截断时会明确告诉模型,并把该文件记为"只读了一部分",之后 `Write` 不会去覆盖没给它看过的行);图片作为图片附加;二进制文件和超过 512KB 的文本会被跳过并提示原因;`@目录` 列出目录内容;行首 `@会话 任务` 把任务发给另一会话
|
|
223
|
-
-
|
|
223
|
+
- 上下文用满上游输入上限时自动压缩(留出写摘要要用的余量:窗口的 5%,最多 4 万 token,这样摘要请求能读缓存而不是因超长被拒),不再读取 `CLAUDE_CODE_AUTO_COMPACT_WINDOW`;子 agent 定义的 `autoCompactWindow` 仍有效,也可手动 `/compact`
|
|
224
224
|
- 会话自动保存到 `~/.claude-pro/projects/`,`claude-pro -c` 继续上次,`claude-pro -r` 选择历史会话
|
|
225
225
|
|
|
226
226
|
**`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件/会话补全、输入历史都换成新目录的;对话、模型、effort、待办、网页上的远程会话(同一个链接)不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
|
|
@@ -237,7 +237,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
237
237
|
|
|
238
238
|
**后台子 agent**:模型可以用 `Task` 的 `run_in_background: true` 把子 agent 放到后台,自己继续干别的。子 agent 完成后,结果会作为 `<task-notification>` 自动送回;如果当时主 agent 空闲,会自动开启新的一轮来处理结果。`TaskOutput` 用于提前等待结果,`TaskStop` 用于取消;`/tasks` 列出所有后台 agent,`/tasks kill agent_1` 停止其中一个。`-p` 模式会等所有后台 agent 结束后再退出。
|
|
239
239
|
|
|
240
|
-
|
|
240
|
+
**验证循环(默认关闭)**:需要时显式设置验证命令(例如 `--verify "npm run check"`、会话中 `/verify npm run check`,或 `CLAUDE_PRO_VERIFY_COMMAND`),`/verify off` 关闭;程序不再自己去找项目的测试脚本来跑。设置之后,只要某一轮改过文件,模型结束前就会自动运行验证命令。失败的输出会发回给模型继续修复,直到通过,最多 3 轮。没有改文件的轮次不会触发验证。
|
|
241
241
|
|
|
242
242
|
**大输出落盘**:工具结果超过 10 万字符时,全文会保存到 `~/.claude-pro/projects/<项目>/tool-results/`,只把预览和文件路径发给模型,模型可以再用 `Read`/`Grep` 按需查看。Bash 输出被截断时同样会保存全文。超过 7 天的旧文件在启动时自动清理。
|
|
243
243
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.2",
|
|
4
4
|
"description": "claude-pro: a command line coding agent for the codex-gateway. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
package/src/agent.js
CHANGED
|
@@ -66,18 +66,46 @@ export function persistLargeOutput(root, id, text) {
|
|
|
66
66
|
// user's answers and the like stay whatever their age.
|
|
67
67
|
export const IDLE_CLEARING = { idleMs: 65 * 60_000, keep: 5, atLeast: 20_000 };
|
|
68
68
|
export const CLEARED = '[Old tool result content cleared]';
|
|
69
|
-
|
|
69
|
+
// (Browser: an old snapshot or screenshot shows a page as it no longer is; REPL and Processes print like a command.)
|
|
70
|
+
const CLEARABLE_TOOLS = new Set(['Read', 'Bash', 'BashOutput', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'Edit', 'MultiEdit', 'Write', 'Browser', 'REPL', 'Processes']);
|
|
70
71
|
const MIN_CLEAR_TOKENS = 100; // a smaller result is left as it is: clearing it gains next to nothing
|
|
72
|
+
// What the model itself wrote into old tool calls goes the same way: after the results were cleared it was the
|
|
73
|
+
// larger half of a long conversation (traces 2026-10-31..11-10: files written, edits and inline scripts made up
|
|
74
|
+
// about half of the largest ones; one was still 549k tokens after a 38-hour pause). The start of each long text
|
|
75
|
+
// stays, so that it can still be told what the call was; a file's content is on disk.
|
|
76
|
+
const CLEARABLE_INPUTS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'Bash', 'REPL']);
|
|
77
|
+
const INPUT_CLEARING = { longerThan: 1200, keep: 300 }; // characters of one text of a tool call
|
|
78
|
+
|
|
79
|
+
// A tool call's input with its long texts cut to their start; the same object when none is long.
|
|
80
|
+
function shortInput(value) {
|
|
81
|
+
if (typeof value === 'string') {
|
|
82
|
+
if (value.length <= INPUT_CLEARING.longerThan) return value;
|
|
83
|
+
return `${value.slice(0, INPUT_CLEARING.keep)}\n[Old tool input cleared: ${value.length - INPUT_CLEARING.keep} more characters]`;
|
|
84
|
+
}
|
|
85
|
+
if (Array.isArray(value)) {
|
|
86
|
+
const out = value.map(shortInput);
|
|
87
|
+
return out.some((v, i) => v !== value[i]) ? out : value;
|
|
88
|
+
}
|
|
89
|
+
if (value && typeof value === 'object') {
|
|
90
|
+
let changed = false;
|
|
91
|
+
const out = {};
|
|
92
|
+
for (const [k, v] of Object.entries(value)) { out[k] = shortInput(v); if (out[k] !== v) changed = true; }
|
|
93
|
+
return changed ? out : value;
|
|
94
|
+
}
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
71
97
|
|
|
72
98
|
const isThinking = (b) => b.type === 'thinking' || b.type === 'redacted_thinking';
|
|
73
99
|
const resultText = (content) => (typeof content === 'string' ? content : Array.isArray(content) ? content.filter((b) => b.type === 'text').map((b) => b.text).join('\n') : '');
|
|
74
100
|
|
|
75
|
-
// Clear the results of all but the last `keep` clearable tool calls,
|
|
76
|
-
//
|
|
101
|
+
// Clear the results of all but the last `keep` clearable tool calls, and the long texts in the inputs of all but
|
|
102
|
+
// the last `keep` calls that have such (CLEARABLE_INPUTS), if that takes out at least `atLeast` tokens (else
|
|
103
|
+
// null). The thinking goes too, all of it: once a tool result before it has changed, the API takes earlier
|
|
77
104
|
// thinking for tampered with, and rejects the request. `save(id, text)` keeps a cleared output in a file and
|
|
78
105
|
// returns its path, so that what a command printed can still be looked up; a file read is read again instead.
|
|
79
|
-
// Returns {messages (a new list: the old one is not changed), results (how many were cleared), tokens
|
|
80
|
-
// how many went, thinking included), forget (the files
|
|
106
|
+
// Returns {messages (a new list: the old one is not changed), results and inputs (how many were cleared), tokens
|
|
107
|
+
// (about how many went, thinking included), forget (the files the model no longer sees the text of: their Read
|
|
108
|
+
// results or what was written to them went, and nothing newer shows them)}.
|
|
81
109
|
export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLeast = IDLE_CLEARING.atLeast, save = () => null, cwd = process.cwd() } = {}) {
|
|
82
110
|
const uses = new Map(); // tool_use id -> the tool_use block
|
|
83
111
|
for (const m of messages) if (m.role === 'assistant' && Array.isArray(m.content)) for (const b of m.content) if (b.type === 'tool_use') uses.set(b.id, b);
|
|
@@ -93,6 +121,14 @@ export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLea
|
|
|
93
121
|
clear.add(b);
|
|
94
122
|
tokens += t;
|
|
95
123
|
}
|
|
124
|
+
const calls = [...uses.values()].filter((b) => CLEARABLE_INPUTS.has(b.name));
|
|
125
|
+
const shorter = new Map(); // tool_use block -> its input with the long texts cut
|
|
126
|
+
for (const b of calls.slice(0, Math.max(0, calls.length - keep))) {
|
|
127
|
+
const input = shortInput(b.input);
|
|
128
|
+
if (input === b.input) continue;
|
|
129
|
+
shorter.set(b, input);
|
|
130
|
+
tokens += Math.max(0, estimateTokens(b.input) - estimateTokens(input));
|
|
131
|
+
}
|
|
96
132
|
if (tokens < atLeast) return null;
|
|
97
133
|
const fileOf = (b) => {
|
|
98
134
|
const p = uses.get(b.tool_use_id)?.input?.file_path;
|
|
@@ -109,9 +145,13 @@ export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLea
|
|
|
109
145
|
const out = messages.map((m) => {
|
|
110
146
|
if (!Array.isArray(m.content)) return m;
|
|
111
147
|
if (m.role === 'assistant') {
|
|
112
|
-
|
|
148
|
+
for (const b of m.content) {
|
|
149
|
+
if (b.type !== 'tool_use' || b.name !== 'Write' || !fileOf({ tool_use_id: b.id })) continue;
|
|
150
|
+
(shorter.has(b) ? gone : shown).add(fileOf({ tool_use_id: b.id }));
|
|
151
|
+
}
|
|
152
|
+
if (!m.content.some((b) => isThinking(b) || shorter.has(b))) return m;
|
|
113
153
|
for (const b of m.content) if (isThinking(b)) tokens += estimateTokens(b.thinking ?? b.data ?? '');
|
|
114
|
-
const content = m.content.filter((b) => !isThinking(b));
|
|
154
|
+
const content = m.content.filter((b) => !isThinking(b)).map((b) => (shorter.has(b) ? { ...b, input: shorter.get(b) } : b));
|
|
115
155
|
return { ...m, content: content.length ? content : [{ type: 'text', text: '(no content)' }] };
|
|
116
156
|
}
|
|
117
157
|
for (const b of m.content) {
|
|
@@ -122,7 +162,7 @@ export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLea
|
|
|
122
162
|
if (!m.content.some((b) => clear.has(b))) return m;
|
|
123
163
|
return { ...m, content: m.content.map((b) => (clear.has(b) ? { ...b, content: placeholder(b) } : b)) };
|
|
124
164
|
});
|
|
125
|
-
return { messages: out, results: clear.size, tokens, forget: [...gone].filter((f) => !shown.has(f)) };
|
|
165
|
+
return { messages: out, results: clear.size, inputs: shorter.size, tokens, forget: [...gone].filter((f) => !shown.has(f)) };
|
|
126
166
|
}
|
|
127
167
|
|
|
128
168
|
// A summary request's messages with the older half of the turns left out: the first message (the task, or the
|
|
@@ -366,6 +406,7 @@ export class Agent {
|
|
|
366
406
|
this.postCompactTokens = undefined; // undefined: never compacted; null: compacted, awaiting measurement
|
|
367
407
|
this.compactFailures = 0; // automatic compactions that failed in a row
|
|
368
408
|
this.lastActivityAt = 0; // when the last message was added (ms since epoch; 0: unknown), see clearAfterIdle
|
|
409
|
+
this.pauseControl = null; // of the turn's request in flight: has wake() while it is paused for a rate limit (see callModel)
|
|
369
410
|
this.busy = 0; // turns and summaries in progress: while there are any, the cache needs no refresh
|
|
370
411
|
this.keepAlive = isSubagent ? null : new CacheKeepAlive(this); // the prompt cache kept warm while idle
|
|
371
412
|
}
|
|
@@ -446,7 +487,7 @@ export class Agent {
|
|
|
446
487
|
});
|
|
447
488
|
}
|
|
448
489
|
|
|
449
|
-
async streamAgentRequest(request, { signal, kind = 'turn', cacheBucket = 'main', cacheMessages = true, cacheOverride = null, compactionId = null, onEvent = () => {}, waitForRateLimit = true } = {}) {
|
|
490
|
+
async streamAgentRequest(request, { signal, kind = 'turn', cacheBucket = 'main', cacheMessages = true, cacheOverride = null, compactionId = null, onEvent = () => {}, waitForRateLimit = true, afterPause = null, pauseControl = null } = {}) {
|
|
450
491
|
const handle = this.traceRequestStart({ kind, messages: request.messages, cacheBucket, cacheMessages, compactionId });
|
|
451
492
|
// A bug in what shows or traces the stream must not fail the request: it had no HTTP status, so it was taken
|
|
452
493
|
// for a network error and the request was sent (and billed) again, up to the retry limit, failing the same way
|
|
@@ -461,7 +502,7 @@ export class Agent {
|
|
|
461
502
|
}
|
|
462
503
|
};
|
|
463
504
|
try {
|
|
464
|
-
const res = await streamMessage(this.config, request, { signal, onEvent: forward, waitForRateLimit });
|
|
505
|
+
const res = await streamMessage(this.config, request, { signal, onEvent: forward, waitForRateLimit, afterPause, pauseControl });
|
|
465
506
|
if (handlerError) this.io.notice?.(`Showing the reply failed (${handlerError.message}); the reply itself is complete.`, 'warn');
|
|
466
507
|
const observed = cacheOverride ? { ...res, cache: { ...res.cache, ...cacheOverride } } : res;
|
|
467
508
|
const recorded = this.recordUsage(observed, kind === 'summary' || kind === 'keepalive' ? kind : 'turn');
|
|
@@ -578,8 +619,9 @@ export class Agent {
|
|
|
578
619
|
// (MAX_THINKING_TOKENS: thinking.type "enabled") the API wants its last assistant message to start with its
|
|
579
620
|
// thinking, which cannot stay once a result before it has changed: then nothing is cleared. Adaptive thinking,
|
|
580
621
|
// the default and the only mode of the 5.x models, has no such rule: all thinking may go, that turn's too.
|
|
622
|
+
// `pause`: called in the middle of a turn, after a pause for a rate limit (see callModel): the same holds then.
|
|
581
623
|
// Returns what clearOldToolResults did, or null.
|
|
582
|
-
clearAfterIdle(now = Date.now()) {
|
|
624
|
+
clearAfterIdle(now = Date.now(), { pause = false } = {}) {
|
|
583
625
|
if (this.isSubagent || !this.config.clearAfterIdle || !this.lastActivityAt) return null;
|
|
584
626
|
const idle = now - this.lastActivityAt;
|
|
585
627
|
if (idle <= IDLE_CLEARING.idleMs) return null;
|
|
@@ -593,7 +635,9 @@ export class Agent {
|
|
|
593
635
|
this.replaceMessages(out.messages); // into the session file too: a resumed conversation goes on with the short one
|
|
594
636
|
for (const file of out.forget) this.fileState.delete(file); // the model no longer sees it: Read before Edit/Write
|
|
595
637
|
this.lastContextTokens = Math.max(0, this.lastContextTokens - out.tokens);
|
|
596
|
-
|
|
638
|
+
const s = (n) => (n === 1 ? '' : 's');
|
|
639
|
+
const what = [out.results ? `${out.results} old tool result${s(out.results)}` : '', out.inputs ? `the long texts of ${out.inputs} old tool call${s(out.inputs)}` : '', 'the earlier thinking'].filter(Boolean);
|
|
640
|
+
this.io.notice?.(`${pause ? 'Going on' : 'Back'} after ${Math.round(idle / 60_000)} minutes, with the prompt cache expired: cleared ${what.slice(0, -1).join(', ')} and ${what.at(-1)} (about ${Math.round(out.tokens / 1000)}k tokens). The last ${IDLE_CLEARING.keep} are kept; files are read again when needed.`);
|
|
597
641
|
return out;
|
|
598
642
|
}
|
|
599
643
|
|
|
@@ -605,6 +649,16 @@ export class Agent {
|
|
|
605
649
|
return this.lastActivityAt > 0 && now - this.lastActivityAt >= TTL_MS[this.config.cacheTtl('main')];
|
|
606
650
|
}
|
|
607
651
|
|
|
652
|
+
// Is a request of this agent's turn paused for a rate limit right now (and can be sent on at once)?
|
|
653
|
+
get pausedForLimit() { return typeof this.pauseControl?.wake === 'function'; }
|
|
654
|
+
|
|
655
|
+
// End that pause now: the request is sent again at once, to the model chosen meanwhile. False when none is paused.
|
|
656
|
+
wakePause() {
|
|
657
|
+
if (!this.pausedForLimit) return false;
|
|
658
|
+
this.pauseControl.wake();
|
|
659
|
+
return true;
|
|
660
|
+
}
|
|
661
|
+
|
|
608
662
|
// The conversation's last request again, for a refresh of its cache entry (keepalive.js): the messages before
|
|
609
663
|
// the last reply, the way callModel sent them then (normalizing and repairing give the same result for the same
|
|
610
664
|
// messages), and max_tokens 1. null when there is no reply yet.
|
|
@@ -718,7 +772,7 @@ export class Agent {
|
|
|
718
772
|
if (err.promptTooLong && !compactedForError && this.messages.length > 2) {
|
|
719
773
|
compactedForError = true;
|
|
720
774
|
this.io.notice?.('Context limit reached; compacting conversation…', 'warn');
|
|
721
|
-
const outcome = await this.compactOnTheWay(signal, { required: true });
|
|
775
|
+
const outcome = await this.compactOnTheWay(signal, { required: true, overflow: err });
|
|
722
776
|
if (outcome?.interrupted) return tracedReturn(outcome);
|
|
723
777
|
continue;
|
|
724
778
|
}
|
|
@@ -846,10 +900,10 @@ export class Agent {
|
|
|
846
900
|
// A compaction that fails does not fail the turn when the request still fits (the threshold leaves room
|
|
847
901
|
// below the model's limit): the turn goes on without it, and {failed: true} is returned. After
|
|
848
902
|
// MAX_COMPACT_FAILURES in a row it is left off (see shouldAutoCompact). `required`: the request is already
|
|
849
|
-
// too long, so there is nothing to go on with, and the error is thrown.
|
|
850
|
-
async compactOnTheWay(signal, { required = false } = {}) {
|
|
903
|
+
// too long (`overflow`: the error that said so), so there is nothing to go on with, and the error is thrown.
|
|
904
|
+
async compactOnTheWay(signal, { required = false, overflow = null } = {}) {
|
|
851
905
|
try {
|
|
852
|
-
await this.compact({ signal, auto: true });
|
|
906
|
+
await this.compact({ signal, auto: true, overflow });
|
|
853
907
|
return null;
|
|
854
908
|
} catch (err) {
|
|
855
909
|
if (isAbort(err) || signal?.aborted) return this.handleInterrupt();
|
|
@@ -891,13 +945,16 @@ export class Agent {
|
|
|
891
945
|
|
|
892
946
|
async callModel(signal) {
|
|
893
947
|
await this.lightenImages();
|
|
894
|
-
const system = this.currentSystem();
|
|
895
948
|
// The system prompt is kept with the conversation, so that a resumed one can continue behind the same
|
|
896
949
|
// prompt (and so with the cache it has) instead of a freshly built one.
|
|
897
|
-
|
|
898
|
-
this.recordedSystem
|
|
899
|
-
|
|
900
|
-
|
|
950
|
+
const noteSystem = (text) => {
|
|
951
|
+
if (!this.isSubagent && text !== this.recordedSystem) {
|
|
952
|
+
this.recordedSystem = text;
|
|
953
|
+
this.io.systemPrompt?.(text, this);
|
|
954
|
+
}
|
|
955
|
+
return text;
|
|
956
|
+
};
|
|
957
|
+
const system = noteSystem(this.currentSystem());
|
|
901
958
|
// The repair goes into the request only, done again (the same way) for every request: storing it in place of
|
|
902
959
|
// the conversation merged and inserted messages, which moved the messages the checkpoints point at, so a
|
|
903
960
|
// /rewind after a restart cut the conversation in the wrong place.
|
|
@@ -907,7 +964,7 @@ export class Agent {
|
|
|
907
964
|
for (const id of fresh) this.recoveredToolIds.add(id);
|
|
908
965
|
this.io.notice?.('Recovered an unfinished tool call in the conversation; continuing with an interrupted result.', 'warn');
|
|
909
966
|
}
|
|
910
|
-
|
|
967
|
+
let request = {
|
|
911
968
|
model: this.model,
|
|
912
969
|
system,
|
|
913
970
|
messages: repaired.messages,
|
|
@@ -915,12 +972,33 @@ export class Agent {
|
|
|
915
972
|
cacheBucket: this.isSubagent ? 'other' : 'main',
|
|
916
973
|
...(this.effort ? { effort: this.effort } : {}),
|
|
917
974
|
};
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
975
|
+
// While the request is paused for a rate limit, the user may choose another model to go on with (/model, see
|
|
976
|
+
// wakePause): the main agent's turns only, which are what the user waits for.
|
|
977
|
+
const pauseControl = this.isSubagent ? null : {};
|
|
978
|
+
this.pauseControl = pauseControl;
|
|
979
|
+
let res;
|
|
980
|
+
try {
|
|
981
|
+
res = await this.streamAgentRequest(request, {
|
|
982
|
+
signal,
|
|
983
|
+
kind: 'turn',
|
|
984
|
+
cacheBucket: request.cacheBucket,
|
|
985
|
+
onEvent: (ev) => this.io.streamEvent?.(ev, this),
|
|
986
|
+
pauseControl,
|
|
987
|
+
// A pause for a rate limit lasts hours, and the prompt cache one: the request repeated after it wrote the
|
|
988
|
+
// whole conversation again, as it stood (6 times in 11 days, 310k to 890k tokens each, out of the limit
|
|
989
|
+
// that had just been reset). What a return after such a pause clears is cleared here too, before it is
|
|
990
|
+
// repeated. And the model is the one of now: the user may have changed it to get on.
|
|
991
|
+
afterPause: () => {
|
|
992
|
+
const model = this.model;
|
|
993
|
+
const cleared = this.clearAfterIdle(Date.now(), { pause: true });
|
|
994
|
+
if (!cleared && model.id === request.model.id) return null;
|
|
995
|
+
request = { ...request, model, system: noteSystem(this.currentSystem()), messages: repairToolResults(normalizeMessages(this.messages)).messages };
|
|
996
|
+
return request;
|
|
997
|
+
},
|
|
998
|
+
});
|
|
999
|
+
} finally {
|
|
1000
|
+
if (this.pauseControl === pauseControl) this.pauseControl = null;
|
|
1001
|
+
}
|
|
924
1002
|
this.lastContextTokens = contextTokens(res.usage);
|
|
925
1003
|
this.usageModel = request.model.id;
|
|
926
1004
|
this.tokensSinceUsage = 0;
|
|
@@ -961,14 +1039,28 @@ export class Agent {
|
|
|
961
1039
|
else batches.push({ parallel: safe, items: [tu] });
|
|
962
1040
|
}
|
|
963
1041
|
this.io.toolBatchStart?.(toolUses, this);
|
|
1042
|
+
// The model is told that the calls of one response run in the order given, so that an edit and the command that
|
|
1043
|
+
// builds or tests it can come together (it wrote scripts through Bash to get both into one call, and those
|
|
1044
|
+
// edits are not checkpointed). A command after an edit that failed would run on the file as it was: left out.
|
|
1045
|
+
let failedEdit = null;
|
|
964
1046
|
for (const batch of batches) {
|
|
965
1047
|
if (stop || interrupted) break;
|
|
966
1048
|
const run = async (tu) => {
|
|
967
1049
|
try {
|
|
1050
|
+
const tool = map.get(tu.name);
|
|
1051
|
+
if (failedEdit && tool && !tool.readOnly && !tool.editsFiles) {
|
|
1052
|
+
const message = `Not run: the ${failedEdit} call before it in this response failed, and this call may depend on that edit. Make the edit, then send this call again.`;
|
|
1053
|
+
const skipped = this.trace?.toolStart({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, name: tu.name, input: tu.input, parallel: false, toolUseId: tu.id });
|
|
1054
|
+
this.trace?.toolEnd(skipped, { skipped: true, error: true, error_type: 'skipped' });
|
|
1055
|
+
this.io.toolRejected?.(tu, tool, message, this);
|
|
1056
|
+
results.set(tu, { type: 'tool_result', tool_use_id: tu.id, is_error: true, content: message });
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
968
1059
|
const r = await this.runOne(tu, signal, map, { parallel: batch.parallel });
|
|
969
1060
|
// Key by the tool-use object, not its provider id. A malformed provider response
|
|
970
1061
|
// can repeat an id; one duplicate must not overwrite the other result.
|
|
971
1062
|
results.set(tu, r.block);
|
|
1063
|
+
if (r.block.is_error && tool?.editsFiles) failedEdit ||= tu.name;
|
|
972
1064
|
if (r.stop) stop = true;
|
|
973
1065
|
} catch (err) {
|
|
974
1066
|
if (isAbort(err) || signal?.aborted) {
|
|
@@ -1141,7 +1233,8 @@ export class Agent {
|
|
|
1141
1233
|
}
|
|
1142
1234
|
}
|
|
1143
1235
|
|
|
1144
|
-
|
|
1236
|
+
// `overflow`: the error of the turn's request when the compaction is made because that was too long.
|
|
1237
|
+
async summaryRequest(messages, { signal, onEvent, compactionId = null, overflow = null }) {
|
|
1145
1238
|
const cacheMessages = !this.cacheExpired();
|
|
1146
1239
|
const call = (request, options = {}) => {
|
|
1147
1240
|
const useMessages = request.cacheMessages === undefined ? cacheMessages : request.cacheMessages;
|
|
@@ -1155,29 +1248,48 @@ export class Agent {
|
|
|
1155
1248
|
...options,
|
|
1156
1249
|
});
|
|
1157
1250
|
};
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
const plain = (msgs) => call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false, messages: msgs }, { cacheOverride: { caching: false } });
|
|
1165
|
-
let tooLong;
|
|
1166
|
-
try {
|
|
1167
|
-
return await plain(messages);
|
|
1168
|
-
} catch (err) {
|
|
1251
|
+
// A refusal for length says how long the request was and what fits (Anthropic's does). With our own estimate of
|
|
1252
|
+
// the same messages that tells of a smaller request whether it can fit, without sending it: each refusal of a
|
|
1253
|
+
// conversation at the window took 5 to 25 seconds to upload (5 in a row, 2026-11-06).
|
|
1254
|
+
let tooLong = null;
|
|
1255
|
+
let over = null; // {tokens, limit, estimate} of the last request refused for its length
|
|
1256
|
+
const refused = (err, msgs) => {
|
|
1169
1257
|
if (isAbort(err) || signal?.aborted || !err.promptTooLong) throw err;
|
|
1170
1258
|
tooLong = err;
|
|
1259
|
+
if (err.promptTokens > 0 && err.promptLimit > 0) over = { tokens: err.promptTokens, limit: err.promptLimit, estimate: Math.max(1, estimateTokens(msgs)) };
|
|
1260
|
+
};
|
|
1261
|
+
const cannotFit = (msgs) => over != null && estimateTokens(msgs) * (over.tokens / over.estimate) > over.limit * 1.05;
|
|
1262
|
+
if (overflow?.promptTooLong) refused(overflow, messages); // the same request with the instruction at its end is too long as well
|
|
1263
|
+
else {
|
|
1264
|
+
try {
|
|
1265
|
+
const res = await call({ system: this.currentSystem() });
|
|
1266
|
+
if (Agent.summaryOf(res)) return res;
|
|
1267
|
+
} catch (err) {
|
|
1268
|
+
refused(err, messages);
|
|
1269
|
+
}
|
|
1171
1270
|
}
|
|
1172
|
-
//
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
let smaller = clearOldToolResults(messages, { keep: 3, atLeast: 0, cwd: this.cwd })?.messages || messages;
|
|
1176
|
-
for (let i = 0; i < 4 && smaller; i++) {
|
|
1271
|
+
// null: it does not fit
|
|
1272
|
+
const plain = async (msgs) => {
|
|
1273
|
+
if (cannotFit(msgs)) return null;
|
|
1177
1274
|
try {
|
|
1178
|
-
return await
|
|
1275
|
+
return await call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false, messages: msgs }, { cacheOverride: { caching: false } });
|
|
1179
1276
|
} catch (err) {
|
|
1180
|
-
|
|
1277
|
+
refused(err, msgs);
|
|
1278
|
+
return null;
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
let res = await plain(messages);
|
|
1282
|
+
if (res) return res;
|
|
1283
|
+
// The history alone is over the window (one turn of very large results can do it, or a model that counts the
|
|
1284
|
+
// conversation in more tokens than the one before it): the summary is made from less, old tool results and
|
|
1285
|
+
// inputs first (as idle clearing does), then the oldest turns. Without this every later request failed too,
|
|
1286
|
+
// and only /clear or /rewind got the conversation going again.
|
|
1287
|
+
let smaller = clearOldToolResults(messages, { keep: 3, atLeast: 0, cwd: this.cwd })?.messages || messages;
|
|
1288
|
+
for (let i = 0; i < 4 && smaller; i++) {
|
|
1289
|
+
res = await plain(smaller);
|
|
1290
|
+
if (res) {
|
|
1291
|
+
if (i > 0) this.io.notice?.(`The conversation was too long for the model to summarize whole (${tooLong.promptTokens ? `${Math.round(tooLong.promptTokens / 1000)}k tokens, ${Math.round(tooLong.promptLimit / 1000)}k fit` : 'over its window'}): the summary was made without the oldest ${messages.length - smaller.length + 1} of its ${messages.length} messages. Your own messages are kept as they were.`, 'warn');
|
|
1292
|
+
return res;
|
|
1181
1293
|
}
|
|
1182
1294
|
smaller = withoutOldestHalf(smaller);
|
|
1183
1295
|
}
|
|
@@ -1229,7 +1341,7 @@ export class Agent {
|
|
|
1229
1341
|
}
|
|
1230
1342
|
|
|
1231
1343
|
// Summarise the conversation and replace it with the summary.
|
|
1232
|
-
async compact({ signal, auto = false, instructions = '' } = {}) {
|
|
1344
|
+
async compact({ signal, auto = false, instructions = '', overflow = null } = {}) {
|
|
1233
1345
|
if (this.messages.length === 0) return null;
|
|
1234
1346
|
const compactionId = `compact_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1235
1347
|
const compactionStartedAt = Date.now();
|
|
@@ -1241,7 +1353,7 @@ export class Agent {
|
|
|
1241
1353
|
const messages = repairToolResults(normalizeMessages([...this.messages, { role: 'user', content: [{ type: 'text', text: compactPrompt(instructions) }] }])).messages;
|
|
1242
1354
|
let res;
|
|
1243
1355
|
try {
|
|
1244
|
-
res = await this.requestSummary(messages, { signal, compactionId, onEvent: (ev) => this.io.compactProgress?.(ev, this) });
|
|
1356
|
+
res = await this.requestSummary(messages, { signal, compactionId, overflow, onEvent: (ev) => this.io.compactProgress?.(ev, this) });
|
|
1245
1357
|
} catch (err) {
|
|
1246
1358
|
this.trace?.compact({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, auto, before_context_tokens: beforeContextTokens, duration_ms: Date.now() - compactionStartedAt, error: err });
|
|
1247
1359
|
this.io.compactEnd?.(null, this, err);
|
package/src/api.js
CHANGED
|
@@ -207,11 +207,14 @@ export function buildParams(config, { model, system, messages, tools, maxTokens,
|
|
|
207
207
|
}
|
|
208
208
|
|
|
209
209
|
export class APIError extends Error {
|
|
210
|
-
constructor(message, { status, retryable, promptTooLong, retryAfterMs = null, rateLimit = null, overloaded = false } = {}) {
|
|
210
|
+
constructor(message, { status, retryable, promptTooLong, promptTokens = 0, promptLimit = 0, retryAfterMs = null, rateLimit = null, overloaded = false } = {}) {
|
|
211
211
|
super(message);
|
|
212
212
|
this.status = status;
|
|
213
213
|
this.retryable = retryable;
|
|
214
214
|
this.promptTooLong = promptTooLong;
|
|
215
|
+
// Anthropic says how long it was and what fits ("prompt is too long: 1003873 tokens > 1000000 maximum"); 0: not said
|
|
216
|
+
this.promptTokens = promptTokens;
|
|
217
|
+
this.promptLimit = promptLimit;
|
|
215
218
|
this.overloaded = overloaded; // 529 / overloaded_error: waited out with its own backoff (see planRetry)
|
|
216
219
|
this.retryAfterMs = retryAfterMs; // what the server's Retry-After header asked for
|
|
217
220
|
this.rateLimit = rateLimit; // what the rate limit headers say (see ratelimit.js)
|
|
@@ -232,7 +235,8 @@ function describeError(err, config) {
|
|
|
232
235
|
const retryable = !promptTooLong && (!status || status === 408 || status === 409 || status === 429 || status >= 500);
|
|
233
236
|
const header = typeof err?.headers?.get === 'function' ? err.headers.get('retry-after') : err?.headers?.['retry-after'];
|
|
234
237
|
const overloaded = status === 529 || (err?.error?.error?.type || err?.error?.type) === 'overloaded_error';
|
|
235
|
-
|
|
238
|
+
const sizes = promptTooLong ? /(\d+) tokens > (\d+) maximum/.exec(msg) : null;
|
|
239
|
+
return new APIError(msg, { status, retryable, promptTooLong, promptTokens: Number(sizes?.[1]) || 0, promptLimit: Number(sizes?.[2]) || 0, retryAfterMs: parseRetryAfter(header), rateLimit: parseRateLimit(err?.headers, timing.now()), overloaded });
|
|
236
240
|
}
|
|
237
241
|
|
|
238
242
|
// Our own aborts are named AbortError and the SDK's is an APIUserAbortError. The message test only
|
|
@@ -261,9 +265,14 @@ function charge(config, requested, served, usage) {
|
|
|
261
265
|
// {type:'rate_limit_resume', waitedMs} the repeated request was accepted: the pause is over
|
|
262
266
|
// {type:'reset'} partial output from a failed attempt must be discarded
|
|
263
267
|
// `waitForRateLimit: false` reports a rate limit as an error instead of waiting for it (side queries
|
|
264
|
-
// where nobody wants to sit through a pause).
|
|
268
|
+
// where nobody wants to sit through a pause). `afterPause({woken})` is called when a pause for a rate limit (or an
|
|
269
|
+
// overloaded API) is over, before the request is repeated: it may return the request to go on with instead (the
|
|
270
|
+
// conversation made smaller once its prompt cache has run out, or another model), or null for the same one.
|
|
271
|
+
// `pauseControl`: an object that gets a wake() function while such a pause lasts; calling it ends the pause at
|
|
272
|
+
// once (the user chose another model to go on with), and afterPause is told so.
|
|
273
|
+
// Returns {message, usage, stopReason, model, cost, cache}.
|
|
265
274
|
// What each request costs (an interrupted one too) goes to config.onCost, the conversation's running total.
|
|
266
|
-
export async function streamMessage(config, request, { signal, onEvent = () => {}, waitForRateLimit = true } = {}) {
|
|
275
|
+
export async function streamMessage(config, request, { signal, onEvent = () => {}, waitForRateLimit = true, afterPause = null, pauseControl = null } = {}) {
|
|
267
276
|
if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
|
|
268
277
|
// Load gateway model metadata before the synchronous parameter builder; the cache is keyed by gateway and key,
|
|
269
278
|
// so changing accounts or gateway URLs cannot leak a model's effort levels into another context. A gateway that
|
|
@@ -271,7 +280,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
271
280
|
await loadGatewayModels(config, signal);
|
|
272
281
|
if (signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError', partial: [] });
|
|
273
282
|
const client = await getClient(config);
|
|
274
|
-
|
|
283
|
+
let params = buildParams(config, request);
|
|
275
284
|
// The gateway keeps a conversation on the upstream account that served it, where its prompt cache is; the
|
|
276
285
|
// session id names the conversation, in the header Claude Code sends it in.
|
|
277
286
|
const options = { signal, ...(config.sessionId ? { headers: { 'X-Claude-Code-Session-Id': config.sessionId } } : {}) };
|
|
@@ -279,6 +288,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
279
288
|
const refused = new Set(); // what the endpoint refused for this request: remembered once a request got through
|
|
280
289
|
const retryState = { attempt: 0, rateLimitHits: 0, waitedMs: 0, overloaded: 0, overloadedWaitMs: 0 };
|
|
281
290
|
let paused = null; // the plan of the pause in progress (see planRetry)
|
|
291
|
+
let woken = false; // the pause was ended by pauseControl.wake()
|
|
282
292
|
for (;;) {
|
|
283
293
|
let emitted = false;
|
|
284
294
|
const startedAt = Date.now(); // the cache TTL counts from the start of the request, not from the end of the reply
|
|
@@ -291,7 +301,7 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
291
301
|
if (paused) {
|
|
292
302
|
const overloaded = paused.overloaded;
|
|
293
303
|
paused = null;
|
|
294
|
-
onEvent({ type: 'rate_limit_resume', waitedMs: overloaded ? retryState.overloadedWaitMs : retryState.waitedMs, ...(overloaded ? { overloaded } : {}) });
|
|
304
|
+
onEvent({ type: 'rate_limit_resume', waitedMs: overloaded ? retryState.overloadedWaitMs : retryState.waitedMs, ...(overloaded ? { overloaded } : {}), ...(woken ? { woken } : {}) });
|
|
295
305
|
}
|
|
296
306
|
let stopReason = null;
|
|
297
307
|
let stopped = false;
|
|
@@ -431,8 +441,15 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
431
441
|
? { overloaded: true, waitedMs: retryState.overloadedWaitMs, maxWaitMs: config.overloadedMaxWait }
|
|
432
442
|
: { waitedMs: retryState.waitedMs, maxWaitMs: config.rateLimitMaxWait }),
|
|
433
443
|
});
|
|
434
|
-
await
|
|
444
|
+
woken = await sleepThroughPause(plan.resumeAt, signal, pauseControl);
|
|
445
|
+
if (woken) { // what was not waited does not count against the time the session may wait
|
|
446
|
+
const left = Math.max(0, plan.resumeAt - timing.now());
|
|
447
|
+
if (plan.overloaded) retryState.overloadedWaitMs = Math.max(0, retryState.overloadedWaitMs - left);
|
|
448
|
+
else retryState.waitedMs = Math.max(0, retryState.waitedMs - left);
|
|
449
|
+
}
|
|
435
450
|
retryState.attempt = 0; // the pause is a fresh start: quick retries made before it do not count after it
|
|
451
|
+
const next = afterPause?.({ woken });
|
|
452
|
+
if (next) params = buildParams(config, next);
|
|
436
453
|
} else {
|
|
437
454
|
onEvent({ type: 'retry', attempt: plan.attempt, error: err, delayMs: plan.delayMs, maxRetries: plan.maxRetries });
|
|
438
455
|
await sleepUntil(plan.resumeAt, signal);
|
|
@@ -441,6 +458,26 @@ export async function streamMessage(config, request, { signal, onEvent = () => {
|
|
|
441
458
|
}
|
|
442
459
|
}
|
|
443
460
|
|
|
461
|
+
// Sleep until `deadline`, or until control.wake() is called (true then). The user's interrupt still throws.
|
|
462
|
+
async function sleepThroughPause(deadline, signal, control) {
|
|
463
|
+
if (!control) { await sleepUntil(deadline, signal); return false; }
|
|
464
|
+
const ac = new AbortController();
|
|
465
|
+
const onAbort = () => ac.abort();
|
|
466
|
+
if (signal?.aborted) ac.abort();
|
|
467
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
468
|
+
let woken = false;
|
|
469
|
+
control.wake = () => { woken = true; ac.abort(); };
|
|
470
|
+
try {
|
|
471
|
+
await sleepUntil(deadline, ac.signal);
|
|
472
|
+
} catch (err) {
|
|
473
|
+
if (!woken || signal?.aborted) throw err;
|
|
474
|
+
} finally {
|
|
475
|
+
control.wake = null;
|
|
476
|
+
signal?.removeEventListener('abort', onAbort);
|
|
477
|
+
}
|
|
478
|
+
return woken;
|
|
479
|
+
}
|
|
480
|
+
|
|
444
481
|
// One-shot, non-streaming helper for small side queries (summaries, titles, web page extraction).
|
|
445
482
|
// Nothing here can tell the user that it is paused, so a rate limit is reported as an error by default
|
|
446
483
|
// instead of being waited for out of sight; waitForRateLimit: true is for a caller that accepts that.
|
package/src/commands.js
CHANGED
|
@@ -396,12 +396,16 @@ export function buildCommands(app) {
|
|
|
396
396
|
const forget = choice === '__default__' || choice === 'default';
|
|
397
397
|
const next = cfg.resolveModel(forget ? cfg.configuredModelSpec : choice).id;
|
|
398
398
|
const changed = next !== cfg.model.id;
|
|
399
|
-
|
|
399
|
+
// (Not asked at a pause for a rate limit: the cache runs out while waiting for the limit as well.)
|
|
400
|
+
if (changed && !app.agent.pausedForLimit && !(await confirmCacheLoss('Switching the model', { model: next }))) { out(c.dim('The model was not changed.')); return; }
|
|
400
401
|
cfg.modelOverride = forget ? null : choice;
|
|
401
402
|
if (changed) app.runtime.invalidateSystemPrompt(); // the prompt names the model; the new model starts a cache of its own anyway
|
|
402
403
|
const kept = keep(cfg, { model: cfg.modelOverride }, forget);
|
|
403
404
|
await loadGatewayModels(cfg); // the window shown may come from the gateway's model list (see Config.resolveModel)
|
|
404
|
-
|
|
405
|
+
// A turn paused for the other model's rate limit goes on with this one now (the one case in which /model runs
|
|
406
|
+
// during a turn, see App.modelSwitchAtPause).
|
|
407
|
+
const resumed = changed && app.agent.wakePause();
|
|
408
|
+
out(`Model set to ${c.bold(cfg.model.label)} ${c.dim(`(${formatTokens(cfg.model.contextWindow)} context)`)}${kept}${resumed ? c.dim(' · the paused request goes on with it now') : changed ? c.dim(' · restored conversation remains in context for the next request') : ''}`);
|
|
405
409
|
},
|
|
406
410
|
});
|
|
407
411
|
|
|
@@ -550,7 +554,7 @@ export function buildCommands(app) {
|
|
|
550
554
|
: savedPrompt?.text != null ? `${savedPrompt.name} (saved)` : savedPrompt?.error ? `${savedPrompt.name} (missing; using built-in)` : 'built-in default'),
|
|
551
555
|
row('Max output', formatTokens(cfg.maxOutputTokens)),
|
|
552
556
|
row('Prompt cache', cfg.promptCachingDisabled() ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.model.id).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.model.id).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
|
|
553
|
-
row('Auto-compact', `at ${formatTokens(cfg.compactWindow())} tokens (
|
|
557
|
+
row('Auto-compact', `at ${formatTokens(cfg.compactWindow())} tokens (the window, less room for the summary)`),
|
|
554
558
|
row('Access', 'full (no permission prompts)'),
|
|
555
559
|
row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
|
|
556
560
|
row('Shell', `${app.runtime.shell.name} ${c.dim(app.runtime.shell.path)}`),
|
|
@@ -704,12 +708,12 @@ export function buildCommands(app) {
|
|
|
704
708
|
add({
|
|
705
709
|
name: 'verify',
|
|
706
710
|
argHint: '[command|off]',
|
|
707
|
-
description: 'Run a command (e.g. npm test) after turns that edit files;
|
|
711
|
+
description: 'Run a command (e.g. npm test) after turns that edit files; failures go back to the agent (off unless set)',
|
|
708
712
|
run(args) {
|
|
709
713
|
const cfg = app.runtime.config;
|
|
710
714
|
if (args.trim()) cfg.verifyOverride = args.trim();
|
|
711
715
|
out(cfg.verifyCommand
|
|
712
|
-
? `Verify command: ${c.bold(cfg.verifyCommand)} ${c.dim(`(
|
|
716
|
+
? `Verify command: ${c.bold(cfg.verifyCommand)} ${c.dim(`(up to ${cfg.verifyMaxRounds} fix rounds; /verify off to disable)`)}`
|
|
713
717
|
: c.dim('Verification is off. Turn it on with /verify <command>, --verify <command> or CLAUDE_PRO_VERIFY_COMMAND.'));
|
|
714
718
|
},
|
|
715
719
|
});
|
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
|
|
@@ -279,9 +278,14 @@ export class Config {
|
|
|
279
278
|
get overloadedRetryMaxDelay() { return 32_000; }
|
|
280
279
|
get overloadedMaxWait() { return this.rateLimitMaxWait; }
|
|
281
280
|
|
|
282
|
-
//
|
|
281
|
+
// At the model's input window (only sub-agent definitions may ask for a smaller one), less the room the compaction
|
|
282
|
+
// itself takes: its request is the conversation with the instruction at its end, and its reply (the summary and
|
|
283
|
+
// the thinking before it) counts against the window too. With no room left, the summary request of a
|
|
284
|
+
// conversation at the window was refused as too long and the conversation sent again without its cache (895k
|
|
285
|
+
// tokens of plain input on Opus, 2026-11-02; a request that fits reads them from the cache at a twentieth).
|
|
283
286
|
compactWindow(model = this.model, own = 0) {
|
|
284
|
-
|
|
287
|
+
const window = own > 0 ? Math.min(own, model.contextWindow) : model.contextWindow;
|
|
288
|
+
return window - Math.min(40_000, Math.round(window * 0.05));
|
|
285
289
|
}
|
|
286
290
|
|
|
287
291
|
get bashDefaultTimeout() { return 600_000; }
|
|
@@ -300,18 +304,14 @@ export class Config {
|
|
|
300
304
|
// How deep sub-agents may nest: the main agent is depth 0; an agent below this depth gets the Task tool.
|
|
301
305
|
get maxSubagentDepth() { return 2; }
|
|
302
306
|
|
|
303
|
-
// Verification after edits: session
|
|
304
|
-
//
|
|
307
|
+
// Verification after edits, only when asked for: the session's own (/verify, --verify) wins over the setting.
|
|
308
|
+
// With neither there is none. (Until 2026-11-11 the project's test or check script was found and run by itself:
|
|
309
|
+
// a step after every edit that nobody had asked for, minutes long where the tests are; how to verify is the
|
|
310
|
+
// model's choice, in proportion to the change.)
|
|
305
311
|
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
312
|
const v = this.verifyOverride ?? this.env.CLAUDE_PRO_VERIFY_COMMAND ?? '';
|
|
309
313
|
return v.trim() && v.trim() !== 'off' ? v.trim() : null;
|
|
310
314
|
}
|
|
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
315
|
// How many times a failing verify command is sent back before giving up.
|
|
316
316
|
get verifyMaxRounds() { return 3; }
|
|
317
317
|
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/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/repl.js
CHANGED
|
@@ -21,7 +21,7 @@ import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
|
|
|
21
21
|
import { gatewayLogin, loadGatewayModels, normalizeGatewayUrl, formatUsd } from '../gateway.js';
|
|
22
22
|
import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
|
|
23
23
|
import { buildCommands, modelChoices, effortChoices } from '../commands.js';
|
|
24
|
-
import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
|
|
24
|
+
import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, reloadTiming, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
|
|
25
25
|
import { resolvePath, displayPath } from '../utils/paths.js';
|
|
26
26
|
import { listDirectory, recentDirectories } from '../utils/dirs.js';
|
|
27
27
|
import { ripgrepPath } from '../utils/shell.js';
|
|
@@ -142,18 +142,38 @@ function appendHistory(cwd, text, parts = null) {
|
|
|
142
142
|
} catch { /* ignore */ }
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
// The files of the working directory, for the completion after an `@`. Listed when an `@` is first typed, not at
|
|
146
|
+
// the start, and never more than MAX_FILES of them: the listing is stopped there. (It ran at every start and
|
|
147
|
+
// restart and went through the whole directory before keeping the first 50,000: in a home directory of 1.3
|
|
148
|
+
// million files that was 10 seconds of ripgrep on every core and 45 MB, for every session open there, each time
|
|
149
|
+
// the program's source changed.) `onLoaded` is called when a listing is in, so that the completion is drawn again.
|
|
150
|
+
const MAX_FILES = 50_000;
|
|
145
151
|
class FileIndex {
|
|
146
|
-
constructor(cwd, getConfig = () => null
|
|
152
|
+
constructor(cwd, getConfig = () => null, onLoaded = () => {}) {
|
|
153
|
+
Object.assign(this, { cwd, getConfig, onLoaded, files: [], at: 0, took: 0, loading: false });
|
|
154
|
+
}
|
|
147
155
|
refresh() {
|
|
148
|
-
|
|
156
|
+
// listed again after 30 seconds, or later where the listing itself takes long
|
|
157
|
+
if (this.loading || Date.now() - this.at < Math.max(30_000, this.took * 30)) return;
|
|
149
158
|
this.loading = true;
|
|
150
|
-
const
|
|
159
|
+
const started = Date.now();
|
|
160
|
+
const done = (list) => {
|
|
161
|
+
Object.assign(this, { files: list.slice(0, MAX_FILES), at: Date.now(), took: Date.now() - started, loading: false });
|
|
162
|
+
this.onLoaded();
|
|
163
|
+
};
|
|
151
164
|
const rg = ripgrepPath(this.getConfig());
|
|
152
165
|
if (rg) {
|
|
153
166
|
const child = spawn(rg, ['--files', '--hidden', '--glob', '!.git'], { cwd: this.cwd, windowsHide: true });
|
|
154
167
|
let out = '';
|
|
168
|
+
let lines = 0;
|
|
155
169
|
child.stdout.setEncoding('utf8'); // a Chinese file name can be split between two chunks
|
|
156
|
-
child.stdout.on('data', (d) => {
|
|
170
|
+
child.stdout.on('data', (d) => {
|
|
171
|
+
if (lines >= MAX_FILES) return;
|
|
172
|
+
out += d;
|
|
173
|
+
for (let i = d.indexOf('\n'); i !== -1; i = d.indexOf('\n', i + 1)) lines++;
|
|
174
|
+
if (lines >= MAX_FILES) child.kill();
|
|
175
|
+
});
|
|
176
|
+
// (stopped in the middle of a name: the list is cut to MAX_FILES whole ones in done)
|
|
157
177
|
child.on('close', () => done(out.split(/\r?\n/).filter(Boolean).map((f) => f.replace(/\\/g, '/'))));
|
|
158
178
|
child.on('error', () => done([]));
|
|
159
179
|
} else {
|
|
@@ -162,7 +182,7 @@ class FileIndex {
|
|
|
162
182
|
try {
|
|
163
183
|
for await (const f of fs.promises.glob('**/*', { cwd: this.cwd, exclude: (p) => /(^|[\\/])(node_modules|\.git)$/.test(p) })) {
|
|
164
184
|
list.push(f.replace(/\\/g, '/'));
|
|
165
|
-
if (list.length >
|
|
185
|
+
if (list.length > MAX_FILES) break;
|
|
166
186
|
}
|
|
167
187
|
} catch { /* ignore */ }
|
|
168
188
|
done(list);
|
|
@@ -248,6 +268,8 @@ export class App {
|
|
|
248
268
|
this.restarts = []; // when this session was restarted lately (carried over by each restart)
|
|
249
269
|
this.restartRequest = null; // {reason, then, continueTurn}: restart as soon as nothing is running
|
|
250
270
|
this.sourceChanged = null; // the program's own source changed since it was last checked
|
|
271
|
+
this.sourceChangedInTurn = false; // ...while a turn of this session ran: its own work, most likely
|
|
272
|
+
this.sourceQuietAt = 0; // a change made elsewhere is loaded once the source has been left alone until then
|
|
251
273
|
this.reloading = false;
|
|
252
274
|
this.skipAutoReload = false;
|
|
253
275
|
this.peers = null; // this session as seen by the other sessions on the machine (see peers.js)
|
|
@@ -267,7 +289,7 @@ export class App {
|
|
|
267
289
|
this.remotePeersLoading = null;
|
|
268
290
|
this.remotePeersTimer = null;
|
|
269
291
|
this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
|
|
270
|
-
this.fileIndex = new FileIndex(cwd, () => this.runtime?.config);
|
|
292
|
+
this.fileIndex = new FileIndex(cwd, () => this.runtime?.config, () => { this.editor?.refreshSuggestions(); this.screen?.schedule(); });
|
|
271
293
|
this.store = new SessionStore(cwd);
|
|
272
294
|
SessionStore.onError = (e, store) => this.notice(`Could not save the conversation to ${store.file} (${e.code || e.message}): it is written again whole before a restart, but /resume may miss what was not saved.`, 'warn');
|
|
273
295
|
// What the terminal prints goes to the remote page too, except what it is told about as events.
|
|
@@ -365,7 +387,6 @@ export class App {
|
|
|
365
387
|
else if (!gatewayLogin(this.config.gatewayUrl)) {
|
|
366
388
|
Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
|
|
367
389
|
}
|
|
368
|
-
this.fileIndex.refresh();
|
|
369
390
|
this.startSourceWatch();
|
|
370
391
|
if (!this.driven) {
|
|
371
392
|
// Updates are deliberately manual: /update checks npm and installs the selected release.
|
|
@@ -453,6 +474,7 @@ export class App {
|
|
|
453
474
|
this.exiting = true;
|
|
454
475
|
this.controller?.abort();
|
|
455
476
|
clearInterval(this.spinnerTimer);
|
|
477
|
+
clearTimeout(this.reloadTimer);
|
|
456
478
|
this.sourceWatch?.close();
|
|
457
479
|
shutdownBackgroundShells();
|
|
458
480
|
shutdownInterpreters();
|
|
@@ -881,7 +903,7 @@ export class App {
|
|
|
881
903
|
// the same pattern and message; this holds when it does not (another gateway, or one that misses them).
|
|
882
904
|
if (TERMINAL_ONLY.test(value)) throw new Error('结束、重启会话和更新 claude-pro 只能在终端里操作');
|
|
883
905
|
if (this.exiting) throw new Error('The session is ending.');
|
|
884
|
-
if (this.isTurnRunning() && value.trim().startsWith('/')) throw new Error('Commands wait until the current task is done (or stopped).');
|
|
906
|
+
if (this.isTurnRunning() && value.trim().startsWith('/') && !this.modelSwitchAtPause(value.trim())) throw new Error('Commands wait until the current task is done (or stopped).');
|
|
885
907
|
if (this.dialogs.length && !this.isTurnRunning()) throw new Error('A question is open: answer it first.');
|
|
886
908
|
const queued = this.isTurnRunning();
|
|
887
909
|
this.onSubmit(value, value, pictures);
|
|
@@ -1128,12 +1150,18 @@ export class App {
|
|
|
1128
1150
|
});
|
|
1129
1151
|
}
|
|
1130
1152
|
|
|
1131
|
-
// Follow the program's own source:
|
|
1132
|
-
// a
|
|
1153
|
+
// Follow the program's own source: a change to it is loaded by a restart, if the new code starts. A change made
|
|
1154
|
+
// while a turn of this session runs is its own work, and is loaded when the turn is over. One that arrives while
|
|
1155
|
+
// the session is idle was made elsewhere (another session working on the program, an editor), one step of a
|
|
1156
|
+
// change that is not finished: it is loaded once the source has been left alone for a few minutes. (Loaded at
|
|
1157
|
+
// once, every edit of one session made each of the other open sessions check and restart, into a half-made
|
|
1158
|
+
// change: 8 of them, a dozen times in a day's work.)
|
|
1133
1159
|
startSourceWatch() {
|
|
1134
1160
|
if (!canRestart()) return;
|
|
1135
1161
|
this.sourceWatch = watchSource(INSTALL_DIR, (file) => {
|
|
1136
1162
|
this.sourceChanged = file || true;
|
|
1163
|
+
if (this.isTurnRunning()) this.sourceChangedInTurn = true;
|
|
1164
|
+
else this.sourceQuietAt = Date.now() + reloadTiming.quietMs + Math.random() * reloadTiming.spreadMs; // (not all sessions at the same moment)
|
|
1137
1165
|
// another window (or npm) installed a new version: say so, and load it once this session is idle. In a
|
|
1138
1166
|
// source checkout a newer version in package.json is a release being made, not an install.
|
|
1139
1167
|
const disk = installedVersion();
|
|
@@ -1150,8 +1178,18 @@ export class App {
|
|
|
1150
1178
|
if (!this.sourceChanged || this.updating || this.reloading || this.isTurnRunning() || this.exiting || this.restartRequest || this.dialogs.length || this.queue.length) return;
|
|
1151
1179
|
if (this.skipAutoReload) { this.skipAutoReload = false; return; } // the user just interrupted: not now
|
|
1152
1180
|
if (this.restartBlockers().length) return; // looked at again whenever the program is next idle
|
|
1181
|
+
clearTimeout(this.reloadTimer);
|
|
1182
|
+
const wait = this.updateRestart || this.sourceChangedInTurn ? 0 : this.sourceQuietAt - Date.now(); // (an installed version is complete)
|
|
1183
|
+
if (wait > 0) {
|
|
1184
|
+
this.reloadTimer = setTimeout(() => this.maybeAutoReload(), wait + 50);
|
|
1185
|
+
this.reloadTimer.unref?.();
|
|
1186
|
+
this.screen.schedule();
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1153
1189
|
const changed = this.sourceChanged;
|
|
1190
|
+
const inTurn = this.sourceChangedInTurn;
|
|
1154
1191
|
this.sourceChanged = null;
|
|
1192
|
+
this.sourceChangedInTurn = false;
|
|
1155
1193
|
this.reloading = true;
|
|
1156
1194
|
this.flash(this.updateRestart ? `Updated to ${this.updateRestart}: checking it starts, then restarting…` : 'Source changed: checking the new code…');
|
|
1157
1195
|
let check;
|
|
@@ -1161,7 +1199,7 @@ export class App {
|
|
|
1161
1199
|
this.notice(`The program's source changed but the new code does not start, so it was not restarted:\n${check.output.split('\n').slice(0, 12).join('\n')}\nFix it; the restart follows by itself (or run /restart).`, 'warn');
|
|
1162
1200
|
return;
|
|
1163
1201
|
}
|
|
1164
|
-
if (this.isTurnRunning() || this.dialogs.length) { this.sourceChanged = changed; return; } // something started meanwhile: later
|
|
1202
|
+
if (this.isTurnRunning() || this.dialogs.length) { this.sourceChanged = changed; this.sourceChangedInTurn = inTurn; return; } // something started meanwhile: later
|
|
1165
1203
|
const r = this.requestRestart({ reason: this.updateRestart ? `updated to ${APP_NAME} ${this.updateRestart}` : 'source changed', force: true });
|
|
1166
1204
|
// refused (too many restarts in a row): say so, or later changes would go unloaded without a word
|
|
1167
1205
|
if (!r.ok) this.notice(`The program's source changed, but it was not restarted to load it: ${r.message.replace(/ That looks like a loop:.*$/, '')} A change after that window loads it, or /restart once it has passed.`, 'warn');
|
|
@@ -1536,7 +1574,7 @@ export class App {
|
|
|
1536
1574
|
});
|
|
1537
1575
|
const items = [...peers, ...fileItems];
|
|
1538
1576
|
if (!items.length) {
|
|
1539
|
-
if (!q && m.index === 0 && !m[1] && !quiet) this.flash(this.remote ? 'No file or session is available here or online at the gateway' : 'No file or other session is available on this computer (/login to the gateway reaches your other computers)');
|
|
1577
|
+
if (!q && m.index === 0 && !m[1] && !quiet && !this.fileIndex.loading) this.flash(this.remote ? 'No file or session is available here or online at the gateway' : 'No file or other session is available on this computer (/login to the gateway reaches your other computers)');
|
|
1540
1578
|
return null;
|
|
1541
1579
|
}
|
|
1542
1580
|
return { items, from: cursor - q.length - (quoted ? 2 : 1), to: cursor };
|
|
@@ -1575,7 +1613,7 @@ export class App {
|
|
|
1575
1613
|
if (this.screen.scrolledUp) this.screen.scrollBy('bottom'); // what was sent, and what comes of it, is in view
|
|
1576
1614
|
appendHistory(this.cwd, raw, parts);
|
|
1577
1615
|
if (this.sendTypedToPeer(text)) return;
|
|
1578
|
-
if (this.isTurnRunning()) {
|
|
1616
|
+
if (this.isTurnRunning() && !this.modelSwitchAtPause(text)) {
|
|
1579
1617
|
if (text.startsWith('/')) { this.notice('Wait for the current task to finish (or press Esc) before running commands.', 'warn'); return; }
|
|
1580
1618
|
this.queue.push({ text: value, images, ...(display ? { display } : {}) });
|
|
1581
1619
|
this.screen.schedule();
|
|
@@ -1601,6 +1639,13 @@ export class App {
|
|
|
1601
1639
|
this.startTurn(value, { display });
|
|
1602
1640
|
}
|
|
1603
1641
|
|
|
1642
|
+
// /model while the turn's request is paused for a rate limit: the one command that runs in a turn. The request
|
|
1643
|
+
// then goes on with the model chosen instead of waiting hours for the limit of the other (the user had to stop
|
|
1644
|
+
// the turn, change the model and say "go on" for that).
|
|
1645
|
+
modelSwitchAtPause(text) {
|
|
1646
|
+
return /^\/model(?:\s|$)/i.test(text) && this.agent.pausedForLimit;
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1604
1649
|
// `@name message`: the message goes to that session, as a task for it. A session on another computer of the
|
|
1605
1650
|
// gateway account: `@machine/name message`, or `@machine message` when that computer runs one session. A known
|
|
1606
1651
|
// file wins only when no session matches; use `@./name` to force a file when the names collide.
|
|
@@ -2192,7 +2237,7 @@ export class App {
|
|
|
2192
2237
|
// Say it once; later waits of the same pause only move the countdown (unless the reset moved a lot).
|
|
2193
2238
|
const prev = this.rateWait;
|
|
2194
2239
|
this.rateWait = { resumeAt: ev.resumeAt, label: ev.label, polling: ev.polling, overloaded: Boolean(ev.overloaded) };
|
|
2195
|
-
if (shouldAnnounce(prev, ev)) this.notice(`${describePause(ev)} Esc cancels.`, 'warn');
|
|
2240
|
+
if (shouldAnnounce(prev, ev)) this.notice(`${describePause(ev)} Esc cancels${!ev.overloaded && this.agent.pauseControl ? '; /model goes on with another model at once' : ''}.`, 'warn');
|
|
2196
2241
|
this.screen.schedule();
|
|
2197
2242
|
}
|
|
2198
2243
|
|
|
@@ -2506,6 +2551,7 @@ export class App {
|
|
|
2506
2551
|
if (!flash) {
|
|
2507
2552
|
if (this.updating) left += c.dim(' · ') + c.blue(`⇣ updating ${APP_NAME} to ${this.updating}…`);
|
|
2508
2553
|
else if (this.updateRestart && this.sourceChanged && !this.restartRequest) left += c.dim(' · ') + c.blue(`↻ ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
|
|
2554
|
+
else if (this.sourceChanged && !this.sourceChangedInTurn && !this.restartRequest && !this.reloading && !this.working() && this.sourceQuietAt > Date.now()) left += c.dim(' · ') + c.dim('↻ source changed: restarts once it is left alone (/restart: now)');
|
|
2509
2555
|
else if (this.pendingUpdate) left += c.dim(' · ') + c.dim(`update ${this.pendingUpdate} ready · ${this.updateWaitingFor ? `installs when @${this.updateWaitingFor.split(',')[0]} is idle` : 'installs when idle'}`);
|
|
2510
2556
|
}
|
|
2511
2557
|
const cfg = this.config;
|
package/src/utils/shell.js
CHANGED
|
@@ -21,17 +21,16 @@ export function findShell(config) {
|
|
|
21
21
|
const candidates = [];
|
|
22
22
|
if (isWin) {
|
|
23
23
|
if (config?.env.CLAUDE_CODE_GIT_BASH_PATH) candidates.push(config.env.CLAUDE_CODE_GIT_BASH_PATH);
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
24
|
+
// Where git is on the PATH, looked up here (`where git` in a process of its own took 75 ms of every start):
|
|
25
|
+
// ...\Git\cmd\git.exe or ...\Git\bin\git.exe or ...\Git\mingw64\bin\git.exe
|
|
26
|
+
for (const entry of (process.env.PATH || '').split(path.delimiter).filter(Boolean)) {
|
|
27
|
+
if (!['git.exe', 'git.cmd'].some((name) => fs.existsSync(path.join(entry, name)))) continue;
|
|
28
|
+
let dir = entry;
|
|
29
|
+
for (let i = 0; i < 3; i++) {
|
|
30
|
+
candidates.push(path.join(dir, 'bin', 'bash.exe'));
|
|
31
|
+
dir = path.dirname(dir);
|
|
33
32
|
}
|
|
34
|
-
}
|
|
33
|
+
}
|
|
35
34
|
candidates.push('C:\\Program Files\\Git\\bin\\bash.exe', 'C:\\Program Files (x86)\\Git\\bin\\bash.exe');
|
|
36
35
|
for (const c of candidates) {
|
|
37
36
|
if (c && fs.existsSync(c)) return (shellCache = { path: c, kind: 'bash', name: 'bash (Git Bash)' });
|
package/src/verify.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
// Discover a conservative project verification command when the user has not configured one.
|
|
2
|
-
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
|
|
6
|
-
function exists(cwd, name) {
|
|
7
|
-
try { return fs.statSync(path.join(cwd, name)).isFile(); } catch { return false; }
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
function directoryExists(cwd, name) {
|
|
11
|
-
try { return fs.statSync(path.join(cwd, name)).isDirectory(); } catch { return false; }
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function readJson(file) {
|
|
15
|
-
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function packageRunner(cwd) {
|
|
19
|
-
if (exists(cwd, 'pnpm-lock.yaml')) return 'pnpm';
|
|
20
|
-
if (exists(cwd, 'yarn.lock')) return 'yarn';
|
|
21
|
-
return 'npm';
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function meaningfulTestScript(script) {
|
|
25
|
-
if (typeof script !== 'string' || !script.trim()) return false;
|
|
26
|
-
// Skip npm init's placeholder because it intentionally exits with an error.
|
|
27
|
-
return !/(?:error:\s*)?no test specified/i.test(script);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function packageCommand(cwd) {
|
|
31
|
-
const pkg = readJson(path.join(cwd, 'package.json'));
|
|
32
|
-
const scripts = pkg?.scripts;
|
|
33
|
-
if (!scripts || typeof scripts !== 'object') return null;
|
|
34
|
-
const runner = packageRunner(cwd);
|
|
35
|
-
if (meaningfulTestScript(scripts.test)) return runner === 'npm' ? 'npm test' : `${runner} test`;
|
|
36
|
-
for (const name of ['check', 'verify', 'lint']) {
|
|
37
|
-
if (typeof scripts[name] === 'string' && scripts[name].trim()) return `${runner} run ${name}`;
|
|
38
|
-
}
|
|
39
|
-
return null;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function makefileCommand(cwd) {
|
|
43
|
-
if (!exists(cwd, 'Makefile')) return null;
|
|
44
|
-
try {
|
|
45
|
-
const text = fs.readFileSync(path.join(cwd, 'Makefile'), 'utf8');
|
|
46
|
-
return /^(?:\.PHONY\s+)?test\s*(?::|;)/m.test(text) ? 'make test' : null;
|
|
47
|
-
} catch { return null; }
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function discoverVerifyCommand(cwd) {
|
|
51
|
-
const root = path.resolve(cwd || process.cwd());
|
|
52
|
-
return packageCommand(root)
|
|
53
|
-
|| (exists(root, 'pyproject.toml') && (directoryExists(root, 'tests') || directoryExists(root, 'test')) ? 'python -m pytest -q' : null)
|
|
54
|
-
|| (exists(root, 'Cargo.toml') ? 'cargo test' : null)
|
|
55
|
-
|| (exists(root, 'go.mod') ? 'go test ./...' : null)
|
|
56
|
-
|| makefileCommand(root);
|
|
57
|
-
}
|