@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/README.md
CHANGED
|
@@ -71,7 +71,7 @@ claude-pro -p "用 Read 工具读取 package.json,告诉我项目版本"
|
|
|
71
71
|
|
|
72
72
|
网关 key 只来自 `/login`:登录后保存在 `~/.claude-pro/gateway.json`,不用手动填写,也没有环境变量或 `.env` 文件可以设置它(没有浏览器的机器可以把另一台登录过的电脑的 `gateway.json` 拷过去)。
|
|
73
73
|
|
|
74
|
-
一般只需要 `/login`、`/model`、`/effort`、`/tui` 和 settings
|
|
74
|
+
一般只需要 `/login`、`/model`、`/effort`、`/tui` 和 settings。六个普通设置直接写在 `settings.json` 顶层(下面也是默认值):
|
|
75
75
|
|
|
76
76
|
```json
|
|
77
77
|
{
|
|
@@ -79,10 +79,13 @@ claude-pro -p "用 Read 工具读取 package.json,告诉我项目版本"
|
|
|
79
79
|
"effort": "auto",
|
|
80
80
|
"tui": "fullscreen",
|
|
81
81
|
"promptCacheTtl": "1h",
|
|
82
|
-
"subagentPromptCacheTtl": "5m"
|
|
82
|
+
"subagentPromptCacheTtl": "5m",
|
|
83
|
+
"cleanupPeriodDays": 30
|
|
83
84
|
}
|
|
84
85
|
```
|
|
85
86
|
|
|
87
|
+
`cleanupPeriodDays` 和 Claude Code 的同名设置一样:会话最后一次使用超过这么多天就删除(连同它的 trace,此后 `/resume` 里也看不到),每次启动后在后台清理所有项目,一台机器一小时最多一次;保存的大块工具输出最多留 7 天、`/rewind` 快照最多 14 天,项目记忆从不删。最小 1,想长期保留就设 `3650` 之类的大数。这一项只从 `~/.claude-pro/settings.json` 读,项目里的设置文件改不了它。
|
|
88
|
+
|
|
86
89
|
也可以用命令修改:
|
|
87
90
|
|
|
88
91
|
```bash
|
|
@@ -93,7 +96,7 @@ claude-pro config list --advanced # 另外显示高级配置
|
|
|
93
96
|
claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
94
97
|
```
|
|
95
98
|
|
|
96
|
-
会话中 `/config`
|
|
99
|
+
会话中 `/config` 默认只显示这六项,`/config advanced` 查看高级项;`/config set model sonnet` 等同于 CLI 的 `config set`。普通设置写顶层,高级设置写 `env`。`/config set/unset` 保留 `--project`、`--local`,分别修改项目共享设置或本地设置。`/model`、`/effort` 仍会记住选择,`/tui` 记到顶层 `tui`;`--model`、`--effort` 可覆盖本次启动。
|
|
97
100
|
|
|
98
101
|
设置文件从低到高:`~/.claude-pro/settings.json`、项目 `.claude-pro/settings.json`、`.claude-pro/settings.local.json`。高级项仍兼容进程环境变量(高于设置文件),包括网关地址、远程会话、输出/thinking 预算、缓存总开关、保活、网络重试、工具路径、验证、自动记忆/话题标题和 Trace 开关;普通设置不从进程环境读取。旧 `settings.json.env` 中的 `CLAUDE_PRO_GATEWAY_MODEL`、`CLAUDE_CODE_EFFORT_LEVEL`、`CLAUDE_PRO_TUI`、`CLAUDE_CODE_PROMPT_CACHE_TTL`、`CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL` 只作为兼容别名读取,同文件顶层新字段优先;用 `config set` 或 `/config set` 设置旧别名,会改写顶层新字段并移除同文件旧别名。provider 固定为 `gateway`,已删除 `--provider` 和 `CLAUDE_PRO_PROVIDER` 配置入口。
|
|
99
102
|
|
|
@@ -134,7 +137,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
134
137
|
|
|
135
138
|
## 限流:自动暂停,到点自动恢复
|
|
136
139
|
|
|
137
|
-
网关账户的 5 小时和每周限额用完时,不报错停下,而是暂停并显示倒计时(`✻ 5-hour limit reached · resumes at 23:41 (in 2h 13m)`,Esc
|
|
140
|
+
网关账户的 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
141
|
|
|
139
142
|
## 终端标题、页脚与窗口缩放
|
|
140
143
|
|
|
@@ -148,7 +151,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
148
151
|
交互式会话运行在一个很薄的**监督进程**(`src/supervisor.js`,只用 Node 内置模块)之下,所以程序可以自己重启、加载自己刚改过的代码,不需要你退出再启动:
|
|
149
152
|
|
|
150
153
|
- **模型自己重启**:改完 `src/`、`bin/` 里的代码后,模型调用 `Restart` 工具。它先在一个临时进程里把新代码完整启动一遍(所有模块能加载、界面能画出来、工具定义和系统提示词合法)——**启动不起来就不重启**,把错误还给模型去修,修好再调用;通过后在**本回合结束时**重启,对话、待办列表、`/model`、`/effort`、排队的消息、输入框里没发出去的草稿、`/rewind` 检查点都带过去,新进程里模型收到一条"已重启"的提示后接着做(可用 `then` 指定重启后先验证什么)。只在**源码仓库**(有 `.git` 的克隆,包括 `npm link` 到它)里这样做:从 npm 装的副本没有版本控制、下次更新会被覆盖,那里不给模型 `Restart` 工具,系统提示词改成"不要改自己的文件,绕过问题并在最后说明缺陷,方便用户反馈"。
|
|
151
|
-
-
|
|
154
|
+
- **改了源码自动重启**:`src/`、`bin/` 下的文件变过,就自动做同样的检查并重启。本会话的回合进行中发生的改动(多半是它自己改的)在回合结束时加载;会话空闲时看到的改动是别处做的(另一个会话在改程序、编辑器),要等源码连续 3 分钟没有再变才加载,页脚会提示,急用可以 `/restart`——否则一个会话每改一步,其余打开的会话都跟着检查、重启一次,加载的还是改到一半的代码。npm 装好的新版本是完整的,不用等。检查不通过只提示错误、不重启。按 Esc 打断的那一回合不会触发。源码自动重启固定开启,旧 `CLAUDE_PRO_AUTO_RESTART` 不再生效。
|
|
152
155
|
- **手动**:`/restart`(别名 `/reload`),`/restart force` 跳过检查并无视后台任务。
|
|
153
156
|
- 后台 agent / 后台 shell 会被重启杀掉,所以有它们在跑时拒绝重启(可 `force`)。5 分钟内重启超过 5 次视为死循环,拒绝。
|
|
154
157
|
- 重启之间终端保持原样(不退回 shell 提示符,原始模式不关),重启时敲的键不会丢;标签标题也不闪。
|
|
@@ -220,7 +223,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
220
223
|
- **全屏模式(默认)**:程序画在终端的备用屏幕上(像 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
224
|
- `ctrl+c` 或连按两次 `Esc` 清掉的草稿不会丢:在空输入框按 `↑` 找回(连同粘贴的文本和图片),中间发过别的消息也可以
|
|
222
225
|
- `@` 同时补全文件和本机/远程会话:文件引用走 `Read` 工具,等于模型自己读了这个文件。最多带前 2000 行(被截断时会明确告诉模型,并把该文件记为"只读了一部分",之后 `Write` 不会去覆盖没给它看过的行);图片作为图片附加;二进制文件和超过 512KB 的文本会被跳过并提示原因;`@目录` 列出目录内容;行首 `@会话 任务` 把任务发给另一会话
|
|
223
|
-
-
|
|
226
|
+
- 上下文用满上游输入上限时自动压缩(留出写摘要要用的余量:窗口的 5%,最多 4 万 token,这样摘要请求能读缓存而不是因超长被拒),不再读取 `CLAUDE_CODE_AUTO_COMPACT_WINDOW`;子 agent 定义的 `autoCompactWindow` 仍有效,也可手动 `/compact`
|
|
224
227
|
- 会话自动保存到 `~/.claude-pro/projects/`,`claude-pro -c` 继续上次,`claude-pro -r` 选择历史会话
|
|
225
228
|
|
|
226
229
|
**`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件/会话补全、输入历史都换成新目录的;对话、模型、effort、待办、网页上的远程会话(同一个链接)不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
|
|
@@ -237,7 +240,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
|
237
240
|
|
|
238
241
|
**后台子 agent**:模型可以用 `Task` 的 `run_in_background: true` 把子 agent 放到后台,自己继续干别的。子 agent 完成后,结果会作为 `<task-notification>` 自动送回;如果当时主 agent 空闲,会自动开启新的一轮来处理结果。`TaskOutput` 用于提前等待结果,`TaskStop` 用于取消;`/tasks` 列出所有后台 agent,`/tasks kill agent_1` 停止其中一个。`-p` 模式会等所有后台 agent 结束后再退出。
|
|
239
242
|
|
|
240
|
-
|
|
243
|
+
**验证循环(默认关闭)**:需要时显式设置验证命令(例如 `--verify "npm run check"`、会话中 `/verify npm run check`,或 `CLAUDE_PRO_VERIFY_COMMAND`),`/verify off` 关闭;程序不再自己去找项目的测试脚本来跑。设置之后,只要某一轮改过文件,模型结束前就会自动运行验证命令。失败的输出会发回给模型继续修复,直到通过,最多 3 轮。没有改文件的轮次不会触发验证。
|
|
241
244
|
|
|
242
245
|
**大输出落盘**:工具结果超过 10 万字符时,全文会保存到 `~/.claude-pro/projects/<项目>/tool-results/`,只把预览和文件路径发给模型,模型可以再用 `Read`/`Grep` 按需查看。Bash 输出被截断时同样会保存全文。超过 7 天的旧文件在启动时自动清理。
|
|
243
246
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.3",
|
|
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
|
});
|