@yanzc/claude-pro 0.7.4 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/commands.js CHANGED
@@ -15,7 +15,8 @@ import { listBackgroundShells } from './tools/bash.js';
15
15
  import { estimateTokens } from './agent.js';
16
16
  import { quickQuery, cacheRefusals, defaultEffort, effortToSend, CLAUDE_EFFORTS } from './api.js';
17
17
  import { hasRipgrep } from './utils/shell.js';
18
- import { displayPath } from './utils/paths.js';
18
+ import { displayPath, resolvePath } from './utils/paths.js';
19
+ import { activePromptName, listPromptProfiles, loadActivePrompt, promptDirectory, promptNameForText, savePrompt, setActivePrompt } from './prompt-profiles.js';
19
20
  import { cleanName, machineName } from './peers.js';
20
21
  import { rewind, promptAt } from './checkpoints.js';
21
22
  import { canRestart, runSelfCheck } from './restart.js';
@@ -54,7 +55,7 @@ export async function modelChoices(cfg) {
54
55
  // What /effort offers for the current model: {levels, options: [{value, label, description}]} in plain text (the
55
56
  // levels, auto, default).
56
57
  export async function effortChoices(cfg) {
57
- const id = cfg.mainModel.id;
58
+ const id = cfg.model.id;
58
59
  let info = null;
59
60
  if (cfg.usesGateway && isGpt(id)) {
60
61
  const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
@@ -92,14 +93,14 @@ export function buildCommands(app) {
92
93
  const reloadConfig = () => {
93
94
  const fresh = loadConfig({ cwd: app.cwd, flags: app.flags });
94
95
  const cfg = app.runtime.config;
95
- const model = cfg.mainModel.id;
96
+ const model = cfg.model.id;
96
97
  cfg.env = fresh.env;
97
98
  cfg.sources = fresh.sources;
98
99
  cfg.settings = fresh.settings;
99
100
  // What the system prompt is built from may have changed (memory switched off, say). It is not rebuilt in the
100
101
  // middle of a conversation, which would lose its prompt cache; it is, at the next /clear or compaction. A
101
102
  // different model is the exception: the prompt names it, and the new model has a cache of its own anyway.
102
- if (cfg.mainModel.id !== model) app.runtime.invalidateSystemPrompt();
103
+ if (cfg.model.id !== model) app.runtime.invalidateSystemPrompt();
103
104
  else app.runtime.deferSystemPromptRefresh();
104
105
  };
105
106
 
@@ -119,6 +120,91 @@ export function buildCommands(app) {
119
120
  return choice === 'yes';
120
121
  };
121
122
 
123
+ const unquotePromptArgument = (args) => {
124
+ const value = String(args ?? '').trim();
125
+ return /^(["'])[\s\S]*\1$/.test(value) ? value.slice(1, -1).trim() : value;
126
+ };
127
+
128
+ // `/prompt` accepts either an existing file or literal text. Files are copied into the user's prompt directory so
129
+ // changing or deleting the source later does not change the prompt used by future sessions.
130
+ const readPromptArgument = (args) => {
131
+ const value = unquotePromptArgument(args);
132
+ if (!value) throw new Error('Usage: /prompt <file|text>');
133
+ const file = resolvePath(value, app.cwd);
134
+ let stat = null;
135
+ try { stat = fs.statSync(file); } catch (e) { if (e.code !== 'ENOENT') throw e; }
136
+ if (stat) {
137
+ if (!stat.isFile()) throw new Error(`Prompt source is not a file: ${file}`);
138
+ const text = fs.readFileSync(file, 'utf8');
139
+ if (!text.trim()) throw new Error(`Prompt source is empty: ${file}`);
140
+ return { name: path.basename(file), text, source: file };
141
+ }
142
+ return { name: promptNameForText(value), text: value, source: null };
143
+ };
144
+
145
+ const promptChanged = (name, text = undefined) => {
146
+ const currentName = activePromptName();
147
+ if (currentName !== name) return true;
148
+ if (text === undefined) return false;
149
+ return loadActivePrompt()?.text !== text;
150
+ };
151
+
152
+ const activatePrompt = async (name, { text, saved = null } = {}) => {
153
+ const changed = promptChanged(name, text);
154
+ if (!changed) {
155
+ out(`System prompt is already ${name ? c.bold(name) : c.bold('the built-in default')}.`);
156
+ return false;
157
+ }
158
+ if (!(await confirmCacheLoss('Changing the system prompt'))) {
159
+ out(c.dim('The system prompt was not changed.'));
160
+ return false;
161
+ }
162
+ const stored = saved ? savePrompt(saved.name, saved.text, { activate: true }) : null;
163
+ if (!saved) setActivePrompt(name);
164
+ // A prompt choice is persistent, but also takes effect for the next request in this session. The cache check
165
+ // above is the same safeguard used by /model and /effort when changing request-level cache inputs.
166
+ app.runtime.invalidateSystemPrompt();
167
+ const label = name ? c.bold(name) : c.bold('the built-in default');
168
+ const location = stored ? ` · copied to ${displayPath(stored.file, app.cwd)}` : '';
169
+ out(`System prompt set to ${label}${location} · kept for later sessions${promptDirectory() ? c.dim(` (${promptDirectory()})`) : ''}`);
170
+ return true;
171
+ };
172
+
173
+ const choosePrompt = async (args = '') => {
174
+ const wanted = unquotePromptArgument(args);
175
+ const profiles = listPromptProfiles();
176
+ const current = activePromptName();
177
+ if (wanted) {
178
+ if (/^(default|none|off)$/i.test(wanted)) return activatePrompt(null);
179
+ const found = profiles.find((p) => p.name === wanted) || profiles.find((p) => p.name.toLowerCase() === wanted.toLowerCase());
180
+ if (!found) {
181
+ out(c.red(`No saved prompt named "${wanted}". Use /prompts to choose one, or /prompt <file|text> to save it.`));
182
+ return false;
183
+ }
184
+ return activatePrompt(found.name);
185
+ }
186
+ if (!profiles.length) {
187
+ out(c.dim(`No saved prompts. Use /prompt <file|text> to create one (saved in ${promptDirectory()}).`));
188
+ return false;
189
+ }
190
+ const options = [
191
+ { label: `Built-in default${current ? '' : c.dim(' (active)')}`, value: '__default__', description: 'Use claude-pro\'s normal system prompt' },
192
+ ...profiles.map((p) => ({
193
+ label: `${p.name}${p.name === current ? c.dim(' (active)') : ''}`,
194
+ value: p.name,
195
+ description: p.preview || `${p.size} bytes`,
196
+ })),
197
+ ];
198
+ const selected = await app.showDialog(new SelectDialog({
199
+ title: 'Select system prompt',
200
+ question: `Saved prompts in ${promptDirectory()}`,
201
+ options,
202
+ selected: Math.max(0, current ? options.findIndex((o) => o.value === current) : 0),
203
+ }));
204
+ if (selected === null || selected === undefined) return false;
205
+ return activatePrompt(selected === '__default__' ? null : selected);
206
+ };
207
+
122
208
  add({
123
209
  name: 'help',
124
210
  description: 'Show help and available commands',
@@ -273,6 +359,27 @@ export function buildCommands(app) {
273
359
  },
274
360
  });
275
361
 
362
+ add({
363
+ name: 'prompt',
364
+ aliases: ['promt'],
365
+ argHint: '<file|text>',
366
+ argRequired: true,
367
+ description: 'Save and use a system prompt from a file or literal text (kept for later sessions)',
368
+ async run(args) {
369
+ if (!unquotePromptArgument(args)) return choosePrompt('');
370
+ const source = readPromptArgument(args);
371
+ return activatePrompt(source.name, { text: source.text, saved: source });
372
+ },
373
+ });
374
+
375
+ add({
376
+ name: 'prompts',
377
+ aliases: ['promits', 'promts'],
378
+ argHint: '[name|default]',
379
+ description: 'Choose a saved system prompt, or return to the built-in default',
380
+ run(args) { return choosePrompt(args); },
381
+ });
382
+
276
383
  add({
277
384
  name: 'model',
278
385
  argHint: '[model]',
@@ -282,17 +389,17 @@ export function buildCommands(app) {
282
389
  let choice = args.trim();
283
390
  if (!choice) {
284
391
  const opts = (await modelChoices(cfg)).map((o) => ({ label: `${o.label}${o.description ? ` ${c.dim(o.description.startsWith('→') ? o.description : `(${o.description})`)}` : ''}`, value: o.value }));
285
- choice = await app.showDialog(new SelectDialog({ title: 'Select model', question: `Current: ${c.bold(cfg.mainModel.label)}. Any name works too: /model <name>`, options: opts }));
392
+ choice = await app.showDialog(new SelectDialog({ title: 'Select model', question: `Current: ${c.bold(cfg.model.label)}. Any name works too: /model <name>`, options: opts }));
286
393
  if (!choice) return;
287
394
  }
288
395
  const forget = choice === '__default__' || choice === 'default';
289
396
  const next = cfg.resolveModel(forget ? cfg.configuredModelSpec : choice).id;
290
- const changed = next !== cfg.mainModel.id;
397
+ const changed = next !== cfg.model.id;
291
398
  if (changed && !(await confirmCacheLoss('Switching the model', { model: next }))) { out(c.dim('The model was not changed.')); return; }
292
399
  cfg.modelOverride = forget ? null : choice;
293
400
  if (changed) app.runtime.invalidateSystemPrompt(); // the prompt names the model; the new model starts a cache of its own anyway
294
401
  const kept = keep(cfg, { model: cfg.modelOverride }, forget);
295
- out(`Model set to ${c.bold(cfg.mainModel.label)} ${c.dim(`(${formatTokens(cfg.mainModel.contextWindow)} context)`)}${kept}`);
402
+ out(`Model set to ${c.bold(cfg.model.label)} ${c.dim(`(${formatTokens(cfg.model.contextWindow)} context)`)}${kept}`);
296
403
  },
297
404
  });
298
405
 
@@ -301,12 +408,12 @@ export function buildCommands(app) {
301
408
  get argHint() {
302
409
  const cfg = app.runtime.config;
303
410
  const login = cfg.usesGateway ? gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) : null;
304
- return `[${effortLevels(cfg.mainModel.id, cachedGatewayModel(login, cfg.mainModel.id)).join('|')}|auto|default]`;
411
+ return `[${effortLevels(cfg.model.id, cachedGatewayModel(login, cfg.model.id)).join('|')}|auto|default]`;
305
412
  },
306
413
  description: 'Set reasoning effort (output_config.effort; kept for later sessions)',
307
414
  async run(args) {
308
415
  const cfg = app.runtime.config;
309
- const id = cfg.mainModel.id;
416
+ const id = cfg.model.id;
310
417
  const { levels, options } = await effortChoices(cfg);
311
418
  let choice = args.trim().toLowerCase();
312
419
  if (!choice) {
@@ -344,13 +451,13 @@ export function buildCommands(app) {
344
451
  const set = (f) => updateSettingsFile(f, (json) => { json.env = { ...(json.env || {}), CLAUDE_PRO_PROVIDER: provider }; });
345
452
  set(files.user); // the default for the other projects too
346
453
  if (file !== files.user) set(file);
347
- const model = cfg.mainModel.id;
454
+ const model = cfg.model.id;
348
455
  reloadConfig();
349
456
  cfg.modelOverride = null;
350
457
  cfg.effortOverride = null;
351
458
  cfg.effortBoost = null;
352
459
  applyRememberedChoices(cfg, app.flags);
353
- if (cfg.mainModel.id !== model) app.runtime.invalidateSystemPrompt();
460
+ if (cfg.model.id !== model) app.runtime.invalidateSystemPrompt();
354
461
  if (cfg.provider !== provider) return c.red(` · NOT switched: CLAUDE_PRO_PROVIDER=${cfg.provider} is set by ${cfg.sources.CLAUDE_PRO_PROVIDER}, which overrides the settings files; change it there`);
355
462
  return file !== files.user ? c.dim(` · also saved in ${displayPath(file, app.cwd)}, which overrides the user settings in this project`) : '';
356
463
  };
@@ -382,7 +489,7 @@ export function buildCommands(app) {
382
489
  try {
383
490
  const account = await fetchGatewayAccount(saved);
384
491
  const note = switchProvider('gateway');
385
- out([`Using the gateway ${c.bold(url)}: ${cfg.mainModel.label}${note}`, accountLine(account), c.dim(`Top up and usage: ${url}/user · another account: /logout, then /login`)]);
492
+ out([`Using the gateway ${c.bold(url)}: ${cfg.model.label}${note}`, accountLine(account), c.dim(`Top up and usage: ${url}/user · another account: /logout, then /login`)]);
386
493
  await goOnline();
387
494
  return;
388
495
  } catch (e) {
@@ -400,7 +507,7 @@ export function buildCommands(app) {
400
507
  onUrl: (page) => out([`Opening the gateway login in your browser. If it does not open, visit:`, c.blue(page), c.dim('Waiting for the browser (10 minutes at most)…')]),
401
508
  });
402
509
  const note = switchProvider('gateway');
403
- out([`Logged in to the gateway ${c.bold(url)}: ${cfg.mainModel.label}${note}`, accountLine(login.balance || login.account), c.dim(`Top up and usage: ${url}/user`)]);
510
+ out([`Logged in to the gateway ${c.bold(url)}: ${cfg.model.label}${note}`, accountLine(login.balance || login.account), c.dim(`Top up and usage: ${url}/user`)]);
404
511
  await goOnline();
405
512
  } catch (e) {
406
513
  if (e.name !== 'AbortError') out(c.red(`Gateway login failed: ${e.message}`));
@@ -430,6 +537,7 @@ export function buildCommands(app) {
430
537
  run() {
431
538
  const cfg = app.runtime.config;
432
539
  const mem = memoryFiles(app.cwd);
540
+ const savedPrompt = loadActivePrompt();
433
541
  const mcp = app.runtime.mcp.status();
434
542
  const row = (k, v) => `${c.dim(padEnd(k, 18))} ${v}`;
435
543
  log([
@@ -440,12 +548,13 @@ export function buildCommands(app) {
440
548
  row('Provider', cfg.provider),
441
549
  row('Endpoint', cfg.endpointLabel),
442
550
  row('Auth', gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? `gateway key of ${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)')),
443
- row('Model', `${cfg.mainModel.label} ${c.dim(`(sent as "${cfg.mainModel.id}", ${formatTokens(cfg.mainModel.contextWindow)} context)`)}`),
444
- row('Sub-agent model', cfg.subagentModelChosen ? `chosen per task by difficulty ${c.dim(`(haiku, sonnet or opus; not chosen: ${cfg.subagentModel.label})`)}` : cfg.subagentModel.label),
445
- row('Small model', cfg.smallModel.label),
551
+ row('Model', `${cfg.model.label} ${c.dim(`(sent as "${cfg.model.id}", ${formatTokens(cfg.model.contextWindow)} context)`)}`),
446
552
  row('Effort', cfg.effort || 'auto'),
553
+ row('System prompt', app.flags.systemPrompt !== undefined
554
+ ? 'command line override'
555
+ : savedPrompt?.text != null ? `${savedPrompt.name} (saved)` : savedPrompt?.error ? `${savedPrompt.name} (missing; using built-in)` : 'built-in default'),
447
556
  row('Max output', formatTokens(cfg.maxOutputTokens)),
448
- row('Prompt cache', cfg.promptCachingDisabled(cfg.mainModel.id) ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.mainModel.id).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.mainModel.id).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
557
+ row('Prompt cache', cfg.promptCachingDisabled(cfg.model.id) ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.model.id).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.model.id).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
449
558
  row('Auto-compact', cfg.autoCompactEnabled ? `at ${formatTokens(cfg.autoCompactThreshold())} tokens (window ${formatTokens(cfg.compactWindow())})` : 'disabled'),
450
559
  row('Access', 'full (no permission prompts)'),
451
560
  row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
@@ -482,12 +591,16 @@ export function buildCommands(app) {
482
591
  const u = a.totalUsage();
483
592
  const b = a.subUsage;
484
593
  const cacheLines = a.cache.describe();
594
+ const trace = a.trace?.summary();
595
+ const toolCalls = trace?.tools?.reduce((n, item) => n + item.calls, 0) || 0;
596
+ const toolSuccesses = trace?.tools?.reduce((n, item) => n + item.successes, 0) || 0;
485
597
  out([
486
598
  `Total cost: ${formatUsd(app.cost)} ${c.dim('for this conversation, at list prices (sub-agents, compaction and side requests included)')}`,
487
599
  `Total input: ${formatTokens(u.input + u.cacheRead + u.cacheWrite)} tokens ${c.dim(`(${formatTokens(u.cacheRead)} cache read, ${formatTokens(u.cacheWrite)} cache write${u.cacheWrite1h ? `, ${formatTokens(u.cacheWrite1h)} of it for 1 hour` : ''})`)}`,
488
600
  `Total output: ${formatTokens(u.output)} tokens`,
489
601
  `API requests: ${u.requests}${u.compactions ? c.dim(` + ${u.compactions} to compact the conversation`) : ''}`,
490
602
  ...cacheLines.map((line, i) => (i ? c.dim(line) : line)),
603
+ ...(trace ? [`Trace: ${trace.requests} requests · ${toolCalls} tool calls${toolCalls ? ` · ${Math.round((toolSuccesses / toolCalls) * 100)}% tool success` : ''} · ${trace.compactions} compactions · ${trace.verification_runs} verifications`] : []),
491
604
  ...(b.runs ? [c.dim(`Sub-agents: ${b.runs} run${b.runs === 1 ? '' : 's'}, ${b.requests + b.compactions} request${b.requests + b.compactions === 1 ? '' : 's'}, ${formatTokens(b.input + b.cacheRead + b.cacheWrite)} input (${formatTokens(b.cacheRead)} cached), ${formatTokens(b.output)} output; included in the totals`)] : []),
492
605
  `Session time: ${formatDuration(Date.now() - app.sessionStart)}`,
493
606
  ]);
@@ -506,13 +619,43 @@ export function buildCommands(app) {
506
619
  },
507
620
  });
508
621
 
622
+ add({
623
+ name: 'trace',
624
+ argHint: '[recent count]',
625
+ description: 'Show runtime quality metrics and the privacy-preserving trace file',
626
+ run(args) {
627
+ const trace = app.runtime.trace;
628
+ if (!trace) { out(c.dim('Runtime trace is unavailable.')); return; }
629
+ const summary = trace.summary();
630
+ const lines = [
631
+ `Trace file: ${summary.file || c.dim('(not persisted: no session id)')}`,
632
+ `Enabled: ${summary.enabled ? 'yes' : 'no'}`,
633
+ `Turns: ${summary.turns}`,
634
+ `Requests: ${summary.requests} (${summary.request_successes} succeeded, ${summary.request_failures} failed)`,
635
+ `Cache: ${summary.cache_hits} hits${summary.cache_misses ? `, ${summary.cache_misses} misses` : ''}${summary.cache_hit_rate == null ? '' : ` (${Math.round(summary.cache_hit_rate * 100)}% request hit rate)`}`,
636
+ `Compactions: ${summary.compactions}${summary.compaction_failures ? ` (${summary.compaction_failures} failed)` : ''}`,
637
+ `Verification: ${summary.verification_runs}${summary.verification_runs ? ` (${Math.round((summary.verification_pass_rate || 0) * 100)}% passed)` : ''}`,
638
+ ];
639
+ if (summary.tools.length) {
640
+ lines.push('', 'Tools:');
641
+ for (const tool of summary.tools) lines.push(` ${padEnd(tool.name, 18)} ${tool.calls} calls · ${Math.round((tool.success_rate || 0) * 100)}% success · ${Math.round(tool.avg_duration_ms)}ms avg · ${formatTokens(tool.output_tokens_estimate)} output tokens est.`);
642
+ }
643
+ const count = Math.max(0, Math.min(50, parseInt(args, 10) || 0));
644
+ if (count) {
645
+ lines.push('', `Recent events (${count}):`);
646
+ lines.push(...trace.recent(count).map((event) => c.dim(JSON.stringify(event))));
647
+ }
648
+ out(lines);
649
+ },
650
+ });
651
+
509
652
  add({
510
653
  name: 'context',
511
654
  description: 'Show context window usage',
512
655
  run() {
513
656
  const cfg = app.runtime.config;
514
657
  const a = app.agent;
515
- const window = cfg.mainModel.contextWindow;
658
+ const window = cfg.model.contextWindow;
516
659
  const threshold = cfg.autoCompactThreshold();
517
660
  const sys = estimateTokens(app.runtime.systemPrompt());
518
661
  const tools = estimateTokens(a.toolSchemas());
@@ -567,12 +710,12 @@ export function buildCommands(app) {
567
710
  add({
568
711
  name: 'verify',
569
712
  argHint: '[command|off]',
570
- description: 'Run a command (e.g. npm test) after turns that edit files; failures go back to the agent',
713
+ description: 'Run a command (e.g. npm test) after turns that edit files; auto-detects project tests when available; failures go back to the agent',
571
714
  run(args) {
572
715
  const cfg = app.runtime.config;
573
716
  if (args.trim()) cfg.verifyOverride = args.trim();
574
717
  out(cfg.verifyCommand
575
- ? `Verify command: ${c.bold(cfg.verifyCommand)} ${c.dim(`(up to ${cfg.verifyMaxRounds} fix rounds; /verify off to disable)`)}`
718
+ ? `Verify command: ${c.bold(cfg.verifyCommand)} ${c.dim(`(${cfg.verifyCommandAuto ? 'auto-detected; ' : ''}up to ${cfg.verifyMaxRounds} fix rounds; /verify off to disable)`)}`
576
719
  : c.dim('Verification is off. Turn it on with /verify <command>, --verify <command> or CLAUDE_PRO_VERIFY_COMMAND.'));
577
720
  },
578
721
  });
@@ -864,8 +1007,8 @@ export function buildCommands(app) {
864
1007
  app.controller = new AbortController();
865
1008
  const started = Date.now();
866
1009
  try {
867
- const reply = await quickQuery(cfg, { model: cfg.mainModel, system: 'Reply with exactly: pong', prompt: 'ping', maxTokens: 200, signal: app.controller.signal, waitForRateLimit: false });
868
- out(`${c.green('✔')} ${cfg.endpointLabel} · model ${cfg.mainModel.id} replied "${truncate(reply, 40)}" in ${Date.now() - started}ms`);
1010
+ const reply = await quickQuery(cfg, { model: cfg.model, system: 'Reply with exactly: pong', prompt: 'ping', maxTokens: 200, signal: app.controller.signal, waitForRateLimit: false });
1011
+ out(`${c.green('✔')} ${cfg.endpointLabel} · model ${cfg.model.id} replied "${truncate(reply, 40)}" in ${Date.now() - started}ms`);
869
1012
  } catch (e) {
870
1013
  out(`${c.red('✘')} API request failed: ${e.message}`);
871
1014
  } finally {
package/src/config.js CHANGED
@@ -15,6 +15,7 @@ import path from 'node:path';
15
15
  import os from 'node:os';
16
16
  import { fileURLToPath } from 'node:url';
17
17
  import { normalizeTtl } from './cache.js';
18
+ import { discoverVerifyCommand } from './verify.js';
18
19
 
19
20
  export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
20
21
  // A source checkout (a git clone, also when npm links to one), as opposed to a copy installed from npm: the agent
@@ -66,7 +67,10 @@ export const KNOWN_KEYS = {
66
67
  CLAUDE_PRO_RIPGREP_PATH: 'Path to ripgrep (rg) for Grep and @-file suggestions; "off" forces the built-in JS scanner (default: rg from PATH, else the JS scanner)',
67
68
  CLAUDE_PRO_VERIFY_COMMAND: 'Command run after the agent edits files (e.g. "npm test"); failures are sent back to fix',
68
69
  CLAUDE_PRO_DISABLE_AUTO_MEMORY: 'Set to 1 to turn off the persistent per-project memory',
69
- CLAUDE_PRO_DISABLE_TOPIC_TITLE: 'Set to 1 to stop asking the small model for the current topic after each message (the tab title then shows the first message of the session)',
70
+ CLAUDE_PRO_DISABLE_TOPIC_TITLE: 'Set to 1 to stop asking the current model for the current topic after each message (the tab title then shows the first message of the session)',
71
+ CLAUDE_PRO_TRACE: 'Set to 0 to disable the privacy-preserving runtime JSONL trace (enabled by default)',
72
+ CLAUDE_PRO_TRACE_DIR: 'Directory for runtime trace files (default: the project session directory)',
73
+ CLAUDE_PRO_TRACE_MAX_SIZE: 'Maximum size of one runtime trace file in bytes before rotating it (default 20 MB)',
70
74
  };
71
75
 
72
76
  const SECRET_KEYS = new Set(['CLAUDE_PRO_GATEWAY_API_KEY']);
@@ -209,15 +213,10 @@ export class Config {
209
213
  return { id: name, contextWindow: oneM || nativeOneM ? 1_000_000 : 200_000, label: `${name}${oneM ? '[1m]' : ''}` };
210
214
  }
211
215
 
212
- // The model the gateway is configured with, before any /model override.
216
+ // The selected model: the configured default unless /model has overridden it for this session.
213
217
  get configuredModelSpec() { return this.env.CLAUDE_PRO_GATEWAY_MODEL || 'opus'; }
214
- get mainModelSpec() { return this.modelOverride || this.configuredModelSpec; }
215
- get mainModel() { return this.resolveModel(this.mainModelSpec); }
216
- // The gateway lets the main agent choose Claude sub-agent models by task difficulty.
217
- get subagentModel() { return this.mainModel; }
218
- // The main agent chooses each sub-agent's model (haiku, sonnet, opus) by the task, rather than one being set.
219
- get subagentModelChosen() { return this.usesGateway && /^claude-/i.test(this.mainModel.id); }
220
- get smallModel() { return this.resolveModel('haiku'); }
218
+ get modelSpec() { return this.modelOverride || this.configuredModelSpec; }
219
+ get model() { return this.resolveModel(this.modelSpec); }
221
220
 
222
221
  get effort() {
223
222
  const v = (this.effortBoost ?? this.effortOverride ?? this.env.CLAUDE_CODE_EFFORT_LEVEL ?? '').trim().toLowerCase();
@@ -272,12 +271,12 @@ export class Config {
272
271
 
273
272
  // Effective window for compaction: the configured auto-compact window capped by the model window. `own`: a
274
273
  // sub-agent's autoCompactWindow, which takes the place of the configured one.
275
- compactWindow(model = this.mainModel, own = 0) {
274
+ compactWindow(model = this.model, own = 0) {
276
275
  const configured = own > 0 ? own : int(this.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW, 0);
277
276
  return configured > 0 ? Math.min(configured, model.contextWindow) : model.contextWindow;
278
277
  }
279
278
  get autoCompactEnabled() { return !/^(1|true|yes)$/i.test(this.env.DISABLE_AUTOCOMPACT || ''); }
280
- autoCompactThreshold(model = this.mainModel, own = 0) {
279
+ autoCompactThreshold(model = this.model, own = 0) {
281
280
  const window = this.compactWindow(model, own);
282
281
  const pct = int(this.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE, 0);
283
282
  if (pct > 0 && pct <= 100) return Math.floor(window * pct / 100);
@@ -297,14 +296,30 @@ export class Config {
297
296
  // How deep sub-agents may nest: the main agent is depth 0; an agent below this depth gets the Task tool.
298
297
  get maxSubagentDepth() { return 2; }
299
298
 
300
- // Verification after edits: session override (/verify, --verify) wins over the env setting.
299
+ // Verification after edits: session override (/verify, --verify) wins over the env setting. With neither set,
300
+ // use a conventional project test/check command when one is unambiguous; /verify off remains the opt-out.
301
301
  get verifyCommand() {
302
+ const explicit = this.verifyOverride != null || Object.prototype.hasOwnProperty.call(this.env, 'CLAUDE_PRO_VERIFY_COMMAND');
303
+ if (!explicit) return this.autoVerifyCommand;
302
304
  const v = this.verifyOverride ?? this.env.CLAUDE_PRO_VERIFY_COMMAND ?? '';
303
305
  return v.trim() && v.trim() !== 'off' ? v.trim() : null;
304
306
  }
307
+ get autoVerifyCommand() { return discoverVerifyCommand(this.cwd); }
308
+ get verifyCommandAuto() {
309
+ return this.verifyOverride == null && !Object.prototype.hasOwnProperty.call(this.env, 'CLAUDE_PRO_VERIFY_COMMAND') && Boolean(this.autoVerifyCommand);
310
+ }
305
311
  // How many times a failing verify command is sent back before giving up.
306
312
  get verifyMaxRounds() { return 3; }
307
313
  get autoMemoryEnabled() { return !/^(1|true|yes)$/i.test(this.env.CLAUDE_PRO_DISABLE_AUTO_MEMORY || ''); }
314
+ get traceEnabled() {
315
+ const value = this.env.CLAUDE_PRO_TRACE;
316
+ return value === undefined || !/^(0|false|no|off)$/i.test(String(value).trim());
317
+ }
318
+ get traceDir() {
319
+ const value = String(this.env.CLAUDE_PRO_TRACE_DIR || '').trim();
320
+ return value ? path.resolve(this.cwd, value) : null;
321
+ }
322
+ get traceMaxBytes() { return Math.max(100_000, int(this.env.CLAUDE_PRO_TRACE_MAX_SIZE, 20 * 1024 * 1024)); }
308
323
 
309
324
  display(key) {
310
325
  const v = this.env[key];
package/src/context.js CHANGED
@@ -104,7 +104,9 @@ export function environmentBlock(cwd, { model, shellName, snapshot = null }) {
104
104
  if (git) {
105
105
  lines.push('', 'gitStatus: This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation.');
106
106
  lines.push(`Current branch: ${git.branch}`);
107
- if (git.main) lines.push(`Main branch (you will usually use this for PRs): ${git.main}`);
107
+ // Not Claude Code's wording ("Main branch (you will usually use this for PRs)"): the CodeBuddy channel behind the
108
+ // gateway refuses requests carrying that exact line (code 11128, shown as a 529 "overloaded") for its models.
109
+ if (git.main) lines.push(`Main branch: ${git.main}`);
108
110
  if (git.user) lines.push(`Git user: ${git.user}`);
109
111
  lines.push('', `Status:\n${git.status || '(clean)'}`, '', `Recent commits:\n${git.log || '(none)'}`);
110
112
  }
package/src/host.js CHANGED
@@ -853,7 +853,14 @@ export class HostService {
853
853
  if (other) throw new Error(`这段对话正开在会话 &${other.name} 里:先结束它`);
854
854
  // the service's own sessions with it: those in the registry, and those starting or restarting
855
855
  const running = [...(this.sessions?.sessions.values() || [])].filter((r) => (r.conversationId === id || open.some((p) => p.remoteId === r.sessionId)) && this.sessions.alive(r));
856
- if (running.length && stop !== true) throw new Error(`这段对话正开在会话 &${running[0].name || running[0].sessionId} 里:先结束它`);
856
+ if (running.length && stop !== true) {
857
+ // the name it has in the registry: its record learns it only at the next tick (see BackgroundSessions.tick)
858
+ const name = open.find((p) => p.remoteId === running[0].sessionId)?.name || running[0].name || running[0].sessionId;
859
+ throw new Error(`这段对话正开在会话 &${name} 里:先结束它`);
860
+ }
861
+ // what the registry says it has open, before its record learns it at the next tick: ended with it, the session's
862
+ // log goes with the conversation
863
+ for (const r of running) r.conversationId = id;
857
864
  for (const r of running) await this.sessions.stop(r.sessionId);
858
865
  const logs = this.sessions ? this.sessions.forgetConversation(id) : [];
859
866
  const r = deleteConversation({ projects: path.join(configDir(), 'projects'), id, extra: logs });
package/src/main.js CHANGED
@@ -47,6 +47,11 @@ Commands:
47
47
  code; the computer service then starts, and starts at logon
48
48
  claude-pro attach [name] Use a background session of this computer here, in this terminal
49
49
  (ctrl+] detaches; it goes on in the background)
50
+
51
+ Interactive prompt commands:
52
+ /prompt <file|text> Save and use a system prompt for later sessions
53
+ /prompts Choose a saved prompt (or select default)
54
+ /promt, /promits Accepted spelling-compatible aliases
50
55
  `;
51
56
 
52
57
  const REMOTE_ID = /^[A-Za-z0-9_-]{8,64}$/;
@@ -119,12 +124,11 @@ function configCommand(args, cwd) {
119
124
  }
120
125
  if (sub !== 'get') {
121
126
  console.log(`\nprovider: ${cfg.provider} (${cfg.endpointLabel})`);
122
- console.log(`main model: ${cfg.mainModel.label} (context ${cfg.mainModel.contextWindow.toLocaleString()})${cfg.effort ? `, effort ${cfg.effort}` : ''}`);
127
+ console.log(`model: ${cfg.model.label} (context ${cfg.model.contextWindow.toLocaleString()})${cfg.effort ? `, effort ${cfg.effort}` : ''}`);
123
128
  if (remembered.model || remembered.effort) {
124
129
  const what = Object.entries(remembered).map(([k, v]) => `${k} ${v}`).join(', ');
125
130
  console.log(`chosen with /model, /effort: ${what} (kept in ${files.user}; wins over the settings above, --model/--effort win over it)`);
126
131
  }
127
- console.log(`sub-agent model: ${cfg.subagentModelChosen ? `chosen per task (not chosen: ${cfg.subagentModel.label})` : cfg.subagentModel.label}; small model: ${cfg.smallModel.label}`);
128
132
  console.log(`auto-compact at ${cfg.autoCompactThreshold().toLocaleString()} tokens (window ${cfg.compactWindow().toLocaleString()})`);
129
133
  }
130
134
  return 0;
package/src/print.js CHANGED
@@ -50,8 +50,8 @@ export async function runPrint({ prompt, flags, cwd, stdout = process.stdout, st
50
50
  return { streamEvent: report, compactProgress: report };
51
51
  },
52
52
  };
53
- const runtime = await createRuntime({ cwd, flags, io });
54
53
  let store = new SessionStore(cwd);
54
+ const runtime = await createRuntime({ cwd, flags, io, sessionId: store.id });
55
55
  let cost = 0; // what this run's requests cost (total_cost_usd)
56
56
  let conversationCost = 0; // and the conversation's, kept with the session
57
57
  runtime.config.onCost = (usd) => {
@@ -66,6 +66,7 @@ export async function runPrint({ prompt, flags, cwd, stdout = process.stdout, st
66
66
  runtime.agent.restoreFileState(loaded.messages, loaded.times);
67
67
  runtime.agent.lastActivityAt = loaded.lastAt;
68
68
  store = new SessionStore(cwd, flags.resumeId);
69
+ runtime.trace?.setSessionId(store.id);
69
70
  store.systemPrompt = loaded.systemPrompt;
70
71
  runtime.resumeSystemPrompt(loaded.systemPrompt); // continue behind the prompt (and the cache) the conversation had
71
72
  }
@@ -0,0 +1,115 @@
1
+ // Persistent system-prompt profiles saved in the user's claude-pro configuration.
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { CONFIG_DIR, updateSettingsFile } from './config.js';
6
+
7
+ export const PROMPTS_DIR = path.join(CONFIG_DIR, 'prompts');
8
+ const SETTINGS_FILE = path.join(CONFIG_DIR, 'settings.json');
9
+
10
+ const isPromptName = (name) => {
11
+ const value = String(name ?? '').trim();
12
+ return Boolean(value) && value !== '.' && value !== '..' && !/[\\/\0]/.test(value);
13
+ };
14
+
15
+ function readSettings() {
16
+ try {
17
+ return JSON.parse(fs.readFileSync(SETTINGS_FILE, 'utf8').replace(/^\uFEFF/, ''));
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
22
+
23
+ function profileFile(name) {
24
+ if (!isPromptName(name)) throw new Error(`Invalid prompt name: ${name}`);
25
+ return path.join(PROMPTS_DIR, name);
26
+ }
27
+
28
+ export function activePromptName() {
29
+ const prompts = readSettings()?.prompts;
30
+ const name = prompts && typeof prompts === 'object' && !Array.isArray(prompts) ? prompts.active : null;
31
+ return isPromptName(name) ? String(name).trim() : null;
32
+ }
33
+
34
+ export function loadPrompt(name) {
35
+ const file = profileFile(name);
36
+ const text = fs.readFileSync(file, 'utf8');
37
+ return { name: String(name), file, text };
38
+ }
39
+
40
+ // Returns null for the built-in prompt, or a descriptor with an error when the selected file disappeared.
41
+ export function loadActivePrompt() {
42
+ const name = activePromptName();
43
+ if (!name) return null;
44
+ const file = profileFile(name);
45
+ try {
46
+ return { name, file, text: fs.readFileSync(file, 'utf8') };
47
+ } catch (error) {
48
+ return { name, file, text: null, error };
49
+ }
50
+ }
51
+
52
+ export function listPromptProfiles() {
53
+ let entries;
54
+ try { entries = fs.readdirSync(PROMPTS_DIR, { withFileTypes: true }); } catch { return []; }
55
+ return entries
56
+ .filter((entry) => entry.isFile() && isPromptName(entry.name))
57
+ .map((entry) => {
58
+ const file = path.join(PROMPTS_DIR, entry.name);
59
+ let size = 0;
60
+ let preview = '';
61
+ try {
62
+ size = fs.statSync(file).size;
63
+ preview = fs.readFileSync(file, 'utf8').replace(/\s+/g, ' ').trim().slice(0, 140);
64
+ } catch { /* a file can disappear between readdir and stat/read */ }
65
+ return { name: entry.name, file, size, preview };
66
+ })
67
+ .sort((a, b) => a.name.localeCompare(b.name));
68
+ }
69
+
70
+ export function setActivePrompt(name) {
71
+ const active = name == null || String(name).trim() === '' ? null : String(name).trim();
72
+ if (active !== null) {
73
+ const file = profileFile(active);
74
+ if (!fs.statSync(file).isFile()) throw new Error(`Prompt profile is not a file: ${active}`);
75
+ }
76
+ updateSettingsFile(SETTINGS_FILE, (json) => {
77
+ const current = json.prompts && typeof json.prompts === 'object' && !Array.isArray(json.prompts) ? { ...json.prompts } : {};
78
+ if (active) current.active = active;
79
+ else delete current.active;
80
+ if (Object.keys(current).length) json.prompts = current;
81
+ else delete json.prompts;
82
+ });
83
+ return active;
84
+ }
85
+
86
+ export function promptNameForText(text) {
87
+ const firstLine = String(text).split(/\r?\n/, 1)[0].trim();
88
+ let slug = firstLine
89
+ .normalize('NFKC')
90
+ .replace(/[^\p{L}\p{N}._-]+/gu, '-')
91
+ .replace(/^-+|-+$/g, '')
92
+ .slice(0, 48)
93
+ .replace(/^-+|-+$/g, '');
94
+ if (!slug || slug === '.' || slug === '..') slug = `prompt-${Date.now()}`;
95
+ let name = `${slug}.txt`;
96
+ let n = 2;
97
+ while (fs.existsSync(profileFile(name))) name = `${slug}-${n++}.txt`;
98
+ return name;
99
+ }
100
+
101
+ export function savePrompt(name, text, { activate = true } = {}) {
102
+ const profile = String(name ?? '').trim();
103
+ const content = String(text ?? '');
104
+ if (!isPromptName(profile)) throw new Error('A prompt profile needs a file name.');
105
+ if (!content.trim()) throw new Error('The system prompt cannot be empty.');
106
+ const file = profileFile(profile);
107
+ fs.mkdirSync(PROMPTS_DIR, { recursive: true });
108
+ fs.writeFileSync(file, content);
109
+ if (activate) setActivePrompt(profile);
110
+ return { name: profile, file, text: content };
111
+ }
112
+
113
+ export function promptDirectory() {
114
+ return PROMPTS_DIR;
115
+ }
package/src/prompts.js CHANGED
@@ -120,7 +120,7 @@ ${environmentBlock(cwd, { model, shellName, snapshot })}${files ? `\n\n# Project
120
120
  }
121
121
 
122
122
  // The terminal tab's title follows the topic of the conversation: after each message the user sends, the
123
- // small model says whether it starts a new topic and names it (as the official client does).
123
+ // current model says whether it starts a new topic and names it (as the official client does).
124
124
  export const TOPIC_TITLE_SYSTEM = 'You name the topic of a conversation between a user and a coding assistant, for the title of a terminal tab. Reply with JSON only.';
125
125
 
126
126
  export function topicTitlePrompt(current, message) {