@yanzc/claude-pro 0.7.4 → 0.7.5
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 +26 -2
- package/package.json +1 -1
- package/src/agent.js +211 -81
- package/src/agents.js +0 -1
- package/src/commands.js +165 -22
- package/src/config.js +27 -12
- package/src/context.js +3 -1
- package/src/host.js +8 -1
- package/src/main.js +6 -2
- package/src/print.js +2 -1
- package/src/prompt-profiles.js +115 -0
- package/src/prompts.js +1 -1
- package/src/runtime.js +16 -9
- package/src/tools/effort.js +1 -1
- package/src/tools/index.js +1 -1
- package/src/tools/task.js +6 -28
- package/src/tools/web.js +4 -4
- package/src/trace.js +477 -0
- package/src/ui/repl.js +15 -13
- package/src/ui/screen.js +32 -1
- package/src/verify.js +57 -0
package/README.md
CHANGED
|
@@ -93,6 +93,19 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
|
|
|
93
93
|
|
|
94
94
|
会话中用 `/config`、`/model`、`/effort` 修改。`--provider` 仅接受 `gateway`,其他 provider 已移除。
|
|
95
95
|
|
|
96
|
+
## 持久化系统提示词
|
|
97
|
+
|
|
98
|
+
可以把整个系统提示词保存到用户配置中,之后关闭并重新启动仍然使用:
|
|
99
|
+
|
|
100
|
+
```text
|
|
101
|
+
/prompt path/to/prompt.md # 读取文件,并复制到 ~/.claude-pro/prompts/
|
|
102
|
+
/prompt "回答要简洁,先给结论" # 也可以直接保存一段文字
|
|
103
|
+
/prompts # 选择已保存的提示词
|
|
104
|
+
/prompts default # 切回内置默认提示词
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`/promt` 和 `/promits` 也作为常见拼写兼容。当前选择保存在 `~/.claude-pro/settings.json` 的 `prompts.active` 中,提示词内容保存在 `~/.claude-pro/prompts/`,不会依赖原始文件;`/status` 会显示当前选择。切换提示词会立即用于下一次请求,提示词缓存仍然有效时会先询问,因为下一次请求需要重新写入对话。命令行的 `--system-prompt` 和 `--system-prompt-file` 优先级更高,只覆盖本次启动。
|
|
108
|
+
|
|
96
109
|
## 提示词缓存:自动的,尽量少花钱
|
|
97
110
|
|
|
98
111
|
每次请求都要把整个对话发给模型,用 Anthropic 的提示词缓存,重复的历史按缓存价(十分之一)计费,不用配置:
|
|
@@ -103,6 +116,17 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
|
|
|
103
116
|
|
|
104
117
|
(缓存标记放在哪、端点不认时怎么退、压缩如何复用缓存等细节见 ARCHITECTURE.md 6.5。)
|
|
105
118
|
|
|
119
|
+
## 运行时 Trace:用真实数据优化模型和工具
|
|
120
|
+
|
|
121
|
+
默认在每个会话写入独立的隐私保护 JSONL:`~/.claude-pro/projects/<项目>/traces/<session-id>.jsonl`。Trace 只保存 turn/request/tool/compaction/verification 的计数、耗时、token 数、缓存 fingerprint 和参数结构,不保存 API key、cookie、token、密码、完整 prompt、工具输入或工具输出。大输出只记录大小和是否落盘;单个文件默认 20 MB,超出后轮换为 `.1`。
|
|
122
|
+
|
|
123
|
+
```text
|
|
124
|
+
/trace # 当前会话的请求、工具、缓存、压缩和验证汇总
|
|
125
|
+
/trace 20 # 另外显示最近 20 条结构化事件
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
可用配置:`CLAUDE_PRO_TRACE=0` 关闭,`CLAUDE_PRO_TRACE_DIR` 指定目录,`CLAUDE_PRO_TRACE_MAX_SIZE` 调整单文件上限。`/cost` 也会显示轻量工具成功率和验证次数。Trace 是 best-effort,写入失败不会影响 Agent 主循环。
|
|
129
|
+
|
|
106
130
|
## 限流:自动暂停,到点自动恢复
|
|
107
131
|
|
|
108
132
|
网关账户的 5 小时和每周限额用完时,不报错停下,而是暂停并显示倒计时(`✻ 5-hour limit reached · resumes at 23:41 (in 2h 13m)`,Esc 可取消),到重置时间原样重发同一个请求,任务接着做完。网关过载(529)同样先重试、再暂停等它恢复。最多等 6 小时(`CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS`,`0` = 不等直接报错);重置时间更远(比如周限额还有几天)时直接报错,并写明几点重置。
|
|
@@ -212,7 +236,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
|
|
|
212
236
|
|
|
213
237
|
**`/cd <目录>`**:换工作目录,对话接着进行。目录可以是绝对路径、`~`、相对当前目录的路径;不存在或不是目录时报错(不会创建)。会话在新目录里重启一次(约一秒),新目录的项目设置、CLAUDE.md、记忆、git 状态、`@` 文件补全、输入历史都换成新目录的;对话、模型、effort、待办、网页上的远程会话(同一个链接)不变。会话记录跟着搬到新目录下,在新目录里 `/resume` 能找到。用 `/rename` 或 `--name` 起过的名字保留,默认按目录取的名字换成新目录名。任务进行中不能切换。
|
|
214
238
|
|
|
215
|
-
**斜杠命令**:`/help` `/tui` `/cd` `/rename` `/peers` `/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/rewind` `/skills` `/resume` `/todos` `/agents` `/mcp` `/bashes` `/verbose` `/export` `/doctor` `/exit`,以及 `.claude/commands/*.md`、`.claude-pro/commands/*.md`、`~/.claude-pro/commands/*.md` 中的自定义命令(支持 `$ARGUMENTS`、`$1`、`` !`cmd` ``)。
|
|
239
|
+
**斜杠命令**:`/help` `/tui` `/cd` `/rename` `/peers` `/clear` `/compact` `/config` `/model` `/effort` `/status` `/cost` `/trace` `/context` `/init` `/review` `/memory` `/verify` `/tasks` `/rewind` `/skills` `/resume` `/todos` `/agents` `/mcp` `/bashes` `/verbose` `/export` `/doctor` `/exit`,以及 `.claude/commands/*.md`、`.claude-pro/commands/*.md`、`~/.claude-pro/commands/*.md` 中的自定义命令(支持 `$ARGUMENTS`、`$1`、`` !`cmd` ``)。
|
|
216
240
|
|
|
217
241
|
**记忆**:自动读取 `~/.claude-pro/CLAUDE.md`、项目各级目录的 `CLAUDE.md` / `.claude/CLAUDE.md` / `CLAUDE.local.md`;某一级目录没有 `CLAUDE.md` 时读它的 `AGENTS.md` 代替(两者都有时通常是同一份说明,不重复发送)。
|
|
218
242
|
|
|
@@ -224,7 +248,7 @@ claude-pro config set CLAUDE_PRO_GATEWAY_MODEL sonnet
|
|
|
224
248
|
|
|
225
249
|
**后台子 agent**:模型可以用 `Task` 的 `run_in_background: true` 把子 agent 放到后台,自己继续干别的。子 agent 完成后,结果会作为 `<task-notification>` 自动送回;如果当时主 agent 空闲,会自动开启新的一轮来处理结果。`TaskOutput` 用于提前等待结果,`TaskStop` 用于取消;`/tasks` 列出所有后台 agent,`/tasks kill agent_1` 停止其中一个。`-p` 模式会等所有后台 agent 结束后再退出。
|
|
226
250
|
|
|
227
|
-
|
|
251
|
+
**自动验证循环**:如果项目有明确的测试入口,claude-pro 会自动发现并使用 `package.json` 的 `test`/`check`/`verify`/`lint` 脚本,或 `pytest`、`cargo test`、`go test ./...`、`make test`。也可以显式设置验证命令(`--verify "npm test"`、会话中 `/verify npm test`,或 `CLAUDE_PRO_VERIFY_COMMAND`);显式配置优先,`/verify off` 可关闭自动发现。只要某一轮改过文件,模型结束前就会自动运行验证命令。失败的输出会发回给模型继续修复,直到通过,最多 3 轮。没有改文件的轮次不会触发验证。
|
|
228
252
|
|
|
229
253
|
**大输出落盘**:工具结果超过 10 万字符时,全文会保存到 `~/.claude-pro/projects/<项目>/tool-results/`,只把预览和文件路径发给模型,模型可以再用 `Read`/`Grep` 按需查看。Bash 输出被截断时同样会保存全文。超过 7 天的旧文件在启动时自动清理。
|
|
230
254
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.5",
|
|
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
|
@@ -170,7 +170,7 @@ function validateInput(schema, input) {
|
|
|
170
170
|
}
|
|
171
171
|
|
|
172
172
|
export class Agent {
|
|
173
|
-
constructor({ config, tools, systemPrompt, io, model, isSubagent = false, cwd, name = 'main', spawnSubagent, hooks, tasks, checkpoints, depth = 0, refreshSystemPrompt, beforeTurn, effort, compactWindow = 0 }) {
|
|
173
|
+
constructor({ config, tools, systemPrompt, io, model, isSubagent = false, cwd, name = 'main', spawnSubagent, hooks, tasks, checkpoints, depth = 0, refreshSystemPrompt, beforeTurn, effort, compactWindow = 0, trace = null }) {
|
|
174
174
|
this.config = config;
|
|
175
175
|
this.effort = effort || undefined; // a sub-agent's own effort level; undefined: the session's (config.effort)
|
|
176
176
|
this.compactWindow = compactWindow; // a sub-agent's own auto-compact window (tokens); 0: the session's
|
|
@@ -187,6 +187,8 @@ export class Agent {
|
|
|
187
187
|
this.isSubagent = isSubagent;
|
|
188
188
|
this.name = name;
|
|
189
189
|
this.spawnSubagent = spawnSubagent;
|
|
190
|
+
this.trace = trace;
|
|
191
|
+
this.traceTurnId = null;
|
|
190
192
|
this.messages = [];
|
|
191
193
|
this.todos = [];
|
|
192
194
|
this.workState = null; // last validated state emitted by compaction; the transcript remains the source on resume
|
|
@@ -264,6 +266,56 @@ export class Agent {
|
|
|
264
266
|
return typeof this.systemPrompt === 'function' ? this.systemPrompt() : this.systemPrompt;
|
|
265
267
|
}
|
|
266
268
|
|
|
269
|
+
traceRequestStart({ kind = 'turn', messages = this.messages, cacheBucket = 'main', cacheMessages = true, compactionId = null } = {}) {
|
|
270
|
+
if (!this.trace?.enabled) return null;
|
|
271
|
+
const model = this.model;
|
|
272
|
+
return this.trace.requestStart({
|
|
273
|
+
turnId: this.traceTurnId,
|
|
274
|
+
agent: this.name,
|
|
275
|
+
depth: this.depth,
|
|
276
|
+
kind,
|
|
277
|
+
model: model?.id || model,
|
|
278
|
+
effort: this.effort || this.config.effort,
|
|
279
|
+
context_tokens: this.contextEstimate,
|
|
280
|
+
message_tokens: estimateTokens(messages),
|
|
281
|
+
system_tokens: estimateTokens(this.currentSystem()),
|
|
282
|
+
tool_tokens: estimateTokens(this.toolSchemas()),
|
|
283
|
+
message_count: Array.isArray(messages) ? messages.length : 0,
|
|
284
|
+
cache: {
|
|
285
|
+
bucket: cacheBucket,
|
|
286
|
+
messages: Boolean(cacheMessages),
|
|
287
|
+
caching: !this.config.promptCachingDisabled(model?.id || model),
|
|
288
|
+
ttl: this.config.cacheTtl(cacheBucket),
|
|
289
|
+
},
|
|
290
|
+
compaction_id: compactionId,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async streamAgentRequest(request, { signal, kind = 'turn', cacheBucket = 'main', cacheMessages = true, cacheOverride = null, compactionId = null, onEvent = () => {} } = {}) {
|
|
295
|
+
const handle = this.traceRequestStart({ kind, messages: request.messages, cacheBucket, cacheMessages, compactionId });
|
|
296
|
+
const forward = (ev) => {
|
|
297
|
+
this.trace?.requestEvent(handle, ev);
|
|
298
|
+
onEvent(ev);
|
|
299
|
+
};
|
|
300
|
+
try {
|
|
301
|
+
const res = await streamMessage(this.config, request, { signal, onEvent: forward });
|
|
302
|
+
const observed = cacheOverride ? { ...res, cache: { ...res.cache, ...cacheOverride } } : res;
|
|
303
|
+
const recorded = this.recordUsage(observed, kind === 'summary' ? 'summary' : 'turn');
|
|
304
|
+
this.trace?.requestEnd(handle, {
|
|
305
|
+
usage: res.usage,
|
|
306
|
+
cache: observed.cache,
|
|
307
|
+
model: res.model || request.model?.id || request.model,
|
|
308
|
+
stopReason: res.stopReason,
|
|
309
|
+
context_tokens: contextTokens(res.usage),
|
|
310
|
+
cacheMiss: recorded?.cacheMiss,
|
|
311
|
+
});
|
|
312
|
+
return res;
|
|
313
|
+
} catch (err) {
|
|
314
|
+
this.trace?.requestEnd(handle, { error: err, model: request.model?.id || request.model, context_tokens: this.contextEstimate });
|
|
315
|
+
throw err;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
267
319
|
// A note for the model that goes with the next user message (as a <system-reminder>), after the part of the
|
|
268
320
|
// request that is already cached.
|
|
269
321
|
addReminder(text) {
|
|
@@ -299,8 +351,11 @@ export class Agent {
|
|
|
299
351
|
this.usage.cacheWrite1h += u.cache_creation?.ephemeral_1h_input_tokens || 0;
|
|
300
352
|
if (kind === 'summary') this.usage.compactions++;
|
|
301
353
|
else this.usage.requests++;
|
|
354
|
+
const misses = this.cache.misses;
|
|
302
355
|
this.cache.record({ usage: u, ...res.cache });
|
|
356
|
+
const cacheMiss = this.cache.misses > misses ? this.cache.lastMiss : null;
|
|
303
357
|
this.io.usage?.(u, this);
|
|
358
|
+
return { usage: u, cacheMiss };
|
|
304
359
|
}
|
|
305
360
|
|
|
306
361
|
// After resuming a conversation: drop what the previous one had read and rebuild the map from the
|
|
@@ -401,7 +456,14 @@ export class Agent {
|
|
|
401
456
|
}
|
|
402
457
|
|
|
403
458
|
async run(userContent, { signal } = {}) {
|
|
404
|
-
|
|
459
|
+
const previousTraceTurn = this.traceTurnId;
|
|
460
|
+
const traceTurnId = this.trace?.turnStart({ agent: this.name, depth: this.depth, content: userContent });
|
|
461
|
+
this.traceTurnId = traceTurnId;
|
|
462
|
+
let traceResult = null;
|
|
463
|
+
let traceError = null;
|
|
464
|
+
const tracedReturn = (result) => { traceResult = result; return result; };
|
|
465
|
+
try {
|
|
466
|
+
if (!this.isSubagent) {
|
|
405
467
|
this.beforeTurn?.();
|
|
406
468
|
this.endEffortBoost();
|
|
407
469
|
this.noteUserTurn(userContent);
|
|
@@ -414,7 +476,7 @@ export class Agent {
|
|
|
414
476
|
for (const w of h.warnings) this.io.notice?.(w, 'warn');
|
|
415
477
|
if (h.blocked) {
|
|
416
478
|
this.io.notice?.(`Prompt blocked by hook: ${h.message}`, 'warn');
|
|
417
|
-
return { text: '', interrupted: false, rejected: true };
|
|
479
|
+
return tracedReturn({ text: '', interrupted: false, rejected: true });
|
|
418
480
|
}
|
|
419
481
|
if (h.context.length) content = [...content, { type: 'text', text: `<system-reminder>${h.context.join('\n')}</system-reminder>` }];
|
|
420
482
|
}
|
|
@@ -434,10 +496,10 @@ export class Agent {
|
|
|
434
496
|
let compactedForError = false;
|
|
435
497
|
let finalText = '';
|
|
436
498
|
for (;;) {
|
|
437
|
-
if (signal?.aborted) return this.handleInterrupt(null);
|
|
499
|
+
if (signal?.aborted) return tracedReturn(this.handleInterrupt(null));
|
|
438
500
|
if (this.shouldAutoCompact()) {
|
|
439
501
|
const outcome = await this.compactOnTheWay(signal);
|
|
440
|
-
if (outcome?.interrupted) return outcome;
|
|
502
|
+
if (outcome?.interrupted) return tracedReturn(outcome);
|
|
441
503
|
if (outcome?.failed) compactedForError = true; // it has just failed: a too-long prompt in this turn is not tried again
|
|
442
504
|
}
|
|
443
505
|
|
|
@@ -448,13 +510,13 @@ export class Agent {
|
|
|
448
510
|
if (isAbort(err) || signal?.aborted) {
|
|
449
511
|
// Keep whatever text the user already saw so the model knows what it said.
|
|
450
512
|
if (err.partial?.length) this.pushMessage({ role: 'assistant', content: err.partial });
|
|
451
|
-
return this.handleInterrupt(null);
|
|
513
|
+
return tracedReturn(this.handleInterrupt(null));
|
|
452
514
|
}
|
|
453
515
|
if (err.promptTooLong && !compactedForError && this.messages.length > 2) {
|
|
454
516
|
compactedForError = true;
|
|
455
517
|
this.io.notice?.('Context limit reached; compacting conversation…', 'warn');
|
|
456
518
|
const outcome = await this.compactOnTheWay(signal, { required: true });
|
|
457
|
-
if (outcome?.interrupted) return outcome;
|
|
519
|
+
if (outcome?.interrupted) return tracedReturn(outcome);
|
|
458
520
|
continue;
|
|
459
521
|
}
|
|
460
522
|
throw err;
|
|
@@ -493,8 +555,8 @@ export class Agent {
|
|
|
493
555
|
const verify = this.config.verifyCommand;
|
|
494
556
|
if (verify && !this.isSubagent && this.editsThisRun > 0) {
|
|
495
557
|
this.editsThisRun = 0;
|
|
496
|
-
const v = await this.runVerify(verify, signal);
|
|
497
|
-
if (signal?.aborted) return this.handleInterrupt(null);
|
|
558
|
+
const v = await this.runVerify(verify, signal, { attempt: verifyRounds + 1 });
|
|
559
|
+
if (signal?.aborted) return tracedReturn(this.handleInterrupt(null));
|
|
498
560
|
if (!v.ok) {
|
|
499
561
|
if (verifyRounds < this.config.verifyMaxRounds) {
|
|
500
562
|
verifyRounds++;
|
|
@@ -514,7 +576,7 @@ export class Agent {
|
|
|
514
576
|
}
|
|
515
577
|
}
|
|
516
578
|
if (!text) this.io.notice?.('The model ended its turn without a reply.', 'warn');
|
|
517
|
-
return { text: finalText, interrupted: false };
|
|
579
|
+
return tracedReturn({ text: finalText, interrupted: false });
|
|
518
580
|
}
|
|
519
581
|
|
|
520
582
|
const outcome = await this.runTools(toolUses, signal);
|
|
@@ -525,10 +587,23 @@ export class Agent {
|
|
|
525
587
|
if (outcome.interrupted) {
|
|
526
588
|
resultContent.push({ type: 'text', text: INTERRUPT_TOOL_MESSAGE });
|
|
527
589
|
this.pushMessage({ role: 'user', content: resultContent });
|
|
528
|
-
return { text: finalText, interrupted: true };
|
|
590
|
+
return tracedReturn({ text: finalText, interrupted: true });
|
|
529
591
|
}
|
|
530
592
|
this.pushMessage({ role: 'user', content: resultContent });
|
|
531
|
-
if (outcome.stop) return { text: finalText, interrupted: false, rejected: true };
|
|
593
|
+
if (outcome.stop) return tracedReturn({ text: finalText, interrupted: false, rejected: true });
|
|
594
|
+
}
|
|
595
|
+
} catch (err) {
|
|
596
|
+
traceError = err;
|
|
597
|
+
throw err;
|
|
598
|
+
} finally {
|
|
599
|
+
this.trace?.turnEnd({
|
|
600
|
+
turnId: traceTurnId,
|
|
601
|
+
finalStatus: traceError ? 'error' : traceResult?.interrupted ? 'interrupted' : traceResult?.rejected ? 'rejected' : 'completed',
|
|
602
|
+
interrupted: Boolean(traceResult?.interrupted),
|
|
603
|
+
rejected: Boolean(traceResult?.rejected),
|
|
604
|
+
error: traceError,
|
|
605
|
+
});
|
|
606
|
+
this.traceTurnId = previousTraceTurn;
|
|
532
607
|
}
|
|
533
608
|
}
|
|
534
609
|
|
|
@@ -571,9 +646,10 @@ export class Agent {
|
|
|
571
646
|
}
|
|
572
647
|
|
|
573
648
|
// Run the verification command in the project root with the Bash tool. Returns {ok, output}.
|
|
574
|
-
async runVerify(command, signal) {
|
|
649
|
+
async runVerify(command, signal, { attempt = 1 } = {}) {
|
|
575
650
|
const bash = this.tools.find((t) => t.name === 'Bash');
|
|
576
651
|
if (!bash) return { ok: true, output: '' };
|
|
652
|
+
const verifyStartedAt = Date.now();
|
|
577
653
|
const tool = { name: 'Verify', summarize: () => command };
|
|
578
654
|
const input = { command, timeout: this.config.bashMaxTimeout };
|
|
579
655
|
const handle = this.io.toolStart?.({ id: `verify_${Date.now()}`, name: 'Verify', input }, tool, input, this) || {};
|
|
@@ -584,12 +660,15 @@ export class Agent {
|
|
|
584
660
|
result = await bash.call(input, ctx);
|
|
585
661
|
} catch (err) {
|
|
586
662
|
handle.done?.({ isError: true, content: 'Interrupted', interrupted: true });
|
|
587
|
-
|
|
663
|
+
const aborted = isAbort(err) || signal?.aborted;
|
|
664
|
+
this.trace?.verification({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, command, attempt, ok: false, aborted, duration_ms: Date.now() - verifyStartedAt, error: aborted ? null : err });
|
|
665
|
+
if (aborted) return { ok: true, output: '' };
|
|
588
666
|
return { ok: false, output: `Error: ${err.message}` };
|
|
589
667
|
}
|
|
590
668
|
const output = typeof result.content === 'string' ? result.content : '';
|
|
591
669
|
const ok = !result.isError;
|
|
592
670
|
handle.done?.({ ...result, display: { summary: ok ? 'Verification passed' : undefined } });
|
|
671
|
+
this.trace?.verification({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, command, attempt, ok, output, duration_ms: Date.now() - verifyStartedAt });
|
|
593
672
|
return { ok, output: output.length > 15_000 ? `${output.slice(0, 3000)}\n...\n${output.slice(-12_000)}` : output };
|
|
594
673
|
}
|
|
595
674
|
|
|
@@ -602,18 +681,23 @@ export class Agent {
|
|
|
602
681
|
this.recordedSystem = system;
|
|
603
682
|
this.io.systemPrompt?.(system, this);
|
|
604
683
|
}
|
|
605
|
-
const
|
|
684
|
+
const request = {
|
|
606
685
|
model: this.model,
|
|
607
686
|
system,
|
|
608
687
|
messages: normalizeMessages(this.messages),
|
|
609
688
|
tools: this.toolSchemas(),
|
|
610
689
|
cacheBucket: this.isSubagent ? 'other' : 'main',
|
|
611
690
|
...(this.effort ? { effort: this.effort } : {}),
|
|
612
|
-
}
|
|
691
|
+
};
|
|
692
|
+
const res = await this.streamAgentRequest(request, {
|
|
693
|
+
signal,
|
|
694
|
+
kind: 'turn',
|
|
695
|
+
cacheBucket: request.cacheBucket,
|
|
696
|
+
onEvent: (ev) => this.io.streamEvent?.(ev, this),
|
|
697
|
+
});
|
|
613
698
|
this.lastContextTokens = contextTokens(res.usage);
|
|
614
699
|
this.tokensSinceUsage = 0;
|
|
615
700
|
if (this.postCompactTokens === null) this.postCompactTokens = this.lastContextTokens;
|
|
616
|
-
this.recordUsage(res);
|
|
617
701
|
return res;
|
|
618
702
|
}
|
|
619
703
|
|
|
@@ -654,7 +738,7 @@ export class Agent {
|
|
|
654
738
|
if (stop || interrupted) break;
|
|
655
739
|
const run = async (tu) => {
|
|
656
740
|
try {
|
|
657
|
-
const r = await this.runOne(tu, signal, map);
|
|
741
|
+
const r = await this.runOne(tu, signal, map, { parallel: batch.parallel });
|
|
658
742
|
results.set(tu.id, r.block);
|
|
659
743
|
if (r.stop) stop = true;
|
|
660
744
|
} catch (err) {
|
|
@@ -670,6 +754,11 @@ export class Agent {
|
|
|
670
754
|
else for (const tu of batch.items) { if (stop || interrupted) break; await run(tu); }
|
|
671
755
|
if (signal?.aborted) interrupted = true;
|
|
672
756
|
}
|
|
757
|
+
for (const tu of toolUses) {
|
|
758
|
+
if (results.has(tu.id)) continue;
|
|
759
|
+
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 });
|
|
760
|
+
this.trace?.toolEnd(skipped, { skipped: true, aborted: interrupted, error: true, error_type: interrupted ? 'aborted' : 'skipped' });
|
|
761
|
+
}
|
|
673
762
|
const blocks = toolUses.map((tu) => results.get(tu.id) || {
|
|
674
763
|
type: 'tool_result', tool_use_id: tu.id, is_error: true,
|
|
675
764
|
content: interrupted ? 'Interrupted by user' : 'Skipped: the user rejected an earlier tool call in this batch.',
|
|
@@ -677,71 +766,92 @@ export class Agent {
|
|
|
677
766
|
return { results: blocks, stop, interrupted };
|
|
678
767
|
}
|
|
679
768
|
|
|
680
|
-
async runOne(tu, signal, map) {
|
|
681
|
-
const fail = (content, extra = {}) => ({ block: { type: 'tool_result', tool_use_id: tu.id, is_error: true, content }, ...extra });
|
|
769
|
+
async runOne(tu, signal, map, { parallel = false } = {}) {
|
|
682
770
|
const tool = map.get(tu.name);
|
|
683
|
-
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
return fail(
|
|
696
|
-
|
|
771
|
+
const traceHandle = this.trace?.toolStart({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, name: tu.name, input: tu.input, parallel, toolUseId: tu.id });
|
|
772
|
+
const finish = (result, extra = {}) => {
|
|
773
|
+
this.trace?.toolEnd(traceHandle, {
|
|
774
|
+
ok: !result.block.is_error,
|
|
775
|
+
error: Boolean(result.block.is_error),
|
|
776
|
+
output: result.block.content,
|
|
777
|
+
...extra,
|
|
778
|
+
});
|
|
779
|
+
return result;
|
|
780
|
+
};
|
|
781
|
+
const fail = (content, extra = {}) => finish({ block: { type: 'tool_result', tool_use_id: tu.id, is_error: true, content }, ...extra }, { error: true, ...extra });
|
|
782
|
+
try {
|
|
783
|
+
if (!tool) return fail(`Error: No such tool available: ${tu.name}`, { error_type: 'unknown_tool' });
|
|
784
|
+
const input = tool.normalizeInput && tu.input && typeof tu.input === 'object' ? tool.normalizeInput({ ...tu.input }) : (tu.input || {});
|
|
785
|
+
if (input.__invalid_json !== undefined) {
|
|
786
|
+
return fail('Error: the tool input was not valid JSON (it may have been truncated by the output token limit). Try again with a smaller input, e.g. write large files in several steps.', { validation_error: true, error_type: 'invalid_json' });
|
|
787
|
+
}
|
|
788
|
+
const schemaErr = validateInput(tool.input_schema, input);
|
|
789
|
+
if (schemaErr) return fail(`InputValidationError: ${tool.name} failed due to the following issue:\n${schemaErr}`, { validation_error: true, error_type: 'schema' });
|
|
790
|
+
|
|
791
|
+
const ctx = this.makeCtx(signal);
|
|
792
|
+
const invalid = tool.validate?.(input, ctx);
|
|
793
|
+
if (invalid) {
|
|
794
|
+
this.io.toolRejected?.(tu, tool, invalid, this);
|
|
795
|
+
return fail(invalid, { validation_error: true, error_type: 'tool_validation' });
|
|
796
|
+
}
|
|
697
797
|
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
798
|
+
// Nothing is ever asked: tools run right away (a PreToolUse hook can still block one).
|
|
799
|
+
if (this.hooks?.has('PreToolUse')) {
|
|
800
|
+
const h = await this.hooks.run('PreToolUse', { tool_name: tool.name, tool_input: input }, { cwd: this.cwd, signal });
|
|
801
|
+
for (const w of h.warnings) this.io.notice?.(w, 'warn');
|
|
802
|
+
if (signal?.aborted) throw abortError();
|
|
803
|
+
if (h.blocked) {
|
|
804
|
+
this.io.toolRejected?.(tu, tool, h.message, this);
|
|
805
|
+
return fail(`Blocked by PreToolUse hook: ${h.message}`, { error_type: 'pretooluse_blocked' });
|
|
806
|
+
}
|
|
706
807
|
}
|
|
707
|
-
}
|
|
708
808
|
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
809
|
+
// Remember what the file looked like before this edit, so /rewind can put it back.
|
|
810
|
+
if (tool.editsFiles && this.checkpoints) {
|
|
811
|
+
try { const file = tool.filePath?.(input, ctx); if (file) this.checkpoints.track(file); } catch { /* never block an edit on bookkeeping */ }
|
|
812
|
+
}
|
|
713
813
|
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
814
|
+
this.toolUseCount++;
|
|
815
|
+
const handle = this.io.toolStart?.(tu, tool, input, this) || {};
|
|
816
|
+
ctx.onProgress = (p) => handle.progress?.(p);
|
|
817
|
+
let result;
|
|
818
|
+
try {
|
|
819
|
+
result = await tool.call(input, ctx);
|
|
820
|
+
} catch (err) {
|
|
821
|
+
if (isAbort(err) || signal?.aborted) {
|
|
822
|
+
handle.done?.({ isError: true, content: 'Interrupted', interrupted: true, display: err.partialOutput ? { output: err.partialOutput } : undefined });
|
|
823
|
+
throw abortError();
|
|
824
|
+
}
|
|
825
|
+
result = { isError: true, content: `Error: ${err.message}` };
|
|
826
|
+
}
|
|
827
|
+
// Images from any tool (MCP servers, say) fit what the API takes before they join the conversation.
|
|
828
|
+
if (Array.isArray(result.content)) await fitImagesIn(result.content);
|
|
829
|
+
handle.done?.(result);
|
|
830
|
+
let content = typeof result.content === 'string' ? (result.content || '(no output)') : result.content;
|
|
831
|
+
if (this.hooks?.has('PostToolUse')) {
|
|
832
|
+
const h = await this.hooks.run('PostToolUse', { tool_name: tool.name, tool_input: input, tool_response: typeof content === 'string' ? content.slice(0, 20_000) : '[non-text result]' }, { cwd: this.cwd, signal });
|
|
833
|
+
for (const w of h.warnings) this.io.notice?.(w, 'warn');
|
|
834
|
+
const extra = [...(h.blocked ? [h.message] : []), ...h.context].join('\n');
|
|
835
|
+
if (extra && typeof content === 'string') content += `\n\n<system-reminder>PostToolUse hook:\n${extra}</system-reminder>`;
|
|
836
|
+
}
|
|
837
|
+
let largeOutputPersisted = false;
|
|
838
|
+
if (typeof content === 'string' && tool.name !== 'Read' && content.length > this.config.maxToolResultChars) {
|
|
839
|
+
content = persistLargeOutput(this.projectRoot, tu.id, content);
|
|
840
|
+
largeOutputPersisted = true;
|
|
841
|
+
}
|
|
842
|
+
if (tool.editsFiles && !result.isError) this.editsThisRun++;
|
|
843
|
+
return finish({
|
|
844
|
+
block: { type: 'tool_result', tool_use_id: tu.id, content, ...(result.isError ? { is_error: true } : {}) },
|
|
845
|
+
stop: !!result.stopTurn,
|
|
846
|
+
}, { error_type: result.isError ? 'tool_error' : null, large_output_persisted: largeOutputPersisted });
|
|
720
847
|
} catch (err) {
|
|
721
848
|
if (isAbort(err) || signal?.aborted) {
|
|
722
|
-
|
|
849
|
+
this.trace?.toolEnd(traceHandle, { error: true, aborted: true, error_type: 'aborted' });
|
|
723
850
|
throw abortError();
|
|
724
851
|
}
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
// Images from any tool (MCP servers, say) fit what the API takes before they join the conversation.
|
|
728
|
-
if (Array.isArray(result.content)) await fitImagesIn(result.content);
|
|
729
|
-
handle.done?.(result);
|
|
730
|
-
let content = typeof result.content === 'string' ? (result.content || '(no output)') : result.content;
|
|
731
|
-
if (this.hooks?.has('PostToolUse')) {
|
|
732
|
-
const h = await this.hooks.run('PostToolUse', { tool_name: tool.name, tool_input: input, tool_response: typeof content === 'string' ? content.slice(0, 20_000) : '[non-text result]' }, { cwd: this.cwd, signal });
|
|
733
|
-
for (const w of h.warnings) this.io.notice?.(w, 'warn');
|
|
734
|
-
const extra = [...(h.blocked ? [h.message] : []), ...h.context].join('\n');
|
|
735
|
-
if (extra && typeof content === 'string') content += `\n\n<system-reminder>PostToolUse hook:\n${extra}</system-reminder>`;
|
|
736
|
-
}
|
|
737
|
-
if (typeof content === 'string' && tool.name !== 'Read' && content.length > this.config.maxToolResultChars) {
|
|
738
|
-
content = persistLargeOutput(this.projectRoot, tu.id, content);
|
|
852
|
+
this.trace?.toolEnd(traceHandle, { error: true, error_type: err.name || 'tool_exception' });
|
|
853
|
+
throw err;
|
|
739
854
|
}
|
|
740
|
-
if (tool.editsFiles && !result.isError) this.editsThisRun++;
|
|
741
|
-
return {
|
|
742
|
-
block: { type: 'tool_result', tool_use_id: tu.id, content, ...(result.isError ? { is_error: true } : {}) },
|
|
743
|
-
stop: !!result.stopTurn,
|
|
744
|
-
};
|
|
745
855
|
}
|
|
746
856
|
|
|
747
857
|
// The summary in a summary request's reply: what is inside <summary>, else the text without its <analysis>.
|
|
@@ -786,19 +896,27 @@ export class Agent {
|
|
|
786
896
|
// The messages are marked for the cache only where that can be read: no request after the summary starts with
|
|
787
897
|
// this history, so writing it (25% over the plain input price) pays only for reading what is already there.
|
|
788
898
|
// When the cache is known to have run out, and in the plain request, only the tools and system prompt are marked.
|
|
789
|
-
async requestSummary(messages, { signal, onEvent }) {
|
|
899
|
+
async requestSummary(messages, { signal, onEvent, compactionId = null }) {
|
|
790
900
|
const cacheMessages = !this.cacheExpired();
|
|
791
|
-
const call = (request
|
|
901
|
+
const call = (request, options = {}) => {
|
|
902
|
+
const useMessages = request.cacheMessages === undefined ? cacheMessages : request.cacheMessages;
|
|
903
|
+
return this.streamAgentRequest({ model: this.model, tools: this.toolSchemas(), messages, cacheBucket: 'other', cacheMessages: useMessages, ...(this.effort ? { effort: this.effort } : {}), ...request }, {
|
|
904
|
+
signal,
|
|
905
|
+
kind: 'summary',
|
|
906
|
+
cacheBucket: 'other',
|
|
907
|
+
cacheMessages: useMessages,
|
|
908
|
+
compactionId,
|
|
909
|
+
onEvent,
|
|
910
|
+
...options,
|
|
911
|
+
});
|
|
912
|
+
};
|
|
792
913
|
try {
|
|
793
914
|
const res = await call({ system: this.currentSystem() });
|
|
794
|
-
this.recordUsage(res, 'summary');
|
|
795
915
|
if (Agent.summaryOf(res)) return res;
|
|
796
916
|
} catch (err) {
|
|
797
917
|
if (isAbort(err) || signal?.aborted || !err.promptTooLong) throw err;
|
|
798
918
|
}
|
|
799
|
-
|
|
800
|
-
this.recordUsage({ ...res, cache: { ...res.cache, caching: false } }, 'summary'); // made to miss: not a miss to report
|
|
801
|
-
return res;
|
|
919
|
+
return call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false }, { cacheOverride: { caching: false } });
|
|
802
920
|
}
|
|
803
921
|
|
|
804
922
|
// Summarise part of the conversation, as /rewind's "Summarize from here" ('after': the messages from `index` on)
|
|
@@ -810,19 +928,24 @@ export class Agent {
|
|
|
810
928
|
const before = this.messages.slice(0, index);
|
|
811
929
|
const after = this.messages.slice(index);
|
|
812
930
|
if (!(part === 'before' ? before : after).length) throw new Error('There is nothing in that part of the conversation to summarize.');
|
|
931
|
+
const compactionId = `compact_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
932
|
+
const compactionStartedAt = Date.now();
|
|
933
|
+
const beforeContextTokens = this.contextEstimate;
|
|
813
934
|
this.io.compactStart?.(false, this);
|
|
814
935
|
await this.lightenImages(); // in place: `before` and `after` hold the same blocks
|
|
815
936
|
const messages = normalizeMessages([...this.messages, { role: 'user', content: [{ type: 'text', text: partialCompactPrompt(part, label, instructions) }] }]);
|
|
816
937
|
let res;
|
|
817
938
|
try {
|
|
818
|
-
res = await this.requestSummary(messages, { signal, onEvent: (ev) => this.io.compactProgress?.(ev, this) });
|
|
939
|
+
res = await this.requestSummary(messages, { signal, compactionId, onEvent: (ev) => this.io.compactProgress?.(ev, this) });
|
|
819
940
|
} catch (err) {
|
|
941
|
+
this.trace?.compact({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, part, before_context_tokens: beforeContextTokens, duration_ms: Date.now() - compactionStartedAt, error: err });
|
|
820
942
|
this.io.compactEnd?.(null, this, err);
|
|
821
943
|
throw err;
|
|
822
944
|
}
|
|
823
945
|
const summary = Agent.summaryOf(res);
|
|
824
946
|
if (!summary) {
|
|
825
947
|
const err = new Error(res.stopReason === 'max_tokens' ? 'The summary was cut off by the output token limit.' : 'The model returned an empty summary.');
|
|
948
|
+
this.trace?.compact({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, part, before_context_tokens: beforeContextTokens, duration_ms: Date.now() - compactionStartedAt, error: err });
|
|
826
949
|
this.io.compactEnd?.(null, this, err);
|
|
827
950
|
throw err;
|
|
828
951
|
}
|
|
@@ -834,6 +957,7 @@ export class Agent {
|
|
|
834
957
|
this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
|
|
835
958
|
this.tokensSinceUsage = 0;
|
|
836
959
|
this.postCompactTokens = null;
|
|
960
|
+
this.trace?.compact({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, part, before_context_tokens: beforeContextTokens, after_context_tokens: this.contextEstimate, summary_chars: summary.length, work_state_valid: Boolean(state.state), duration_ms: Date.now() - compactionStartedAt });
|
|
837
961
|
this.io.compactEnd?.(summary, this, null, { part });
|
|
838
962
|
return summary;
|
|
839
963
|
}
|
|
@@ -841,20 +965,25 @@ export class Agent {
|
|
|
841
965
|
// Summarise the conversation and replace it with the summary.
|
|
842
966
|
async compact({ signal, auto = false, instructions = '' } = {}) {
|
|
843
967
|
if (this.messages.length === 0) return null;
|
|
968
|
+
const compactionId = `compact_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
969
|
+
const compactionStartedAt = Date.now();
|
|
970
|
+
const beforeContextTokens = this.contextEstimate;
|
|
844
971
|
this.io.compactStart?.(auto, this);
|
|
845
972
|
await this.lightenImages();
|
|
846
973
|
const messages = normalizeMessages([...this.messages, { role: 'user', content: [{ type: 'text', text: compactPrompt(instructions) }] }]);
|
|
847
974
|
// If the last assistant turn has unanswered tool calls, the sequence is invalid; drop it.
|
|
848
975
|
let res;
|
|
849
976
|
try {
|
|
850
|
-
res = await this.requestSummary(messages, { signal, onEvent: (ev) => this.io.compactProgress?.(ev, this) });
|
|
977
|
+
res = await this.requestSummary(messages, { signal, compactionId, onEvent: (ev) => this.io.compactProgress?.(ev, this) });
|
|
851
978
|
} catch (err) {
|
|
979
|
+
this.trace?.compact({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, auto, before_context_tokens: beforeContextTokens, duration_ms: Date.now() - compactionStartedAt, error: err });
|
|
852
980
|
this.io.compactEnd?.(null, this, err);
|
|
853
981
|
throw err;
|
|
854
982
|
}
|
|
855
983
|
const summary = Agent.summaryOf(res);
|
|
856
984
|
if (!summary) {
|
|
857
985
|
const err = new Error(res.stopReason === 'max_tokens' ? 'Compaction failed: the summary was cut off by the output token limit.' : 'Compaction failed: the model returned an empty summary.');
|
|
986
|
+
this.trace?.compact({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, auto, before_context_tokens: beforeContextTokens, duration_ms: Date.now() - compactionStartedAt, error: err });
|
|
858
987
|
this.io.compactEnd?.(null, this, err);
|
|
859
988
|
throw err;
|
|
860
989
|
}
|
|
@@ -869,6 +998,7 @@ export class Agent {
|
|
|
869
998
|
this.tokensSinceUsage = 0;
|
|
870
999
|
this.postCompactTokens = null; // measured on the next request
|
|
871
1000
|
this.compactFailures = 0;
|
|
1001
|
+
this.trace?.compact({ turnId: this.traceTurnId, agent: this.name, depth: this.depth, auto, before_context_tokens: beforeContextTokens, after_context_tokens: this.contextEstimate, summary_chars: summary.length, work_state_valid: Boolean(state.state), duration_ms: Date.now() - compactionStartedAt });
|
|
872
1002
|
this.io.compactEnd?.(summary, this);
|
|
873
1003
|
return summary;
|
|
874
1004
|
}
|
package/src/agents.js
CHANGED
|
@@ -92,7 +92,6 @@ export function loadAgents(cwd) {
|
|
|
92
92
|
name: parsed.meta.name,
|
|
93
93
|
description: parsed.meta.description,
|
|
94
94
|
tools: parsed.meta.tools ? toolList(parsed.meta.tools) : '*',
|
|
95
|
-
model: parsed.meta.model && parsed.meta.model !== 'inherit' ? parsed.meta.model : null,
|
|
96
95
|
effort: EFFORTS.includes(parsed.meta.effort?.toLowerCase()) ? parsed.meta.effort.toLowerCase() : null,
|
|
97
96
|
autoCompactWindow: window > 0 ? window : 0,
|
|
98
97
|
prompt: parsed.body,
|