@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 +26 -2
- package/package.json +1 -1
- package/src/agent.js +239 -84
- 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/mcp.js +14 -0
- package/src/print.js +2 -1
- package/src/prompt-profiles.js +115 -0
- package/src/prompts.js +24 -15
- package/src/runtime.js +19 -11
- 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/src/work-state.js +62 -0
package/src/trace.js
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
// Low-overhead runtime telemetry. Trace records are deliberately structural: they keep
|
|
2
|
+
// fingerprints, counts and sizes, never prompts, tool arguments or tool output bodies.
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { projectDir } from './session.js';
|
|
8
|
+
|
|
9
|
+
const TRACE_VERSION = 1;
|
|
10
|
+
const DEFAULT_MAX_BYTES = 20 * 1024 * 1024;
|
|
11
|
+
const MAX_RECENT = 200;
|
|
12
|
+
const MAX_KEYS = 64;
|
|
13
|
+
|
|
14
|
+
const finite = (value, fallback = 0) => Number.isFinite(Number(value)) ? Number(value) : fallback;
|
|
15
|
+
const positive = (value, fallback = 0) => Math.max(0, finite(value, fallback));
|
|
16
|
+
const short = (value, max = 160) => String(value ?? '').slice(0, max);
|
|
17
|
+
|
|
18
|
+
export function fingerprintText(value) {
|
|
19
|
+
return crypto.createHash('sha1').update(String(value ?? '')).digest('hex').slice(0, 16);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// This is intentionally a shape, not a redacted copy. A password value or a file body must
|
|
23
|
+
// never reach the trace even if a future tool adds a new parameter.
|
|
24
|
+
export function inputShape(value, depth = 0) {
|
|
25
|
+
if (value === null) return { type: 'null' };
|
|
26
|
+
if (value === undefined) return { type: 'undefined' };
|
|
27
|
+
if (typeof value === 'string') return { type: 'string', chars: value.length };
|
|
28
|
+
if (typeof value === 'number') return { type: 'number' };
|
|
29
|
+
if (typeof value === 'boolean') return { type: 'boolean' };
|
|
30
|
+
if (Array.isArray(value)) return { type: 'array', length: value.length };
|
|
31
|
+
if (typeof value === 'object') {
|
|
32
|
+
const keys = Object.keys(value);
|
|
33
|
+
const result = { type: 'object', keys: keys.slice(0, MAX_KEYS), key_count: keys.length };
|
|
34
|
+
if (depth < 1) {
|
|
35
|
+
// Nested values are represented only by their type/size. This helps diagnose malformed
|
|
36
|
+
// requests without retaining a nested token, cookie, command or file body.
|
|
37
|
+
result.fields = Object.fromEntries(keys.slice(0, 16).map((key) => [key, inputShape(value[key], depth + 1)]));
|
|
38
|
+
}
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
return { type: typeof value };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function errorShape(error) {
|
|
45
|
+
if (!error) return null;
|
|
46
|
+
return {
|
|
47
|
+
name: short(error.name || 'Error', 80),
|
|
48
|
+
status: Number.isFinite(error.status) ? error.status : undefined,
|
|
49
|
+
retryable: typeof error.retryable === 'boolean' ? error.retryable : undefined,
|
|
50
|
+
overloaded: typeof error.overloaded === 'boolean' ? error.overloaded : undefined,
|
|
51
|
+
prompt_too_long: typeof error.promptTooLong === 'boolean' ? error.promptTooLong : undefined,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function outputStats(content) {
|
|
56
|
+
if (typeof content === 'string') return { chars: content.length, tokens_estimate: Math.ceil(content.length / 4) };
|
|
57
|
+
if (content == null) return { chars: 0, tokens_estimate: 0 };
|
|
58
|
+
if (Array.isArray(content)) {
|
|
59
|
+
const chars = content.reduce((n, block) => n + (typeof block?.text === 'string' ? block.text.length : 0), 0);
|
|
60
|
+
return { chars, tokens_estimate: Math.ceil(chars / 4), blocks: content.length };
|
|
61
|
+
}
|
|
62
|
+
return { chars: 0, tokens_estimate: 0 };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function emptyTool(name) {
|
|
66
|
+
return {
|
|
67
|
+
name,
|
|
68
|
+
calls: 0,
|
|
69
|
+
successes: 0,
|
|
70
|
+
failures: 0,
|
|
71
|
+
validation_errors: 0,
|
|
72
|
+
aborts: 0,
|
|
73
|
+
skipped: 0,
|
|
74
|
+
parallel_calls: 0,
|
|
75
|
+
duration_ms: 0,
|
|
76
|
+
output_chars: 0,
|
|
77
|
+
output_tokens_estimate: 0,
|
|
78
|
+
large_output_persisted: 0,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function cloneTool(tool) { return { ...tool }; }
|
|
83
|
+
|
|
84
|
+
export class RuntimeTrace {
|
|
85
|
+
constructor({ cwd = process.cwd(), sessionId = '', enabled = true, file = null, dir = null, maxBytes = DEFAULT_MAX_BYTES } = {}) {
|
|
86
|
+
this.cwd = cwd;
|
|
87
|
+
this.enabled = enabled !== false;
|
|
88
|
+
this.dir = dir ? path.resolve(dir) : path.join(projectDir(cwd), 'traces');
|
|
89
|
+
this.maxBytes = Math.max(100_000, finite(maxBytes, DEFAULT_MAX_BYTES));
|
|
90
|
+
this._explicitFile = file ? path.resolve(file) : null;
|
|
91
|
+
this._file = this._explicitFile;
|
|
92
|
+
this.sessionId = '';
|
|
93
|
+
this.sequence = 0;
|
|
94
|
+
this.turnSequence = 0;
|
|
95
|
+
this.requestSequence = 0;
|
|
96
|
+
this.toolSequence = 0;
|
|
97
|
+
this.turns = new Map();
|
|
98
|
+
this.requests = new Map();
|
|
99
|
+
this.tools = new Map();
|
|
100
|
+
this.recentEvents = [];
|
|
101
|
+
this.stats = this.newStats();
|
|
102
|
+
if (sessionId) this.setSessionId(sessionId);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
newStats() {
|
|
106
|
+
return {
|
|
107
|
+
turns: 0,
|
|
108
|
+
requests: 0,
|
|
109
|
+
request_successes: 0,
|
|
110
|
+
request_failures: 0,
|
|
111
|
+
input_tokens: 0,
|
|
112
|
+
output_tokens: 0,
|
|
113
|
+
cache_read_tokens: 0,
|
|
114
|
+
cache_write_tokens: 0,
|
|
115
|
+
cache_hits: 0,
|
|
116
|
+
cache_misses: 0,
|
|
117
|
+
compactions: 0,
|
|
118
|
+
compaction_failures: 0,
|
|
119
|
+
verification_runs: 0,
|
|
120
|
+
verification_passes: 0,
|
|
121
|
+
verification_failures: 0,
|
|
122
|
+
verification_aborts: 0,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
setSessionId(sessionId) {
|
|
127
|
+
const next = String(sessionId || '').trim();
|
|
128
|
+
if (next === this.sessionId && (this._file || !next)) return this.file;
|
|
129
|
+
this.sessionId = next;
|
|
130
|
+
this._file = this._explicitFile || (next ? path.join(this.dir, `${next}.jsonl`) : null);
|
|
131
|
+
this.turns.clear();
|
|
132
|
+
this.requests.clear();
|
|
133
|
+
this.tools.clear();
|
|
134
|
+
this.recentEvents = [];
|
|
135
|
+
this.stats = this.newStats();
|
|
136
|
+
return this.file;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
get file() { return this.enabled ? this._file : null; }
|
|
140
|
+
|
|
141
|
+
// All writes are best effort. Telemetry must not turn a successful agent request into a
|
|
142
|
+
// failed request because a project directory is read-only or has been removed.
|
|
143
|
+
append(type, fields = {}) {
|
|
144
|
+
if (!this.enabled) return null;
|
|
145
|
+
const record = {
|
|
146
|
+
schema_version: TRACE_VERSION,
|
|
147
|
+
type,
|
|
148
|
+
time: new Date().toISOString(),
|
|
149
|
+
session_id: this.sessionId,
|
|
150
|
+
...fields,
|
|
151
|
+
};
|
|
152
|
+
this.recentEvents.push(record);
|
|
153
|
+
if (this.recentEvents.length > MAX_RECENT) this.recentEvents.shift();
|
|
154
|
+
if (!this._file) return record;
|
|
155
|
+
try {
|
|
156
|
+
fs.mkdirSync(path.dirname(this._file), { recursive: true });
|
|
157
|
+
this.rotateIfNeeded();
|
|
158
|
+
fs.appendFileSync(this._file, JSON.stringify(record) + '\n');
|
|
159
|
+
} catch {
|
|
160
|
+
// A trace is observability, never a dependency of the coding agent.
|
|
161
|
+
}
|
|
162
|
+
return record;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
rotateIfNeeded() {
|
|
166
|
+
if (!this._file) return;
|
|
167
|
+
let size = 0;
|
|
168
|
+
try { size = fs.statSync(this._file).size; } catch { return; }
|
|
169
|
+
if (size < this.maxBytes) return;
|
|
170
|
+
const rotated = `${this._file}.1`;
|
|
171
|
+
try { fs.rmSync(rotated, { force: true }); } catch { /* best effort */ }
|
|
172
|
+
try { fs.renameSync(this._file, rotated); } catch { /* the next append may still work */ }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
turnStart({ agent = 'main', depth = 0, content = null } = {}) {
|
|
176
|
+
if (!this.enabled) return null;
|
|
177
|
+
const id = `turn_${Date.now().toString(36)}_${(++this.turnSequence).toString(36)}`;
|
|
178
|
+
const startedAt = Date.now();
|
|
179
|
+
const state = {
|
|
180
|
+
id,
|
|
181
|
+
agent: short(agent, 80),
|
|
182
|
+
depth: finite(depth),
|
|
183
|
+
startedAt,
|
|
184
|
+
requests: 0,
|
|
185
|
+
tools: new Map(),
|
|
186
|
+
compacted: false,
|
|
187
|
+
compactions: 0,
|
|
188
|
+
verifications: [],
|
|
189
|
+
usage: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 },
|
|
190
|
+
};
|
|
191
|
+
this.turns.set(id, state);
|
|
192
|
+
this.stats.turns++;
|
|
193
|
+
const blocks = Array.isArray(content) ? content : content == null ? [] : [content];
|
|
194
|
+
const textChars = blocks.reduce((n, b) => n + (typeof b === 'string' ? b.length : typeof b?.text === 'string' ? b.text.length : 0), 0);
|
|
195
|
+
this.append('turn_start', {
|
|
196
|
+
turn_id: id,
|
|
197
|
+
agent: state.agent,
|
|
198
|
+
depth: state.depth,
|
|
199
|
+
prompt_chars: textChars,
|
|
200
|
+
prompt_blocks: blocks.length,
|
|
201
|
+
});
|
|
202
|
+
return id;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
turnEnd({ turnId, finalStatus = 'completed', interrupted = false, rejected = false, error = null } = {}) {
|
|
206
|
+
if (!this.enabled || !turnId) return null;
|
|
207
|
+
const state = this.turns.get(turnId);
|
|
208
|
+
if (!state) return null;
|
|
209
|
+
const tools = [...state.tools.values()].map(cloneTool);
|
|
210
|
+
const record = this.append('turn_end', {
|
|
211
|
+
turn_id: turnId,
|
|
212
|
+
agent: state.agent,
|
|
213
|
+
depth: state.depth,
|
|
214
|
+
duration_ms: Math.max(0, Date.now() - state.startedAt),
|
|
215
|
+
final_status: short(finalStatus, 80),
|
|
216
|
+
interrupted: Boolean(interrupted),
|
|
217
|
+
rejected: Boolean(rejected),
|
|
218
|
+
error: errorShape(error),
|
|
219
|
+
requests: state.requests,
|
|
220
|
+
input_tokens: state.usage.input_tokens,
|
|
221
|
+
output_tokens: state.usage.output_tokens,
|
|
222
|
+
cache_read_tokens: state.usage.cache_read_input_tokens,
|
|
223
|
+
cache_write_tokens: state.usage.cache_creation_input_tokens,
|
|
224
|
+
compacted: state.compacted,
|
|
225
|
+
compactions: state.compactions,
|
|
226
|
+
verification: state.verifications,
|
|
227
|
+
tool_calls: tools,
|
|
228
|
+
});
|
|
229
|
+
this.turns.delete(turnId);
|
|
230
|
+
return record;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
requestStart({ turnId = null, agent = 'main', depth = 0, kind = 'turn', model = '', effort = null, context_tokens = 0, message_tokens = 0, system_tokens = 0, tool_tokens = 0, message_count = 0, cache = null, fingerprint = null, compaction_id = null } = {}) {
|
|
234
|
+
if (!this.enabled) return null;
|
|
235
|
+
const id = `request_${Date.now().toString(36)}_${(++this.requestSequence).toString(36)}`;
|
|
236
|
+
const state = this.turns.get(turnId);
|
|
237
|
+
const request = {
|
|
238
|
+
id,
|
|
239
|
+
turnId,
|
|
240
|
+
startedAt: Date.now(),
|
|
241
|
+
retries: 0,
|
|
242
|
+
rate_limit_waits: 0,
|
|
243
|
+
rate_limit_wait_ms: 0,
|
|
244
|
+
agent: short(agent, 80),
|
|
245
|
+
depth: finite(depth),
|
|
246
|
+
kind: short(kind, 40),
|
|
247
|
+
};
|
|
248
|
+
this.requests.set(id, request);
|
|
249
|
+
if (state) state.requests++;
|
|
250
|
+
this.append('request_start', {
|
|
251
|
+
request_id: id,
|
|
252
|
+
turn_id: turnId,
|
|
253
|
+
request_index: state?.requests || null,
|
|
254
|
+
agent: request.agent,
|
|
255
|
+
depth: request.depth,
|
|
256
|
+
kind: request.kind,
|
|
257
|
+
model: short(model, 160),
|
|
258
|
+
effort: effort == null ? null : short(effort, 40),
|
|
259
|
+
context_tokens: positive(context_tokens),
|
|
260
|
+
message_tokens: positive(message_tokens),
|
|
261
|
+
system_tokens: positive(system_tokens),
|
|
262
|
+
tool_tokens: positive(tool_tokens),
|
|
263
|
+
message_count: positive(message_count),
|
|
264
|
+
cache: cache && typeof cache === 'object' ? {
|
|
265
|
+
bucket: cache.bucket ? short(cache.bucket, 20) : undefined,
|
|
266
|
+
messages: cache.messages === undefined ? undefined : Boolean(cache.messages),
|
|
267
|
+
caching: cache.caching === undefined ? undefined : Boolean(cache.caching),
|
|
268
|
+
ttl: cache.ttl ? short(cache.ttl, 8) : undefined,
|
|
269
|
+
} : null,
|
|
270
|
+
prompt_fingerprint: fingerprint && typeof fingerprint === 'object' ? { ...fingerprint } : null,
|
|
271
|
+
compaction_id: compaction_id || null,
|
|
272
|
+
});
|
|
273
|
+
return request;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
requestEvent(handle, event) {
|
|
277
|
+
if (!this.enabled || !handle || !event) return;
|
|
278
|
+
if (event.type === 'retry') handle.retries++;
|
|
279
|
+
if (event.type === 'rate_limit_wait') {
|
|
280
|
+
handle.rate_limit_waits++;
|
|
281
|
+
handle.rate_limit_wait_ms += positive(event.delayMs || event.waitedMs);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
requestEnd(handle, { usage = {}, cache = null, model = '', stopReason = null, context_tokens = 0, error = null, cacheMiss = null } = {}) {
|
|
286
|
+
if (!this.enabled || !handle) return null;
|
|
287
|
+
const u = usage || {};
|
|
288
|
+
const ok = !error;
|
|
289
|
+
const read = positive(u.cache_read_input_tokens);
|
|
290
|
+
const write = positive(u.cache_creation_input_tokens);
|
|
291
|
+
const state = this.turns.get(handle.turnId);
|
|
292
|
+
const miss = cacheMiss ? { cause: short(cacheMiss.cause, 180), expected: positive(cacheMiss.expected), read: positive(cacheMiss.read) } : null;
|
|
293
|
+
const record = this.append('request_end', {
|
|
294
|
+
request_id: handle.id,
|
|
295
|
+
turn_id: handle.turnId,
|
|
296
|
+
request_index: state?.requests || null,
|
|
297
|
+
agent: handle.agent,
|
|
298
|
+
depth: handle.depth,
|
|
299
|
+
kind: handle.kind,
|
|
300
|
+
duration_ms: Math.max(0, Date.now() - handle.startedAt),
|
|
301
|
+
model: short(model, 160),
|
|
302
|
+
ok,
|
|
303
|
+
stop_reason: stopReason == null ? null : short(stopReason, 40),
|
|
304
|
+
error: errorShape(error),
|
|
305
|
+
retry_count: handle.retries,
|
|
306
|
+
rate_limit_waits: handle.rate_limit_waits,
|
|
307
|
+
rate_limit_wait_ms: handle.rate_limit_wait_ms,
|
|
308
|
+
context_tokens: positive(context_tokens),
|
|
309
|
+
input_tokens: positive(u.input_tokens),
|
|
310
|
+
output_tokens: positive(u.output_tokens),
|
|
311
|
+
cache_read_tokens: read,
|
|
312
|
+
cache_write_tokens: write,
|
|
313
|
+
cache_hit: read > 0,
|
|
314
|
+
cache_miss: miss,
|
|
315
|
+
cache: cache && typeof cache === 'object' ? {
|
|
316
|
+
caching: Boolean(cache.caching),
|
|
317
|
+
ttl: short(cache.ttl, 8),
|
|
318
|
+
fingerprint: cache.fingerprint && typeof cache.fingerprint === 'object' ? { ...cache.fingerprint } : null,
|
|
319
|
+
} : null,
|
|
320
|
+
});
|
|
321
|
+
this.requests.delete(handle.id);
|
|
322
|
+
this.stats.requests++;
|
|
323
|
+
if (ok) this.stats.request_successes++; else this.stats.request_failures++;
|
|
324
|
+
this.stats.input_tokens += positive(u.input_tokens);
|
|
325
|
+
this.stats.output_tokens += positive(u.output_tokens);
|
|
326
|
+
this.stats.cache_read_tokens += read;
|
|
327
|
+
this.stats.cache_write_tokens += write;
|
|
328
|
+
if (read > 0) this.stats.cache_hits++;
|
|
329
|
+
if (miss) this.stats.cache_misses++;
|
|
330
|
+
if (state) {
|
|
331
|
+
state.usage.input_tokens += positive(u.input_tokens);
|
|
332
|
+
state.usage.output_tokens += positive(u.output_tokens);
|
|
333
|
+
state.usage.cache_read_input_tokens += read;
|
|
334
|
+
state.usage.cache_creation_input_tokens += write;
|
|
335
|
+
}
|
|
336
|
+
return record;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
toolStart({ turnId = null, agent = 'main', depth = 0, name = '', input = null, parallel = false, toolUseId = null } = {}) {
|
|
340
|
+
if (!this.enabled) return null;
|
|
341
|
+
const id = `tool_${Date.now().toString(36)}_${(++this.toolSequence).toString(36)}`;
|
|
342
|
+
const handle = { id, turnId, name: short(name, 120), startedAt: Date.now(), parallel: Boolean(parallel), agent: short(agent, 80), depth: finite(depth) };
|
|
343
|
+
this.append('tool_start', {
|
|
344
|
+
tool_id: id,
|
|
345
|
+
tool_use_id: toolUseId || null,
|
|
346
|
+
turn_id: turnId,
|
|
347
|
+
agent: handle.agent,
|
|
348
|
+
depth: handle.depth,
|
|
349
|
+
tool: handle.name,
|
|
350
|
+
parallel: handle.parallel,
|
|
351
|
+
input: inputShape(input),
|
|
352
|
+
});
|
|
353
|
+
return handle;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
toolEnd(handle, { ok = false, error = false, validation_error = false, aborted = false, skipped = false, output = null, large_output_persisted = false, error_type = null } = {}) {
|
|
357
|
+
if (!this.enabled || !handle) return null;
|
|
358
|
+
const stats = this.tools.get(handle.name) || emptyTool(handle.name);
|
|
359
|
+
const out = outputStats(output);
|
|
360
|
+
const success = Boolean(ok) && !error && !aborted && !skipped;
|
|
361
|
+
stats.calls++;
|
|
362
|
+
if (success) stats.successes++; else stats.failures++;
|
|
363
|
+
if (validation_error) stats.validation_errors++;
|
|
364
|
+
if (aborted) stats.aborts++;
|
|
365
|
+
if (skipped) stats.skipped++;
|
|
366
|
+
if (handle.parallel) stats.parallel_calls++;
|
|
367
|
+
stats.duration_ms += Math.max(0, Date.now() - handle.startedAt);
|
|
368
|
+
stats.output_chars += out.chars;
|
|
369
|
+
stats.output_tokens_estimate += out.tokens_estimate;
|
|
370
|
+
if (large_output_persisted) stats.large_output_persisted++;
|
|
371
|
+
this.tools.set(handle.name, stats);
|
|
372
|
+
const state = this.turns.get(handle.turnId);
|
|
373
|
+
if (state) {
|
|
374
|
+
const turnTool = state.tools.get(handle.name) || emptyTool(handle.name);
|
|
375
|
+
turnTool.calls++;
|
|
376
|
+
if (success) turnTool.successes++; else turnTool.failures++;
|
|
377
|
+
if (validation_error) turnTool.validation_errors++;
|
|
378
|
+
if (aborted) turnTool.aborts++;
|
|
379
|
+
if (skipped) turnTool.skipped++;
|
|
380
|
+
if (handle.parallel) turnTool.parallel_calls++;
|
|
381
|
+
turnTool.duration_ms += Math.max(0, Date.now() - handle.startedAt);
|
|
382
|
+
turnTool.output_chars += out.chars;
|
|
383
|
+
turnTool.output_tokens_estimate += out.tokens_estimate;
|
|
384
|
+
if (large_output_persisted) turnTool.large_output_persisted++;
|
|
385
|
+
state.tools.set(handle.name, turnTool);
|
|
386
|
+
}
|
|
387
|
+
this.append('tool_end', {
|
|
388
|
+
tool_id: handle.id,
|
|
389
|
+
turn_id: handle.turnId,
|
|
390
|
+
agent: handle.agent,
|
|
391
|
+
depth: handle.depth,
|
|
392
|
+
tool: handle.name,
|
|
393
|
+
duration_ms: Math.max(0, Date.now() - handle.startedAt),
|
|
394
|
+
ok: success,
|
|
395
|
+
error: Boolean(error),
|
|
396
|
+
validation_error: Boolean(validation_error),
|
|
397
|
+
aborted: Boolean(aborted),
|
|
398
|
+
skipped: Boolean(skipped),
|
|
399
|
+
error_type: error_type ? short(error_type, 100) : null,
|
|
400
|
+
output_chars: out.chars,
|
|
401
|
+
output_tokens_estimate: out.tokens_estimate,
|
|
402
|
+
large_output_persisted: Boolean(large_output_persisted),
|
|
403
|
+
});
|
|
404
|
+
return stats;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
compact({ turnId = null, agent = 'main', depth = 0, auto = false, part = null, before_context_tokens = 0, after_context_tokens = 0, summary_chars = 0, work_state_valid = null, duration_ms = 0, error = null } = {}) {
|
|
408
|
+
if (!this.enabled) return null;
|
|
409
|
+
const state = this.turns.get(turnId);
|
|
410
|
+
if (!error) {
|
|
411
|
+
this.stats.compactions++;
|
|
412
|
+
if (state) { state.compacted = true; state.compactions++; }
|
|
413
|
+
} else this.stats.compaction_failures++;
|
|
414
|
+
return this.append('compaction', {
|
|
415
|
+
turn_id: turnId,
|
|
416
|
+
agent: short(agent, 80),
|
|
417
|
+
depth: finite(depth),
|
|
418
|
+
auto: Boolean(auto),
|
|
419
|
+
part: part || null,
|
|
420
|
+
before_context_tokens: positive(before_context_tokens),
|
|
421
|
+
after_context_tokens: positive(after_context_tokens),
|
|
422
|
+
summary_chars: positive(summary_chars),
|
|
423
|
+
work_state_valid: work_state_valid == null ? null : Boolean(work_state_valid),
|
|
424
|
+
duration_ms: positive(duration_ms),
|
|
425
|
+
ok: !error,
|
|
426
|
+
error: errorShape(error),
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
verification({ turnId = null, agent = 'main', depth = 0, command = '', attempt = 1, ok = false, aborted = false, output = '', duration_ms = 0, error = null } = {}) {
|
|
431
|
+
if (!this.enabled) return null;
|
|
432
|
+
const state = this.turns.get(turnId);
|
|
433
|
+
const result = {
|
|
434
|
+
attempt: positive(attempt, 1),
|
|
435
|
+
ok: Boolean(ok) && !aborted,
|
|
436
|
+
aborted: Boolean(aborted),
|
|
437
|
+
duration_ms: positive(duration_ms),
|
|
438
|
+
output_chars: typeof output === 'string' ? output.length : 0,
|
|
439
|
+
output_tokens_estimate: outputStats(output).tokens_estimate,
|
|
440
|
+
command_fingerprint: fingerprintText(command),
|
|
441
|
+
command_chars: String(command || '').length,
|
|
442
|
+
error: errorShape(error),
|
|
443
|
+
};
|
|
444
|
+
this.stats.verification_runs++;
|
|
445
|
+
if (result.aborted) this.stats.verification_aborts++;
|
|
446
|
+
else if (result.ok) this.stats.verification_passes++;
|
|
447
|
+
else this.stats.verification_failures++;
|
|
448
|
+
state?.verifications.push(result);
|
|
449
|
+
return this.append('verification', { turn_id: turnId, agent: short(agent, 80), depth: finite(depth), ...result });
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
summary() {
|
|
453
|
+
const tools = [...this.tools.values()].map((tool) => {
|
|
454
|
+
const calls = tool.calls || 0;
|
|
455
|
+
return { ...tool, success_rate: calls ? tool.successes / calls : null, avg_duration_ms: calls ? tool.duration_ms / calls : 0, avg_output_tokens_estimate: calls ? tool.output_tokens_estimate / calls : 0 };
|
|
456
|
+
});
|
|
457
|
+
const verificationTotal = this.stats.verification_runs;
|
|
458
|
+
return {
|
|
459
|
+
enabled: this.enabled,
|
|
460
|
+
file: this.file,
|
|
461
|
+
session_id: this.sessionId,
|
|
462
|
+
...this.stats,
|
|
463
|
+
cache_hit_rate: this.stats.requests ? this.stats.cache_hits / this.stats.requests : null,
|
|
464
|
+
verification_pass_rate: verificationTotal ? this.stats.verification_passes / verificationTotal : null,
|
|
465
|
+
tools,
|
|
466
|
+
recent_events: this.recentEvents.length,
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
recent(limit = 20) {
|
|
471
|
+
return this.recentEvents.slice(-Math.max(1, Math.min(200, Number(limit) || 20)));
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
close() {}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export const TRACE_DEFAULT_MAX_BYTES = DEFAULT_MAX_BYTES;
|
package/src/ui/repl.js
CHANGED
|
@@ -41,14 +41,14 @@ export const modelTag = (model) => String(model?.id ?? '').replace(/^claude-/, '
|
|
|
41
41
|
// The model and effort level that requests use now, for the footer and the terminal title. The effort
|
|
42
42
|
// is left out when none is sent (auto) and for a model that does not take one.
|
|
43
43
|
export function modelInfo(config) {
|
|
44
|
-
const model = config.
|
|
44
|
+
const model = config.model;
|
|
45
45
|
// What the requests carry: the nearest level the model takes (none goes out as low on gpt-6.1-sol, ultra as max on Claude).
|
|
46
46
|
const sent = effortToSend(config, model.id, config.effort);
|
|
47
47
|
const effort = sent && effortSupported(model.id) ? sent : null;
|
|
48
48
|
return { model: modelTag(model), effort };
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
// The
|
|
51
|
+
// The title model's answer about the topic (see topicTitlePrompt) as a clean title, or null when it is not
|
|
52
52
|
// a new topic or the answer cannot be used. `required`: there is no title yet, so any title will do.
|
|
53
53
|
export function parseTopicTitle(answer, { required = false } = {}) {
|
|
54
54
|
const json = /\{[\s\S]*\}/.exec(String(answer ?? ''))?.[0];
|
|
@@ -200,7 +200,7 @@ export class App {
|
|
|
200
200
|
this.rateWait = null; // {resumeAt, label, polling} while paused for a rate limit
|
|
201
201
|
this.exitArmed = 0;
|
|
202
202
|
this.notices = [];
|
|
203
|
-
this.topic = null; // what the conversation is about now, named by the
|
|
203
|
+
this.topic = null; // what the conversation is about now, named by the title model (see refreshTopic)
|
|
204
204
|
this.firstPrompt = null; // the session's first message: the title until there is a topic
|
|
205
205
|
this.topicSeq = 0; // topic requests sent ...
|
|
206
206
|
this.topicApplied = 0; // ... and the newest one whose answer was used
|
|
@@ -275,7 +275,7 @@ export class App {
|
|
|
275
275
|
process.on('SIGHUP', () => this.exit(129));
|
|
276
276
|
|
|
277
277
|
await this.startPeer();
|
|
278
|
-
this.runtime = await createRuntime({ cwd: this.cwd, flags: this.flags, io: this });
|
|
278
|
+
this.runtime = await createRuntime({ cwd: this.cwd, flags: this.flags, io: this, sessionId: this.store.id });
|
|
279
279
|
// The conversation's id, sent to the gateway with each request (see streamMessage); it follows /clear and /resume.
|
|
280
280
|
Object.defineProperty(this.runtime.config, 'sessionId', { get: () => this.store.id, configurable: true });
|
|
281
281
|
// Every request's cost (the conversation's, its sub-agents', side queries'), kept with the session.
|
|
@@ -341,7 +341,7 @@ export class App {
|
|
|
341
341
|
return new Promise((resolve) => { this.resolveExit = resolve; });
|
|
342
342
|
}
|
|
343
343
|
|
|
344
|
-
// What the session is about now: the
|
|
344
|
+
// What the session is about now: the current model named the topic last, or else the first thing asked
|
|
345
345
|
// (kept when the conversation is compacted afterwards). Cleared by /clear, replaced by /resume.
|
|
346
346
|
sessionLabel() {
|
|
347
347
|
if (this.customTitle) return this.customTitle;
|
|
@@ -364,7 +364,7 @@ export class App {
|
|
|
364
364
|
return null;
|
|
365
365
|
}
|
|
366
366
|
|
|
367
|
-
// Keep the title on the topic of the conversation: ask the
|
|
367
|
+
// Keep the title on the topic of the conversation: ask the current model, in the background, whether
|
|
368
368
|
// `message` starts a new topic and what to call it (as the official client does). Nothing waits for the
|
|
369
369
|
// answer, and when there is none (a rate limit, no network) the title just stays as it is.
|
|
370
370
|
refreshTopic(message) {
|
|
@@ -374,7 +374,7 @@ export class App {
|
|
|
374
374
|
const seq = ++this.topicSeq;
|
|
375
375
|
const current = this.topic;
|
|
376
376
|
quickQuery(this.config, {
|
|
377
|
-
model: this.config.
|
|
377
|
+
model: this.config.model, system: TOPIC_TITLE_SYSTEM, prompt: topicTitlePrompt(current, text.slice(0, 2000)), maxTokens: 2048,
|
|
378
378
|
}).then((answer) => {
|
|
379
379
|
// another session meanwhile, or an answer about a newer message already in use
|
|
380
380
|
if (store !== this.store || this.exiting || seq < this.topicApplied) return;
|
|
@@ -825,7 +825,7 @@ export class App {
|
|
|
825
825
|
queue: this.queue.map((q) => q.display ?? q.text),
|
|
826
826
|
dialog: this.remoteDialog(),
|
|
827
827
|
model,
|
|
828
|
-
effort: effort || defaultEffort(cfg.
|
|
828
|
+
effort: effort || defaultEffort(cfg.model.id, cfg),
|
|
829
829
|
title: this.sessionLabel() || path.basename(this.cwd),
|
|
830
830
|
cwd: (this.agent.cwd || this.cwd).replace(/\\/g, '/'),
|
|
831
831
|
name: this.peerLabel(),
|
|
@@ -834,7 +834,7 @@ export class App {
|
|
|
834
834
|
asking: this.dialogs.length > 0, // a question waits for an answer (the page reminds the user of it)
|
|
835
835
|
conversationId: this.store.id,
|
|
836
836
|
cost: Number(this.cost.toFixed(6)),
|
|
837
|
-
context: { used: this.contextUsed(), window: cfg.
|
|
837
|
+
context: { used: this.contextUsed(), window: cfg.model.contextWindow },
|
|
838
838
|
background: this.backgroundWork(),
|
|
839
839
|
kind: this.headless ? 'background' : 'terminal',
|
|
840
840
|
};
|
|
@@ -924,7 +924,7 @@ export class App {
|
|
|
924
924
|
const cfg = this.config;
|
|
925
925
|
const [models, efforts] = await Promise.all([modelChoices(cfg), effortChoices(cfg)]);
|
|
926
926
|
const { effort } = modelInfo(cfg);
|
|
927
|
-
return { model: cfg.
|
|
927
|
+
return { model: cfg.model.id, models, effort: effort || defaultEffort(cfg.model.id, cfg), efforts: efforts.options };
|
|
928
928
|
}
|
|
929
929
|
|
|
930
930
|
// For the page's input box: what the input box here would suggest (/commands, @files, &sessions), in plain text,
|
|
@@ -1248,7 +1248,7 @@ export class App {
|
|
|
1248
1248
|
const w = Math.min(this.width - 1, 76);
|
|
1249
1249
|
const inner = w - 4;
|
|
1250
1250
|
const row = (s) => c.claude('│') + ' ' + padEnd(truncate(s, inner), inner) + ' ' + c.claude('│');
|
|
1251
|
-
const model = cfg.
|
|
1251
|
+
const model = cfg.model;
|
|
1252
1252
|
const lines = [
|
|
1253
1253
|
c.claude('╭' + '─'.repeat(w - 2) + '╮'),
|
|
1254
1254
|
row(`${c.claude('✻')} Welcome to ${c.bold(APP_NAME)}! ${c.dim(`v${VERSION} · a command line coding agent`)}`),
|
|
@@ -1909,6 +1909,7 @@ export class App {
|
|
|
1909
1909
|
this.previousSession = null; // the conversation before a /clear: resuming another one ends the offer
|
|
1910
1910
|
this.seedOutput = [];
|
|
1911
1911
|
this.store = new SessionStore(this.cwd, id);
|
|
1912
|
+
this.runtime.trace?.setSessionId(id);
|
|
1912
1913
|
this.peers?.update(); // the conversation, in the registry
|
|
1913
1914
|
this.topic = loaded.topic;
|
|
1914
1915
|
this.customTitle = loaded.name;
|
|
@@ -1957,6 +1958,7 @@ export class App {
|
|
|
1957
1958
|
|
|
1958
1959
|
newSession() {
|
|
1959
1960
|
this.store = new SessionStore(this.cwd);
|
|
1961
|
+
this.runtime.trace?.setSessionId(this.store.id);
|
|
1960
1962
|
this.peers?.update();
|
|
1961
1963
|
this.seedOutput = [];
|
|
1962
1964
|
this.topic = null;
|
|
@@ -2401,7 +2403,7 @@ export class App {
|
|
|
2401
2403
|
else if (this.pendingUpdate) left += c.dim(' · ') + c.dim(`update ${this.pendingUpdate} ready · ${this.updateWaitingFor ? `installs when &${this.updateWaitingFor.split(',')[0]} is idle` : 'installs when idle'}`);
|
|
2402
2404
|
}
|
|
2403
2405
|
const cfg = this.config;
|
|
2404
|
-
const threshold = cfg.autoCompactThreshold(cfg.
|
|
2406
|
+
const threshold = cfg.autoCompactThreshold(cfg.model);
|
|
2405
2407
|
const used = this.agent.contextEstimate;
|
|
2406
2408
|
let notice = '';
|
|
2407
2409
|
const pctLeft = Math.max(0, Math.round((1 - used / threshold) * 100));
|
|
@@ -2412,7 +2414,7 @@ export class App {
|
|
|
2412
2414
|
// and the notice alone when they do not (a context warning matters more than the model's name).
|
|
2413
2415
|
const { model, effort } = modelInfo(cfg);
|
|
2414
2416
|
// An effort that is not set is not sent: the API then uses the model's default, which is shown instead.
|
|
2415
|
-
const level = effort || defaultEffort(cfg.
|
|
2417
|
+
const level = effort || defaultEffort(cfg.model.id, cfg);
|
|
2416
2418
|
const info = c.dim(level ? `${model} · effort ${level}` : model);
|
|
2417
2419
|
// Before the model: the prompt cache clock, then what the conversation has cost so far; when room is short
|
|
2418
2420
|
// the cost goes first, then the clock.
|
package/src/ui/screen.js
CHANGED
|
@@ -154,6 +154,7 @@ export class Screen {
|
|
|
154
154
|
this.wrapped = []; // fullscreen: history[i] wrapped to wrapCols - 1, made when first needed
|
|
155
155
|
this.wrapCols = 0;
|
|
156
156
|
this.lastArea = 0; // fullscreen: rows the conversation had on screen at the last draw
|
|
157
|
+
this.scrollLiveRows = null; // fullscreen: keep the live region's height fixed while the user is scrolled up
|
|
157
158
|
this.viewMap = []; // fullscreen: what each row of the conversation area shows, {line, sub} (null: blank)
|
|
158
159
|
this.barRow = null; // fullscreen: the row of the "Jump to bottom" bar, when it is shown
|
|
159
160
|
this.finding = null; // fullscreen: a search in the conversation (ctrl+f), see openFind
|
|
@@ -572,13 +573,43 @@ export class Screen {
|
|
|
572
573
|
return ' '.repeat(pad) + '\x1b[7m' + label + '\x1b[27m';
|
|
573
574
|
}
|
|
574
575
|
|
|
576
|
+
// While the user is scrolled up, keep the live region at the height it had when scrolling started. Streaming
|
|
577
|
+
// text otherwise grows and shrinks that region, moving every visible conversation row on every token. That is
|
|
578
|
+
// especially conspicuous through PowerShell/ConPTY, where the cursor moves in the terminal before the whole
|
|
579
|
+
// frame has been painted. The new output remains available behind the jump bar; returning to the bottom releases
|
|
580
|
+
// the lock and lays out the complete live region again.
|
|
581
|
+
keepScrolledLiveHeight(layout, rows) {
|
|
582
|
+
const current = layout.rows.length;
|
|
583
|
+
if (current < rows) {
|
|
584
|
+
const gap = rows - current;
|
|
585
|
+
layout.rows.unshift(...Array(gap).fill(''));
|
|
586
|
+
if (layout.cursorRow !== null) layout.cursorRow += gap;
|
|
587
|
+
return layout;
|
|
588
|
+
}
|
|
589
|
+
if (current > rows) {
|
|
590
|
+
const dropped = current - rows;
|
|
591
|
+
layout.rows.splice(0, dropped);
|
|
592
|
+
if (layout.cursorRow !== null) {
|
|
593
|
+
layout.cursorRow -= dropped;
|
|
594
|
+
if (layout.cursorRow < 0) layout.cursorRow = null;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return layout;
|
|
598
|
+
}
|
|
599
|
+
|
|
575
600
|
// Draw the screen: the conversation above, the live region on the last rows, the cursor in the input box.
|
|
576
601
|
draw({ full = false } = {}) {
|
|
577
602
|
if (this.closed || !this.full) return;
|
|
578
603
|
if (this.scheduled) { clearTimeout(this.scheduled); this.scheduled = null; }
|
|
579
604
|
const cols = this.width;
|
|
580
605
|
const screenRows = Math.max(1, this.out.rows || this.height);
|
|
581
|
-
|
|
606
|
+
if (!this.scroll) this.scrollLiveRows = null;
|
|
607
|
+
else if (full) this.scrollLiveRows = null; // a resize changes wrapping; capture the new live layout below
|
|
608
|
+
let layout = this.layoutLive(cols);
|
|
609
|
+
if (this.scroll > 0) {
|
|
610
|
+
if (this.scrollLiveRows === null) this.scrollLiveRows = Math.max(1, layout.rows.length);
|
|
611
|
+
layout = this.keepScrolledLiveHeight(layout, this.scrollLiveRows);
|
|
612
|
+
}
|
|
582
613
|
const area = Math.max(0, screenRows - layout.rows.length);
|
|
583
614
|
this.lastArea = area;
|
|
584
615
|
if (this.finding) this.refreshFind();
|