@yanzc/claude-pro 0.7.3 → 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 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
- **自动验证循环**:设置一条验证命令(`--verify "npm test"`、会话中 `/verify npm test`,或 `CLAUDE_PRO_VERIFY_COMMAND`)后,只要某一轮改过文件,模型结束前就会自动运行这条命令。失败的输出会发回给模型继续修复,直到通过,最多 3 轮。没有改文件的轮次不会触发验证。
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",
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
@@ -10,6 +10,7 @@ import { rebuildFileState } from './filestate.js';
10
10
  import { CacheStats, TTL_MS } from './cache.js';
11
11
  import { resolvePath } from './utils/paths.js';
12
12
  import { fitImagesIn, lightenImagesIn } from './utils/images.js';
13
+ import { latestWorkState, workStateFromText } from './work-state.js';
13
14
 
14
15
  export const INTERRUPT_MESSAGE = '[Request interrupted by user]';
15
16
  export const INTERRUPT_TOOL_MESSAGE = '[Request interrupted by user for tool use]';
@@ -169,7 +170,7 @@ function validateInput(schema, input) {
169
170
  }
170
171
 
171
172
  export class Agent {
172
- 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 }) {
173
174
  this.config = config;
174
175
  this.effort = effort || undefined; // a sub-agent's own effort level; undefined: the session's (config.effort)
175
176
  this.compactWindow = compactWindow; // a sub-agent's own auto-compact window (tokens); 0: the session's
@@ -186,8 +187,11 @@ export class Agent {
186
187
  this.isSubagent = isSubagent;
187
188
  this.name = name;
188
189
  this.spawnSubagent = spawnSubagent;
190
+ this.trace = trace;
191
+ this.traceTurnId = null;
189
192
  this.messages = [];
190
193
  this.todos = [];
194
+ this.workState = null; // last validated state emitted by compaction; the transcript remains the source on resume
191
195
  this.userTurns = 0; // turns the user started (see noteUserTurn)
192
196
  this.todosTurn = 0; // ... and the one in which the todo list was last written
193
197
  this.fileState = new Map();
@@ -262,6 +266,56 @@ export class Agent {
262
266
  return typeof this.systemPrompt === 'function' ? this.systemPrompt() : this.systemPrompt;
263
267
  }
264
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
+
265
319
  // A note for the model that goes with the next user message (as a <system-reminder>), after the part of the
266
320
  // request that is already cached.
267
321
  addReminder(text) {
@@ -297,8 +351,11 @@ export class Agent {
297
351
  this.usage.cacheWrite1h += u.cache_creation?.ephemeral_1h_input_tokens || 0;
298
352
  if (kind === 'summary') this.usage.compactions++;
299
353
  else this.usage.requests++;
354
+ const misses = this.cache.misses;
300
355
  this.cache.record({ usage: u, ...res.cache });
356
+ const cacheMiss = this.cache.misses > misses ? this.cache.lastMiss : null;
301
357
  this.io.usage?.(u, this);
358
+ return { usage: u, cacheMiss };
302
359
  }
303
360
 
304
361
  // After resuming a conversation: drop what the previous one had read and rebuild the map from the
@@ -331,6 +388,7 @@ export class Agent {
331
388
  resetConversation() {
332
389
  this.messages = [];
333
390
  this.todos = [];
391
+ this.workState = null;
334
392
  this.fileState.clear();
335
393
  this.lastContextTokens = 0;
336
394
  this.tokensSinceUsage = 0;
@@ -398,7 +456,14 @@ export class Agent {
398
456
  }
399
457
 
400
458
  async run(userContent, { signal } = {}) {
401
- if (!this.isSubagent) {
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) {
402
467
  this.beforeTurn?.();
403
468
  this.endEffortBoost();
404
469
  this.noteUserTurn(userContent);
@@ -411,7 +476,7 @@ export class Agent {
411
476
  for (const w of h.warnings) this.io.notice?.(w, 'warn');
412
477
  if (h.blocked) {
413
478
  this.io.notice?.(`Prompt blocked by hook: ${h.message}`, 'warn');
414
- return { text: '', interrupted: false, rejected: true };
479
+ return tracedReturn({ text: '', interrupted: false, rejected: true });
415
480
  }
416
481
  if (h.context.length) content = [...content, { type: 'text', text: `<system-reminder>${h.context.join('\n')}</system-reminder>` }];
417
482
  }
@@ -431,10 +496,10 @@ export class Agent {
431
496
  let compactedForError = false;
432
497
  let finalText = '';
433
498
  for (;;) {
434
- if (signal?.aborted) return this.handleInterrupt(null);
499
+ if (signal?.aborted) return tracedReturn(this.handleInterrupt(null));
435
500
  if (this.shouldAutoCompact()) {
436
501
  const outcome = await this.compactOnTheWay(signal);
437
- if (outcome?.interrupted) return outcome;
502
+ if (outcome?.interrupted) return tracedReturn(outcome);
438
503
  if (outcome?.failed) compactedForError = true; // it has just failed: a too-long prompt in this turn is not tried again
439
504
  }
440
505
 
@@ -445,13 +510,13 @@ export class Agent {
445
510
  if (isAbort(err) || signal?.aborted) {
446
511
  // Keep whatever text the user already saw so the model knows what it said.
447
512
  if (err.partial?.length) this.pushMessage({ role: 'assistant', content: err.partial });
448
- return this.handleInterrupt(null);
513
+ return tracedReturn(this.handleInterrupt(null));
449
514
  }
450
515
  if (err.promptTooLong && !compactedForError && this.messages.length > 2) {
451
516
  compactedForError = true;
452
517
  this.io.notice?.('Context limit reached; compacting conversation…', 'warn');
453
518
  const outcome = await this.compactOnTheWay(signal, { required: true });
454
- if (outcome?.interrupted) return outcome;
519
+ if (outcome?.interrupted) return tracedReturn(outcome);
455
520
  continue;
456
521
  }
457
522
  throw err;
@@ -490,8 +555,8 @@ export class Agent {
490
555
  const verify = this.config.verifyCommand;
491
556
  if (verify && !this.isSubagent && this.editsThisRun > 0) {
492
557
  this.editsThisRun = 0;
493
- const v = await this.runVerify(verify, signal);
494
- 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));
495
560
  if (!v.ok) {
496
561
  if (verifyRounds < this.config.verifyMaxRounds) {
497
562
  verifyRounds++;
@@ -511,7 +576,7 @@ export class Agent {
511
576
  }
512
577
  }
513
578
  if (!text) this.io.notice?.('The model ended its turn without a reply.', 'warn');
514
- return { text: finalText, interrupted: false };
579
+ return tracedReturn({ text: finalText, interrupted: false });
515
580
  }
516
581
 
517
582
  const outcome = await this.runTools(toolUses, signal);
@@ -522,10 +587,23 @@ export class Agent {
522
587
  if (outcome.interrupted) {
523
588
  resultContent.push({ type: 'text', text: INTERRUPT_TOOL_MESSAGE });
524
589
  this.pushMessage({ role: 'user', content: resultContent });
525
- return { text: finalText, interrupted: true };
590
+ return tracedReturn({ text: finalText, interrupted: true });
526
591
  }
527
592
  this.pushMessage({ role: 'user', content: resultContent });
528
- 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;
529
607
  }
530
608
  }
531
609
 
@@ -568,9 +646,10 @@ export class Agent {
568
646
  }
569
647
 
570
648
  // Run the verification command in the project root with the Bash tool. Returns {ok, output}.
571
- async runVerify(command, signal) {
649
+ async runVerify(command, signal, { attempt = 1 } = {}) {
572
650
  const bash = this.tools.find((t) => t.name === 'Bash');
573
651
  if (!bash) return { ok: true, output: '' };
652
+ const verifyStartedAt = Date.now();
574
653
  const tool = { name: 'Verify', summarize: () => command };
575
654
  const input = { command, timeout: this.config.bashMaxTimeout };
576
655
  const handle = this.io.toolStart?.({ id: `verify_${Date.now()}`, name: 'Verify', input }, tool, input, this) || {};
@@ -581,12 +660,15 @@ export class Agent {
581
660
  result = await bash.call(input, ctx);
582
661
  } catch (err) {
583
662
  handle.done?.({ isError: true, content: 'Interrupted', interrupted: true });
584
- if (isAbort(err) || signal?.aborted) return { ok: true, output: '' };
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: '' };
585
666
  return { ok: false, output: `Error: ${err.message}` };
586
667
  }
587
668
  const output = typeof result.content === 'string' ? result.content : '';
588
669
  const ok = !result.isError;
589
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 });
590
672
  return { ok, output: output.length > 15_000 ? `${output.slice(0, 3000)}\n...\n${output.slice(-12_000)}` : output };
591
673
  }
592
674
 
@@ -599,18 +681,23 @@ export class Agent {
599
681
  this.recordedSystem = system;
600
682
  this.io.systemPrompt?.(system, this);
601
683
  }
602
- const res = await streamMessage(this.config, {
684
+ const request = {
603
685
  model: this.model,
604
686
  system,
605
687
  messages: normalizeMessages(this.messages),
606
688
  tools: this.toolSchemas(),
607
689
  cacheBucket: this.isSubagent ? 'other' : 'main',
608
690
  ...(this.effort ? { effort: this.effort } : {}),
609
- }, { signal, onEvent: (ev) => this.io.streamEvent?.(ev, this) });
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
+ });
610
698
  this.lastContextTokens = contextTokens(res.usage);
611
699
  this.tokensSinceUsage = 0;
612
700
  if (this.postCompactTokens === null) this.postCompactTokens = this.lastContextTokens;
613
- this.recordUsage(res);
614
701
  return res;
615
702
  }
616
703
 
@@ -651,7 +738,7 @@ export class Agent {
651
738
  if (stop || interrupted) break;
652
739
  const run = async (tu) => {
653
740
  try {
654
- const r = await this.runOne(tu, signal, map);
741
+ const r = await this.runOne(tu, signal, map, { parallel: batch.parallel });
655
742
  results.set(tu.id, r.block);
656
743
  if (r.stop) stop = true;
657
744
  } catch (err) {
@@ -667,6 +754,11 @@ export class Agent {
667
754
  else for (const tu of batch.items) { if (stop || interrupted) break; await run(tu); }
668
755
  if (signal?.aborted) interrupted = true;
669
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
+ }
670
762
  const blocks = toolUses.map((tu) => results.get(tu.id) || {
671
763
  type: 'tool_result', tool_use_id: tu.id, is_error: true,
672
764
  content: interrupted ? 'Interrupted by user' : 'Skipped: the user rejected an earlier tool call in this batch.',
@@ -674,71 +766,92 @@ export class Agent {
674
766
  return { results: blocks, stop, interrupted };
675
767
  }
676
768
 
677
- async runOne(tu, signal, map) {
678
- 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 } = {}) {
679
770
  const tool = map.get(tu.name);
680
- if (!tool) return fail(`Error: No such tool available: ${tu.name}`);
681
- const input = tool.normalizeInput && tu.input && typeof tu.input === 'object' ? tool.normalizeInput({ ...tu.input }) : (tu.input || {});
682
- if (input.__invalid_json !== undefined) {
683
- 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.');
684
- }
685
- const schemaErr = validateInput(tool.input_schema, input);
686
- if (schemaErr) return fail(`InputValidationError: ${tool.name} failed due to the following issue:\n${schemaErr}`);
687
-
688
- const ctx = this.makeCtx(signal);
689
- const invalid = tool.validate?.(input, ctx);
690
- if (invalid) {
691
- this.io.toolRejected?.(tu, tool, invalid, this);
692
- return fail(invalid);
693
- }
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
+ }
694
797
 
695
- // Nothing is ever asked: tools run right away (a PreToolUse hook can still block one).
696
- if (this.hooks?.has('PreToolUse')) {
697
- const h = await this.hooks.run('PreToolUse', { tool_name: tool.name, tool_input: input }, { cwd: this.cwd, signal });
698
- for (const w of h.warnings) this.io.notice?.(w, 'warn');
699
- if (signal?.aborted) throw abortError();
700
- if (h.blocked) {
701
- this.io.toolRejected?.(tu, tool, h.message, this);
702
- return fail(`Blocked by PreToolUse hook: ${h.message}`);
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
+ }
703
807
  }
704
- }
705
808
 
706
- // Remember what the file looked like before this edit, so /rewind can put it back.
707
- if (tool.editsFiles && this.checkpoints) {
708
- try { const file = tool.filePath?.(input, ctx); if (file) this.checkpoints.track(file); } catch { /* never block an edit on bookkeeping */ }
709
- }
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
+ }
710
813
 
711
- this.toolUseCount++;
712
- const handle = this.io.toolStart?.(tu, tool, input, this) || {};
713
- ctx.onProgress = (p) => handle.progress?.(p);
714
- let result;
715
- try {
716
- result = await tool.call(input, ctx);
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 });
717
847
  } catch (err) {
718
848
  if (isAbort(err) || signal?.aborted) {
719
- handle.done?.({ isError: true, content: 'Interrupted', interrupted: true, display: err.partialOutput ? { output: err.partialOutput } : undefined });
849
+ this.trace?.toolEnd(traceHandle, { error: true, aborted: true, error_type: 'aborted' });
720
850
  throw abortError();
721
851
  }
722
- result = { isError: true, content: `Error: ${err.message}` };
723
- }
724
- // Images from any tool (MCP servers, say) fit what the API takes before they join the conversation.
725
- if (Array.isArray(result.content)) await fitImagesIn(result.content);
726
- handle.done?.(result);
727
- let content = typeof result.content === 'string' ? (result.content || '(no output)') : result.content;
728
- if (this.hooks?.has('PostToolUse')) {
729
- 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 });
730
- for (const w of h.warnings) this.io.notice?.(w, 'warn');
731
- const extra = [...(h.blocked ? [h.message] : []), ...h.context].join('\n');
732
- if (extra && typeof content === 'string') content += `\n\n<system-reminder>PostToolUse hook:\n${extra}</system-reminder>`;
733
- }
734
- if (typeof content === 'string' && tool.name !== 'Read' && content.length > this.config.maxToolResultChars) {
735
- content = persistLargeOutput(this.projectRoot, tu.id, content);
852
+ this.trace?.toolEnd(traceHandle, { error: true, error_type: err.name || 'tool_exception' });
853
+ throw err;
736
854
  }
737
- if (tool.editsFiles && !result.isError) this.editsThisRun++;
738
- return {
739
- block: { type: 'tool_result', tool_use_id: tu.id, content, ...(result.isError ? { is_error: true } : {}) },
740
- stop: !!result.stopTurn,
741
- };
742
855
  }
743
856
 
744
857
  // The summary in a summary request's reply: what is inside <summary>, else the text without its <analysis>.
@@ -754,6 +867,26 @@ export class Agent {
754
867
  return summary.replace(/<\/?(?:summary|analysis)>/g, '').trim();
755
868
  }
756
869
 
870
+ static workStateOf(res) {
871
+ const text = res.message.content.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim();
872
+ return workStateFromText(text);
873
+ }
874
+
875
+ // Keep a valid state when the model emits one; if a legacy or malformed response is returned, retain the last
876
+ // state from this process or the transcript instead of replacing it with unvalidated data.
877
+ compactWorkState(res) {
878
+ const parsed = Agent.workStateOf(res);
879
+ if (parsed.present && !parsed.state) {
880
+ const reason = parsed.errors.slice(0, 3).join('; ');
881
+ this.io.notice?.(`Compaction returned an invalid structured work state${reason ? ` (${reason})` : ''}; keeping the narrative summary.`, 'warn');
882
+ }
883
+ if (parsed.state) this.workState = parsed.state;
884
+ return {
885
+ state: parsed.state || this.workState || latestWorkState(this.messages),
886
+ warning: parsed.present && !parsed.state ? 'The structured work state failed validation during compaction. Verify the state below against the narrative summary before relying on it.' : '',
887
+ };
888
+ }
889
+
757
890
  // Ask the model for the summary. The request is the conversation's own request with the summary instruction
758
891
  // at its end: the same model, system prompt, tools and effort, so that the API reads the conversation from the
759
892
  // cache the turns have been filling instead of processing it all again (this is what Claude Code does; it is
@@ -763,19 +896,27 @@ export class Agent {
763
896
  // The messages are marked for the cache only where that can be read: no request after the summary starts with
764
897
  // this history, so writing it (25% over the plain input price) pays only for reading what is already there.
765
898
  // When the cache is known to have run out, and in the plain request, only the tools and system prompt are marked.
766
- async requestSummary(messages, { signal, onEvent }) {
899
+ async requestSummary(messages, { signal, onEvent, compactionId = null }) {
767
900
  const cacheMessages = !this.cacheExpired();
768
- const call = (request) => streamMessage(this.config, { model: this.model, tools: this.toolSchemas(), messages, cacheBucket: 'other', cacheMessages, ...(this.effort ? { effort: this.effort } : {}), ...request }, { signal, onEvent });
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
+ };
769
913
  try {
770
914
  const res = await call({ system: this.currentSystem() });
771
- this.recordUsage(res, 'summary');
772
915
  if (Agent.summaryOf(res)) return res;
773
916
  } catch (err) {
774
917
  if (isAbort(err) || signal?.aborted || !err.promptTooLong) throw err;
775
918
  }
776
- const res = await call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false });
777
- this.recordUsage({ ...res, cache: { ...res.cache, caching: false } }, 'summary'); // made to miss: not a miss to report
778
- return res;
919
+ return call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false }, { cacheOverride: { caching: false } });
779
920
  }
780
921
 
781
922
  // Summarise part of the conversation, as /rewind's "Summarize from here" ('after': the messages from `index` on)
@@ -787,29 +928,36 @@ export class Agent {
787
928
  const before = this.messages.slice(0, index);
788
929
  const after = this.messages.slice(index);
789
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;
790
934
  this.io.compactStart?.(false, this);
791
935
  await this.lightenImages(); // in place: `before` and `after` hold the same blocks
792
936
  const messages = normalizeMessages([...this.messages, { role: 'user', content: [{ type: 'text', text: partialCompactPrompt(part, label, instructions) }] }]);
793
937
  let res;
794
938
  try {
795
- 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) });
796
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 });
797
942
  this.io.compactEnd?.(null, this, err);
798
943
  throw err;
799
944
  }
800
945
  const summary = Agent.summaryOf(res);
801
946
  if (!summary) {
802
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 });
803
949
  this.io.compactEnd?.(null, this, err);
804
950
  throw err;
805
951
  }
806
- const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary) }] };
952
+ const state = this.compactWorkState(res);
953
+ const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary, state.state) }] };
807
954
  this.replaceMessages(part === 'before' ? [note, ...after] : [...before, note]);
808
955
  if (part === 'before') this.cache.noteCompacted(); // from its first message on: nothing of it is cached (the start of "after" still is)
809
956
  if (part === 'after') this.todos = []; // what they were about may be summarized away; the model keeps them in the summary
810
957
  this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
811
958
  this.tokensSinceUsage = 0;
812
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 });
813
961
  this.io.compactEnd?.(summary, this, null, { part });
814
962
  return summary;
815
963
  }
@@ -817,33 +965,40 @@ export class Agent {
817
965
  // Summarise the conversation and replace it with the summary.
818
966
  async compact({ signal, auto = false, instructions = '' } = {}) {
819
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;
820
971
  this.io.compactStart?.(auto, this);
821
972
  await this.lightenImages();
822
973
  const messages = normalizeMessages([...this.messages, { role: 'user', content: [{ type: 'text', text: compactPrompt(instructions) }] }]);
823
974
  // If the last assistant turn has unanswered tool calls, the sequence is invalid; drop it.
824
975
  let res;
825
976
  try {
826
- 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) });
827
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 });
828
980
  this.io.compactEnd?.(null, this, err);
829
981
  throw err;
830
982
  }
831
983
  const summary = Agent.summaryOf(res);
832
984
  if (!summary) {
833
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 });
834
987
  this.io.compactEnd?.(null, this, err);
835
988
  throw err;
836
989
  }
990
+ const state = this.compactWorkState(res);
837
991
  const todoNote = this.todos.length ? `\n\n<system-reminder>Current todo list:\n${this.todos.map((t) => `- [${t.status}] ${t.content}`).join('\n')}</system-reminder>` : '';
838
- this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto }) + todoNote }] }]);
992
+ this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto, workState: state.state, workStateWarning: state.warning }) + todoNote }] }]);
839
993
  this.cache.noteCompacted();
840
994
  this.refreshSystemPrompt?.(); // the conversation starts over: it may start from a freshly built system prompt
841
995
  this.fileState.clear();
842
996
  if (!this.isSubagent) this.checkpoints?.markConversationStale(); // the checkpoints are the main conversation's: a sub-agent's own compaction does not end them
843
- this.lastContextTokens = estimateTokens(summary) + estimateTokens(this.toolSchemas()) + 2000;
997
+ this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
844
998
  this.tokensSinceUsage = 0;
845
999
  this.postCompactTokens = null; // measured on the next request
846
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 });
847
1002
  this.io.compactEnd?.(summary, this);
848
1003
  return summary;
849
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,