@yanzc/claude-pro 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +342 -320
- package/package.json +1 -2
- package/src/agent.js +240 -62
- package/src/agents.js +3 -2
- package/src/api.js +83 -41
- package/src/browser/broker.js +367 -0
- package/src/browser/cdp.js +114 -0
- package/src/browser/render.js +242 -0
- package/src/browser/session.js +948 -0
- package/src/browser/snapshot.js +212 -0
- package/src/cache.js +1 -1
- package/src/checkpoints.js +1 -0
- package/src/commands.js +177 -71
- package/src/compaction.js +75 -0
- package/src/config.js +153 -153
- package/src/context.js +45 -18
- package/src/filestate.js +2 -1
- package/src/gateway.js +208 -164
- package/src/hooks.js +2 -2
- package/src/keepalive.js +1 -1
- package/src/main.js +52 -40
- package/src/mcp.js +2 -2
- package/src/peers.js +1 -10
- package/src/print.js +9 -3
- package/src/prompt-profiles.js +0 -6
- package/src/prompts.js +6 -62
- package/src/ratelimit.js +3 -5
- package/src/remote.js +26 -10
- package/src/restart.js +3 -0
- package/src/runtime.js +33 -10
- package/src/selfcheck.js +3 -3
- package/src/session.js +93 -3
- package/src/supervisor.js +10 -1
- package/src/tools/bash.js +19 -18
- package/src/tools/browser.js +365 -0
- package/src/tools/code.js +430 -0
- package/src/tools/effort.js +3 -4
- package/src/tools/files.js +92 -19
- package/src/tools/index.js +6 -0
- package/src/tools/notebook.js +11 -4
- package/src/tools/processes.js +274 -0
- package/src/tools/search.js +104 -21
- package/src/tools/web.js +316 -46
- package/src/trace.js +0 -4
- package/src/ui/ansi.js +92 -13
- package/src/ui/dialogs.js +16 -54
- package/src/ui/editor.js +231 -34
- package/src/ui/markdown.js +1 -2
- package/src/ui/render.js +1 -2
- package/src/ui/repl.js +246 -119
- package/src/ui/screen.js +139 -31
- package/src/updater.js +135 -165
- package/src/utils/clipboard.js +5 -3
- package/src/utils/paths.js +15 -17
- package/src/utils/shell.js +75 -21
- package/.env.example +0 -29
- package/src/verify.js +0 -57
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.2",
|
|
4
4
|
"description": "claude-pro: a command line coding agent for the codex-gateway. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -21,7 +21,6 @@
|
|
|
21
21
|
"files": [
|
|
22
22
|
"bin/",
|
|
23
23
|
"src/",
|
|
24
|
-
".env.example",
|
|
25
24
|
"README.md",
|
|
26
25
|
"LICENSE"
|
|
27
26
|
],
|
package/src/agent.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { streamMessage, contextTokens, isAbort } from './api.js';
|
|
7
|
-
import {
|
|
7
|
+
import { loadGatewayModels } from './gateway.js';
|
|
8
|
+
import { compactPrompt, partialCompactPrompt, partialSummaryMessage, continuationMessage, keptUserMessagesIn, SUMMARY_SYSTEM } from './compaction.js';
|
|
8
9
|
import { toolResultsDir } from './session.js';
|
|
9
10
|
import { rebuildFileState } from './filestate.js';
|
|
10
11
|
import { CacheStats, TTL_MS } from './cache.js';
|
|
@@ -65,18 +66,46 @@ export function persistLargeOutput(root, id, text) {
|
|
|
65
66
|
// user's answers and the like stay whatever their age.
|
|
66
67
|
export const IDLE_CLEARING = { idleMs: 65 * 60_000, keep: 5, atLeast: 20_000 };
|
|
67
68
|
export const CLEARED = '[Old tool result content cleared]';
|
|
68
|
-
|
|
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']);
|
|
69
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
|
+
}
|
|
70
97
|
|
|
71
98
|
const isThinking = (b) => b.type === 'thinking' || b.type === 'redacted_thinking';
|
|
72
99
|
const resultText = (content) => (typeof content === 'string' ? content : Array.isArray(content) ? content.filter((b) => b.type === 'text').map((b) => b.text).join('\n') : '');
|
|
73
100
|
|
|
74
|
-
// Clear the results of all but the last `keep` clearable tool calls,
|
|
75
|
-
//
|
|
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
|
|
76
104
|
// thinking for tampered with, and rejects the request. `save(id, text)` keeps a cleared output in a file and
|
|
77
105
|
// returns its path, so that what a command printed can still be looked up; a file read is read again instead.
|
|
78
|
-
// Returns {messages (a new list: the old one is not changed), results (how many were cleared), tokens
|
|
79
|
-
// 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)}.
|
|
80
109
|
export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLeast = IDLE_CLEARING.atLeast, save = () => null, cwd = process.cwd() } = {}) {
|
|
81
110
|
const uses = new Map(); // tool_use id -> the tool_use block
|
|
82
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);
|
|
@@ -92,6 +121,14 @@ export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLea
|
|
|
92
121
|
clear.add(b);
|
|
93
122
|
tokens += t;
|
|
94
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
|
+
}
|
|
95
132
|
if (tokens < atLeast) return null;
|
|
96
133
|
const fileOf = (b) => {
|
|
97
134
|
const p = uses.get(b.tool_use_id)?.input?.file_path;
|
|
@@ -108,9 +145,13 @@ export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLea
|
|
|
108
145
|
const out = messages.map((m) => {
|
|
109
146
|
if (!Array.isArray(m.content)) return m;
|
|
110
147
|
if (m.role === 'assistant') {
|
|
111
|
-
|
|
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;
|
|
112
153
|
for (const b of m.content) if (isThinking(b)) tokens += estimateTokens(b.thinking ?? b.data ?? '');
|
|
113
|
-
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));
|
|
114
155
|
return { ...m, content: content.length ? content : [{ type: 'text', text: '(no content)' }] };
|
|
115
156
|
}
|
|
116
157
|
for (const b of m.content) {
|
|
@@ -121,7 +162,7 @@ export function clearOldToolResults(messages, { keep = IDLE_CLEARING.keep, atLea
|
|
|
121
162
|
if (!m.content.some((b) => clear.has(b))) return m;
|
|
122
163
|
return { ...m, content: m.content.map((b) => (clear.has(b) ? { ...b, content: placeholder(b) } : b)) };
|
|
123
164
|
});
|
|
124
|
-
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)) };
|
|
125
166
|
}
|
|
126
167
|
|
|
127
168
|
// A summary request's messages with the older half of the turns left out: the first message (the task, or the
|
|
@@ -143,6 +184,49 @@ function toBlocks(content) {
|
|
|
143
184
|
return typeof content === 'string' ? [{ type: 'text', text: content }] : content;
|
|
144
185
|
}
|
|
145
186
|
|
|
187
|
+
// How much of the user's own messages a compaction keeps word for word, in estimated tokens (Codex keeps 20k).
|
|
188
|
+
const KEPT_USER_TOKENS = 20_000;
|
|
189
|
+
// Text the program puts in a user message, not the user: notes for the model, reports of background agents and of
|
|
190
|
+
// other sessions, bash mode, interruptions. The summaries of earlier compactions are read for the messages they kept.
|
|
191
|
+
const PROGRAM_TEXT = /^(?:<(?:system-reminder|task-notification|peer-message|bash-input)\b|\[Request interrupted by user)/;
|
|
192
|
+
const SUMMARY_TEXT = /^(?:This session is being continued|\[Summarized conversation\])/;
|
|
193
|
+
// The note a restarted session goes on with (see restartNote), in front of what the user had queued meanwhile: not the
|
|
194
|
+
// user's either, and in a session that restarts often those notes took the room of what the user wrote.
|
|
195
|
+
const RESTART_NOTE = /^\[claude-pro restarted[\s\S]*?\](?:\n\n|$)/;
|
|
196
|
+
|
|
197
|
+
// The user's own messages in `messages`, oldest first, to keep word for word through a compaction as Codex does: what
|
|
198
|
+
// they typed ("[image]" for a picture) and what earlier summaries kept. The newest that fit in `budget` estimated
|
|
199
|
+
// tokens are kept whole, the next one shortened in the middle to what is left (when that is worth it), none older.
|
|
200
|
+
export function keptUserMessages(messages, budget = KEPT_USER_TOKENS) {
|
|
201
|
+
const all = [];
|
|
202
|
+
for (const m of messages) {
|
|
203
|
+
if (m.role !== 'user') continue;
|
|
204
|
+
const typed = [];
|
|
205
|
+
for (const b of toBlocks(m.content)) {
|
|
206
|
+
if (b.type === 'image') { typed.push('[image]'); continue; }
|
|
207
|
+
if (b.type !== 'text') continue;
|
|
208
|
+
const text = (b.text || '').replace(RESTART_NOTE, '');
|
|
209
|
+
if (!text.trim() || PROGRAM_TEXT.test(text)) continue;
|
|
210
|
+
if (SUMMARY_TEXT.test(text)) all.push(...keptUserMessagesIn(text));
|
|
211
|
+
else typed.push(text);
|
|
212
|
+
}
|
|
213
|
+
if (typed.length) all.push(typed.join('\n'));
|
|
214
|
+
}
|
|
215
|
+
const kept = [];
|
|
216
|
+
let left = budget;
|
|
217
|
+
for (let i = all.length - 1; i >= 0 && left > 0; i--) {
|
|
218
|
+
const text = all[i];
|
|
219
|
+
const tokens = estimateTokens(text);
|
|
220
|
+
if (tokens <= left) { kept.push(text); left -= tokens; continue; }
|
|
221
|
+
if (left >= 200) {
|
|
222
|
+
const half = Math.floor(text.length * left / tokens / 2);
|
|
223
|
+
kept.push(`${text.slice(0, half)}\n[… ${text.length - 2 * half} characters left out …]\n${text.slice(text.length - half)}`);
|
|
224
|
+
}
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
return kept.reverse();
|
|
228
|
+
}
|
|
229
|
+
|
|
146
230
|
// Merge consecutive same-role messages and drop empties so the API always sees a valid sequence.
|
|
147
231
|
export function normalizeMessages(messages) {
|
|
148
232
|
const out = [];
|
|
@@ -305,6 +389,7 @@ export class Agent {
|
|
|
305
389
|
this.projectRoot = cwd;
|
|
306
390
|
this.cwd = cwd;
|
|
307
391
|
this.lastContextTokens = 0;
|
|
392
|
+
this.usageModel = null; // the model whose usage report last set lastContextTokens (see shouldAutoCompact)
|
|
308
393
|
this.tokensSinceUsage = 0;
|
|
309
394
|
this.heldTokens = 0; // room taken by tool results not yet in the conversation (see takeContext)
|
|
310
395
|
// What this agent's own requests used. `requests` counts the turns' requests; the summary requests of
|
|
@@ -321,6 +406,7 @@ export class Agent {
|
|
|
321
406
|
this.postCompactTokens = undefined; // undefined: never compacted; null: compacted, awaiting measurement
|
|
322
407
|
this.compactFailures = 0; // automatic compactions that failed in a row
|
|
323
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)
|
|
324
410
|
this.busy = 0; // turns and summaries in progress: while there are any, the cache needs no refresh
|
|
325
411
|
this.keepAlive = isSubagent ? null : new CacheKeepAlive(this); // the prompt cache kept warm while idle
|
|
326
412
|
}
|
|
@@ -337,7 +423,7 @@ export class Agent {
|
|
|
337
423
|
// Tokens the context can still take before it reaches the auto-compaction threshold: what a Read with allow_large
|
|
338
424
|
// may use (a larger one would be compacted away right after it was read).
|
|
339
425
|
contextRoom() {
|
|
340
|
-
return this.config.
|
|
426
|
+
return this.config.compactWindow(this.model, this.compactWindow) - this.contextEstimate - this.heldTokens;
|
|
341
427
|
}
|
|
342
428
|
|
|
343
429
|
// Claim room for a tool result that is about to be added. Read-only tools run in parallel, so what each one
|
|
@@ -394,14 +480,14 @@ export class Agent {
|
|
|
394
480
|
cache: {
|
|
395
481
|
bucket: cacheBucket,
|
|
396
482
|
messages: Boolean(cacheMessages),
|
|
397
|
-
caching: !this.config.promptCachingDisabled(
|
|
483
|
+
caching: !this.config.promptCachingDisabled(),
|
|
398
484
|
ttl: this.config.cacheTtl(cacheBucket),
|
|
399
485
|
},
|
|
400
486
|
compaction_id: compactionId,
|
|
401
487
|
});
|
|
402
488
|
}
|
|
403
489
|
|
|
404
|
-
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 } = {}) {
|
|
405
491
|
const handle = this.traceRequestStart({ kind, messages: request.messages, cacheBucket, cacheMessages, compactionId });
|
|
406
492
|
// A bug in what shows or traces the stream must not fail the request: it had no HTTP status, so it was taken
|
|
407
493
|
// for a network error and the request was sent (and billed) again, up to the retry limit, failing the same way
|
|
@@ -416,7 +502,7 @@ export class Agent {
|
|
|
416
502
|
}
|
|
417
503
|
};
|
|
418
504
|
try {
|
|
419
|
-
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 });
|
|
420
506
|
if (handlerError) this.io.notice?.(`Showing the reply failed (${handlerError.message}); the reply itself is complete.`, 'warn');
|
|
421
507
|
const observed = cacheOverride ? { ...res, cache: { ...res.cache, ...cacheOverride } } : res;
|
|
422
508
|
const recorded = this.recordUsage(observed, kind === 'summary' || kind === 'keepalive' ? kind : 'turn');
|
|
@@ -533,8 +619,9 @@ export class Agent {
|
|
|
533
619
|
// (MAX_THINKING_TOKENS: thinking.type "enabled") the API wants its last assistant message to start with its
|
|
534
620
|
// thinking, which cannot stay once a result before it has changed: then nothing is cleared. Adaptive thinking,
|
|
535
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.
|
|
536
623
|
// Returns what clearOldToolResults did, or null.
|
|
537
|
-
clearAfterIdle(now = Date.now()) {
|
|
624
|
+
clearAfterIdle(now = Date.now(), { pause = false } = {}) {
|
|
538
625
|
if (this.isSubagent || !this.config.clearAfterIdle || !this.lastActivityAt) return null;
|
|
539
626
|
const idle = now - this.lastActivityAt;
|
|
540
627
|
if (idle <= IDLE_CLEARING.idleMs) return null;
|
|
@@ -548,7 +635,9 @@ export class Agent {
|
|
|
548
635
|
this.replaceMessages(out.messages); // into the session file too: a resumed conversation goes on with the short one
|
|
549
636
|
for (const file of out.forget) this.fileState.delete(file); // the model no longer sees it: Read before Edit/Write
|
|
550
637
|
this.lastContextTokens = Math.max(0, this.lastContextTokens - out.tokens);
|
|
551
|
-
|
|
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.`);
|
|
552
641
|
return out;
|
|
553
642
|
}
|
|
554
643
|
|
|
@@ -560,6 +649,16 @@ export class Agent {
|
|
|
560
649
|
return this.lastActivityAt > 0 && now - this.lastActivityAt >= TTL_MS[this.config.cacheTtl('main')];
|
|
561
650
|
}
|
|
562
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
|
+
|
|
563
662
|
// The conversation's last request again, for a refresh of its cache entry (keepalive.js): the messages before
|
|
564
663
|
// the last reply, the way callModel sent them then (normalizing and repairing give the same result for the same
|
|
565
664
|
// messages), and max_tokens 1. null when there is no reply yet.
|
|
@@ -619,7 +718,7 @@ export class Agent {
|
|
|
619
718
|
this.busy++; // undone in the finally below
|
|
620
719
|
try {
|
|
621
720
|
if (!this.isSubagent) {
|
|
622
|
-
this.beforeTurn?.();
|
|
721
|
+
await this.beforeTurn?.();
|
|
623
722
|
this.endEffortBoost();
|
|
624
723
|
this.noteUserTurn(userContent);
|
|
625
724
|
}
|
|
@@ -651,6 +750,9 @@ export class Agent {
|
|
|
651
750
|
let compactedForError = false;
|
|
652
751
|
let finalText = '';
|
|
653
752
|
for (;;) {
|
|
753
|
+
// The model's window may come from the gateway's model list (see Config.resolveModel): loaded before the check,
|
|
754
|
+
// or a resumed conversation is measured against a guess (deepseek-v4.1-flash was compacted at 160k of its 1M).
|
|
755
|
+
await loadGatewayModels(this.config, signal);
|
|
654
756
|
if (signal?.aborted) return tracedReturn(this.handleInterrupt(null));
|
|
655
757
|
if (this.shouldAutoCompact()) {
|
|
656
758
|
const outcome = await this.compactOnTheWay(signal);
|
|
@@ -670,7 +772,7 @@ export class Agent {
|
|
|
670
772
|
if (err.promptTooLong && !compactedForError && this.messages.length > 2) {
|
|
671
773
|
compactedForError = true;
|
|
672
774
|
this.io.notice?.('Context limit reached; compacting conversation…', 'warn');
|
|
673
|
-
const outcome = await this.compactOnTheWay(signal, { required: true });
|
|
775
|
+
const outcome = await this.compactOnTheWay(signal, { required: true, overflow: err });
|
|
674
776
|
if (outcome?.interrupted) return tracedReturn(outcome);
|
|
675
777
|
continue;
|
|
676
778
|
}
|
|
@@ -693,6 +795,7 @@ export class Agent {
|
|
|
693
795
|
continue;
|
|
694
796
|
}
|
|
695
797
|
const queued = [...toQueuedBlocks(this.io.takeQueued?.() || []), ...(this.isSubagent ? [] : this.drainNotifications())];
|
|
798
|
+
await fitImagesIn(queued); // a pasted photo at full size: scaled now, not after the API refuses it
|
|
696
799
|
if (queued.length) {
|
|
697
800
|
this.pushMessage({ role: 'user', content: queued });
|
|
698
801
|
continue;
|
|
@@ -730,14 +833,21 @@ export class Agent {
|
|
|
730
833
|
continue;
|
|
731
834
|
}
|
|
732
835
|
}
|
|
733
|
-
|
|
836
|
+
// A refusal (stop_reason "refusal") comes without text too, but the model did not just fall silent: it declined
|
|
837
|
+
// the request, and the same request, or "go on" after it, is usually declined again. Said as such, with what
|
|
838
|
+
// helps, as Claude Code does: the message reworded, or the context that led to it left out.
|
|
839
|
+
if (!text) {
|
|
840
|
+
this.io.notice?.(stopReason !== 'refusal' ? 'The model ended its turn without a reply.'
|
|
841
|
+
: `The model declined this request (stop_reason: refusal) and gave no reply.${this.isSubagent ? '' : ' Press esc twice to go back and reword the message, or /compact or /clear to leave out the context that led to it.'}`, 'warn');
|
|
842
|
+
}
|
|
734
843
|
return tracedReturn({ text: finalText, interrupted: false });
|
|
735
844
|
}
|
|
736
845
|
|
|
737
846
|
const outcome = await this.runTools(toolUses, signal);
|
|
738
847
|
const resultContent = [...outcome.results];
|
|
739
|
-
const queued = this.io.takeQueued?.() || [];
|
|
740
|
-
|
|
848
|
+
const queued = toQueuedBlocks(this.io.takeQueued?.() || []);
|
|
849
|
+
await fitImagesIn(queued);
|
|
850
|
+
resultContent.push(...queued);
|
|
741
851
|
if (!this.isSubagent) resultContent.push(...this.drainNotifications());
|
|
742
852
|
if (outcome.interrupted) {
|
|
743
853
|
resultContent.push({ type: 'text', text: INTERRUPT_TOOL_MESSAGE });
|
|
@@ -765,9 +875,13 @@ export class Agent {
|
|
|
765
875
|
}
|
|
766
876
|
|
|
767
877
|
shouldAutoCompact() {
|
|
768
|
-
if (
|
|
878
|
+
if (this.messages.length <= 2) return false;
|
|
769
879
|
if (this.compactFailures >= MAX_COMPACT_FAILURES) return false;
|
|
770
|
-
|
|
880
|
+
// A count reported by another model (the user switched) is in another tokenizer's tokens: Opus counted 304k where
|
|
881
|
+
// GPT had counted 207k of the same conversation, and GPT compacted at once. The next request measures it instead;
|
|
882
|
+
// a conversation too long for this model is compacted on the error.
|
|
883
|
+
if (this.usageModel && this.usageModel !== this.model.id) return false;
|
|
884
|
+
const threshold = this.config.compactWindow(this.model, this.compactWindow);
|
|
771
885
|
if (this.contextEstimate < threshold) return false;
|
|
772
886
|
// Right after a compaction the base context (system prompt, tools, summary) may itself be
|
|
773
887
|
// near a very small window; require real growth so we don't compact on every step.
|
|
@@ -786,10 +900,10 @@ export class Agent {
|
|
|
786
900
|
// A compaction that fails does not fail the turn when the request still fits (the threshold leaves room
|
|
787
901
|
// below the model's limit): the turn goes on without it, and {failed: true} is returned. After
|
|
788
902
|
// MAX_COMPACT_FAILURES in a row it is left off (see shouldAutoCompact). `required`: the request is already
|
|
789
|
-
// too long, so there is nothing to go on with, and the error is thrown.
|
|
790
|
-
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 } = {}) {
|
|
791
905
|
try {
|
|
792
|
-
await this.compact({ signal, auto: true });
|
|
906
|
+
await this.compact({ signal, auto: true, overflow });
|
|
793
907
|
return null;
|
|
794
908
|
} catch (err) {
|
|
795
909
|
if (isAbort(err) || signal?.aborted) return this.handleInterrupt();
|
|
@@ -831,13 +945,16 @@ export class Agent {
|
|
|
831
945
|
|
|
832
946
|
async callModel(signal) {
|
|
833
947
|
await this.lightenImages();
|
|
834
|
-
const system = this.currentSystem();
|
|
835
948
|
// The system prompt is kept with the conversation, so that a resumed one can continue behind the same
|
|
836
949
|
// prompt (and so with the cache it has) instead of a freshly built one.
|
|
837
|
-
|
|
838
|
-
this.recordedSystem
|
|
839
|
-
|
|
840
|
-
|
|
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());
|
|
841
958
|
// The repair goes into the request only, done again (the same way) for every request: storing it in place of
|
|
842
959
|
// the conversation merged and inserted messages, which moved the messages the checkpoints point at, so a
|
|
843
960
|
// /rewind after a restart cut the conversation in the wrong place.
|
|
@@ -847,7 +964,7 @@ export class Agent {
|
|
|
847
964
|
for (const id of fresh) this.recoveredToolIds.add(id);
|
|
848
965
|
this.io.notice?.('Recovered an unfinished tool call in the conversation; continuing with an interrupted result.', 'warn');
|
|
849
966
|
}
|
|
850
|
-
|
|
967
|
+
let request = {
|
|
851
968
|
model: this.model,
|
|
852
969
|
system,
|
|
853
970
|
messages: repaired.messages,
|
|
@@ -855,13 +972,35 @@ export class Agent {
|
|
|
855
972
|
cacheBucket: this.isSubagent ? 'other' : 'main',
|
|
856
973
|
...(this.effort ? { effort: this.effort } : {}),
|
|
857
974
|
};
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
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
|
+
}
|
|
864
1002
|
this.lastContextTokens = contextTokens(res.usage);
|
|
1003
|
+
this.usageModel = request.model.id;
|
|
865
1004
|
this.tokensSinceUsage = 0;
|
|
866
1005
|
if (this.postCompactTokens === null) this.postCompactTokens = this.lastContextTokens;
|
|
867
1006
|
return res;
|
|
@@ -900,14 +1039,28 @@ export class Agent {
|
|
|
900
1039
|
else batches.push({ parallel: safe, items: [tu] });
|
|
901
1040
|
}
|
|
902
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;
|
|
903
1046
|
for (const batch of batches) {
|
|
904
1047
|
if (stop || interrupted) break;
|
|
905
1048
|
const run = async (tu) => {
|
|
906
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
|
+
}
|
|
907
1059
|
const r = await this.runOne(tu, signal, map, { parallel: batch.parallel });
|
|
908
1060
|
// Key by the tool-use object, not its provider id. A malformed provider response
|
|
909
1061
|
// can repeat an id; one duplicate must not overwrite the other result.
|
|
910
1062
|
results.set(tu, r.block);
|
|
1063
|
+
if (r.block.is_error && tool?.editsFiles) failedEdit ||= tu.name;
|
|
911
1064
|
if (r.stop) stop = true;
|
|
912
1065
|
} catch (err) {
|
|
913
1066
|
if (isAbort(err) || signal?.aborted) {
|
|
@@ -949,7 +1102,10 @@ export class Agent {
|
|
|
949
1102
|
const fail = (content, extra = {}) => finish({ block: { type: 'tool_result', tool_use_id: tu.id, is_error: true, content }, ...extra }, { error: true, ...extra });
|
|
950
1103
|
try {
|
|
951
1104
|
if (!tool) return fail(`Error: No such tool available: ${tu.name}`, { error_type: 'unknown_tool' });
|
|
952
|
-
|
|
1105
|
+
// A copy: validation turns numbers sent as strings into numbers, and the tool_use block must stay as it was sent
|
|
1106
|
+
// and saved, or a restarted session sends it differently and the prompt cache misses from there on.
|
|
1107
|
+
const own = tu.input && typeof tu.input === 'object' ? { ...tu.input } : (tu.input || {});
|
|
1108
|
+
const input = tool.normalizeInput && tu.input && typeof tu.input === 'object' ? tool.normalizeInput(own) : own;
|
|
953
1109
|
if (input.__invalid_json !== undefined) {
|
|
954
1110
|
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' });
|
|
955
1111
|
}
|
|
@@ -1077,7 +1233,8 @@ export class Agent {
|
|
|
1077
1233
|
}
|
|
1078
1234
|
}
|
|
1079
1235
|
|
|
1080
|
-
|
|
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 }) {
|
|
1081
1238
|
const cacheMessages = !this.cacheExpired();
|
|
1082
1239
|
const call = (request, options = {}) => {
|
|
1083
1240
|
const useMessages = request.cacheMessages === undefined ? cacheMessages : request.cacheMessages;
|
|
@@ -1091,29 +1248,48 @@ export class Agent {
|
|
|
1091
1248
|
...options,
|
|
1092
1249
|
});
|
|
1093
1250
|
};
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
const plain = (msgs) => call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false, messages: msgs }, { cacheOverride: { caching: false } });
|
|
1101
|
-
let tooLong;
|
|
1102
|
-
try {
|
|
1103
|
-
return await plain(messages);
|
|
1104
|
-
} 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) => {
|
|
1105
1257
|
if (isAbort(err) || signal?.aborted || !err.promptTooLong) throw err;
|
|
1106
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
|
+
}
|
|
1107
1270
|
}
|
|
1108
|
-
//
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
let smaller = clearOldToolResults(messages, { keep: 3, atLeast: 0, cwd: this.cwd })?.messages || messages;
|
|
1112
|
-
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;
|
|
1113
1274
|
try {
|
|
1114
|
-
return await
|
|
1275
|
+
return await call({ system: SUMMARY_SYSTEM, effort: null, cacheMessages: false, messages: msgs }, { cacheOverride: { caching: false } });
|
|
1115
1276
|
} catch (err) {
|
|
1116
|
-
|
|
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;
|
|
1117
1293
|
}
|
|
1118
1294
|
smaller = withoutOldestHalf(smaller);
|
|
1119
1295
|
}
|
|
@@ -1151,8 +1327,9 @@ export class Agent {
|
|
|
1151
1327
|
throw err;
|
|
1152
1328
|
}
|
|
1153
1329
|
const state = this.compactWorkState(res);
|
|
1154
|
-
const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary, state.state) }] };
|
|
1330
|
+
const note = { role: 'user', content: [{ type: 'text', text: partialSummaryMessage(part, summary, state.state, keptUserMessages(part === 'before' ? before : after)) }] };
|
|
1155
1331
|
this.replaceMessages(part === 'before' ? [note, ...after] : [...before, note]);
|
|
1332
|
+
this.fileState.clear(); // the files read in the part summarized are not in view any more: Write wants them read again
|
|
1156
1333
|
if (part === 'before') this.cache.noteCompacted(); // from its first message on: nothing of it is cached (the start of "after" still is)
|
|
1157
1334
|
if (part === 'after') this.todos = []; // what they were about may be summarized away; the model keeps them in the summary
|
|
1158
1335
|
this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
|
|
@@ -1164,7 +1341,7 @@ export class Agent {
|
|
|
1164
1341
|
}
|
|
1165
1342
|
|
|
1166
1343
|
// Summarise the conversation and replace it with the summary.
|
|
1167
|
-
async compact({ signal, auto = false, instructions = '' } = {}) {
|
|
1344
|
+
async compact({ signal, auto = false, instructions = '', overflow = null } = {}) {
|
|
1168
1345
|
if (this.messages.length === 0) return null;
|
|
1169
1346
|
const compactionId = `compact_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1170
1347
|
const compactionStartedAt = Date.now();
|
|
@@ -1176,7 +1353,7 @@ export class Agent {
|
|
|
1176
1353
|
const messages = repairToolResults(normalizeMessages([...this.messages, { role: 'user', content: [{ type: 'text', text: compactPrompt(instructions) }] }])).messages;
|
|
1177
1354
|
let res;
|
|
1178
1355
|
try {
|
|
1179
|
-
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) });
|
|
1180
1357
|
} catch (err) {
|
|
1181
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 });
|
|
1182
1359
|
this.io.compactEnd?.(null, this, err);
|
|
@@ -1191,9 +1368,10 @@ export class Agent {
|
|
|
1191
1368
|
}
|
|
1192
1369
|
const state = this.compactWorkState(res);
|
|
1193
1370
|
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>` : '';
|
|
1194
|
-
|
|
1371
|
+
const userMessages = keptUserMessages(this.messages);
|
|
1372
|
+
this.replaceMessages([{ role: 'user', content: [{ type: 'text', text: continuationMessage(summary, { auto, workState: state.state, workStateWarning: state.warning, userMessages }) + todoNote }] }]);
|
|
1195
1373
|
this.cache.noteCompacted();
|
|
1196
|
-
this.refreshSystemPrompt?.(); // the conversation starts over: it may start from a freshly built system prompt
|
|
1374
|
+
await this.refreshSystemPrompt?.(); // the conversation starts over: it may start from a freshly built system prompt
|
|
1197
1375
|
this.fileState.clear();
|
|
1198
1376
|
if (!this.isSubagent) this.checkpoints?.markConversationStale(); // the checkpoints are the main conversation's: a sub-agent's own compaction does not end them
|
|
1199
1377
|
this.lastContextTokens = estimateTokens(this.messages) + estimateTokens(this.toolSchemas()) + 2000;
|
package/src/agents.js
CHANGED
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { CONFIG_DIR } from './config.js';
|
|
7
|
+
import { CLAUDE_EFFORTS } from './api.js';
|
|
7
8
|
|
|
8
9
|
const READ_ONLY_TOOLS = ['Glob', 'Grep', 'Read', 'Bash', 'WebFetch', 'WebSearch', 'BashOutput'];
|
|
9
|
-
// The effort levels a Task call or an agent definition may ask for (as Claude Code's Agent tool takes them).
|
|
10
|
-
export const EFFORTS =
|
|
10
|
+
// The effort levels a Task call or an agent definition may ask for (as Claude Code's Agent tool takes them): Claude's.
|
|
11
|
+
export const EFFORTS = CLAUDE_EFFORTS;
|
|
11
12
|
|
|
12
13
|
export const BUILTIN_AGENTS = [
|
|
13
14
|
{
|