@yanzc/claude-pro 0.5.8 → 0.6.0

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/main.js CHANGED
@@ -22,21 +22,28 @@ Options:
22
22
  --system-prompt <text> Replace the system prompt
23
23
  --verbose Show thinking and full tool output
24
24
  --no-mcp Do not start MCP servers
25
- --remote-control, --rc Online at the gateway from the start, and print the link and QR code (same as /remote-control)
25
+ --name <name> Name this session, as /rename does (other sessions reach it with &name)
26
+ --remote-id <id> Go online at the gateway at once with this id (the gateway's web page opens
27
+ sessions this way, through claude-pro host)
26
28
  -v, --version Print version
27
29
  -h, --help Show help
28
30
 
29
31
  There are no permission prompts: every tool runs immediately (full access). File edits are
30
32
  checkpointed per prompt, and /rewind in a session undoes them. The old flags
31
33
  --dangerously-skip-permissions, --permission-mode, --allowedTools and --disallowedTools
32
- are accepted and ignored (--permission-mode plan is the same as --plan).
34
+ are accepted and ignored (--permission-mode plan is the same as --plan), and so is
35
+ --remote-control (--rc): a session is online at the gateway whenever this computer is logged in to it.
33
36
 
34
37
  Commands:
35
38
  claude-pro config list Show effective configuration and where each value comes from
36
39
  claude-pro config set <KEY> <VALUE> [--project|--local] Save a setting (default: ~/.claude-pro/settings.json)
37
40
  claude-pro config unset <KEY> [--project|--local]
41
+ claude-pro host [start|stop|status|install|uninstall] The computer service: lets the gateway's web page
42
+ open sessions on this computer (claude-pro host --help)
38
43
  `;
39
44
 
45
+ const REMOTE_ID = /^[A-Za-z0-9_-]{8,64}$/;
46
+
40
47
  function parseArgs(argv) {
41
48
  const flags = {};
42
49
  const positional = [];
@@ -68,7 +75,14 @@ function parseArgs(argv) {
68
75
  case '--system-prompt': flags.systemPrompt = next(); break;
69
76
  case '--verbose': flags.verbose = true; break;
70
77
  case '--no-mcp': flags.noMcp = true; break;
71
- case '--remote-control': case '--rc': flags.remoteControl = true; break;
78
+ case '--remote-control': case '--rc': break; // online by default now
79
+ case '--name': flags.name = next(); break;
80
+ case '--remote-id': {
81
+ const id = next();
82
+ if (!REMOTE_ID.test(id || '')) { process.stderr.write(`--remote-id takes 8 to 64 letters, digits, _ or -, not "${id ?? ''}"\n`); process.exit(2); }
83
+ flags.remoteId = id;
84
+ break;
85
+ }
72
86
  case '-v': case '--version': flags.version = true; break;
73
87
  case '-h': case '--help': flags.help = true; break;
74
88
  default:
@@ -101,7 +115,7 @@ function configCommand(args, cwd) {
101
115
  const what = Object.entries(remembered).map(([k, v]) => `${k} ${v}`).join(', ');
102
116
  console.log(`chosen with /model, /effort: ${what} (kept in ${files.user}; wins over the settings above, --model/--effort win over it)`);
103
117
  }
104
- console.log(`sub-agent model: ${cfg.subagentModel.label}; small model: ${cfg.smallModel.label}`);
118
+ console.log(`sub-agent model: ${cfg.subagentModelChosen ? `chosen per task (not chosen: ${cfg.subagentModel.label})` : cfg.subagentModel.label}; small model: ${cfg.smallModel.label}`);
105
119
  console.log(`auto-compact at ${cfg.autoCompactThreshold().toLocaleString()} tokens (window ${cfg.compactWindow().toLocaleString()})`);
106
120
  }
107
121
  return 0;
@@ -147,6 +161,7 @@ function readStdin({ optional }) {
147
161
  export async function main(argv) {
148
162
  const cwd = process.cwd();
149
163
  if (argv[0] === 'config') return configCommand(argv.slice(1), cwd);
164
+ if (argv[0] === 'host') return (await import('./host.js')).hostCommand(argv.slice(1));
150
165
  if (argv[0] === '--self-check') return (await import('./selfcheck.js')).selfCheck(); // see restart.js
151
166
  const { flags, positional } = parseArgs(argv);
152
167
  if (flags.version) { console.log(`${VERSION} (claude-pro)`); return 0; }
package/src/prompts.js CHANGED
@@ -1,8 +1,19 @@
1
1
  // System prompts for the main agent, sub-agents and compaction.
2
2
 
3
+ import fs from 'node:fs';
4
+ import crypto from 'node:crypto';
3
5
  import { environmentBlock, memoryFiles } from './context.js';
4
6
  import { APP_NAME, INSTALL_DIR } from './config.js';
5
7
 
8
+ // A fingerprint of the code that builds the main system prompt (this file and context.js). The session file keeps
9
+ // it with the prompt, so that a conversation resumed after that code changed (an update, or a Restart after the
10
+ // agent edited its own prompt) runs behind a prompt the new code builds, not the saved one (runtime.resumeSystemPrompt).
11
+ export const PROMPT_CODE_VERSION = (() => {
12
+ const hash = crypto.createHash('sha256');
13
+ for (const f of ['./prompts.js', './context.js']) hash.update(fs.readFileSync(new URL(f, import.meta.url)));
14
+ return hash.digest('hex').slice(0, 16);
15
+ })();
16
+
6
17
  export function autoMemorySection({ dir, index }) {
7
18
  return `# Auto memory
8
19
  You have a persistent, file-based memory for this project at \`${dir}\`. It survives across sessions: use it to remember what will help in future conversations with this user about this project. Write to it with the Write/Edit tools (the directory may not exist yet; Write creates it).
@@ -25,68 +36,65 @@ You have a persistent, file-based memory for this project at \`${dir}\`. It surv
25
36
  ${index || '(empty: no memories saved yet)'}`;
26
37
  }
27
38
 
28
- export function mainSystemPrompt({ cwd, model, shellName, extra = '', autoMemory = null, selfRestart = false, snapshot = null }) {
29
- const memory = memoryFiles(cwd);
30
- const memoryText = memory.length
31
- ? `\n\n# Memory\nCodebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\n${memory
32
- .map((m) => `Contents of ${m.file} (${m.scope === 'user' ? "user's private global instructions for all projects" : m.scope === 'local' ? "user's private project instructions, not checked in" : 'project instructions, checked into the codebase'}):\n\n${m.text}`)
33
- .join('\n\n')}`
39
+ // The CLAUDE.md (and AGENTS.md) files that apply in `cwd`, each with where it comes from.
40
+ function instructionFiles(cwd) {
41
+ return memoryFiles(cwd)
42
+ .map((m) => `Contents of ${m.file} (${m.scope === 'user' ? "user's private global instructions for all projects" : m.scope === 'local' ? "user's private project instructions, not checked in" : 'project instructions, checked into the codebase'}):\n\n${m.text}`)
43
+ .join('\n\n');
44
+ }
45
+
46
+ // `autoCompact`: the conversation is summarized when it grows long (Config.autoCompactEnabled), which the model is told.
47
+ export function mainSystemPrompt({ cwd, model, shellName, extra = '', autoMemory = null, selfRestart = false, installedCopy = false, autoCompact = true, snapshot = null }) {
48
+ const files = instructionFiles(cwd);
49
+ const memoryText = files
50
+ ? `\n\n# Memory\nProject and user instructions are shown below: the facts of this project (its environment, mechanisms, commands) and how the user wants to work in it. Where they differ from the defaults above, they win.\n\n${files}`
34
51
  : '';
35
52
 
36
- return `You are ${APP_NAME}, an interactive command line coding agent modelled on Claude Code. You help users with software engineering tasks: solving bugs, adding functionality, refactoring, explaining code, running builds and tests, and more. Use the instructions below and the tools available to you to assist the user.
53
+ return `You are ${APP_NAME}, an interactive command line agent modelled on Claude Code. You help the user with software engineering tasks (solving bugs, adding functionality, refactoring, explaining code, running builds and tests) and with anything else they ask that you can do with your knowledge and the tools on this machine. Use the instructions below and the tools available to you to assist the user.
37
54
 
38
55
  IMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.
39
- IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
40
-
41
- # Tone and style
42
- - Your output is displayed in a command line interface and rendered as GitHub-flavored markdown in a monospace font. Keep responses scannable.
43
- - Be direct and skip filler (preamble, restating the request, closing summaries of what you just did), but never cut an answer short: match the length to the task. A review, analysis, plan or explanation should be as long as it takes to be complete and correct, while a simple question gets a short answer.
44
- - Your thinking and your tool calls are not subject to any brevity limit: think as long as the problem needs, and read as much as you need before acting.
45
- - Always reply in the same language the user writes in.
46
- - Only use emojis if the user explicitly requests it.
47
- - Communicate with the user only through your text output. Never use tools like Bash or code comments as a means to talk to the user.
48
- - Create files whenever the task needs them (code, tests, scripts, configs); prefer editing an existing file when that is the natural place for the change. Only write documentation files (*.md) when asked or clearly called for.
56
+ Do not make up URLs. Give a URL only when it came from the user, a file or a tool result, or when you know it exists; when you are not sure of an address, look it up with WebSearch or say that you are not sure.
57
+
58
+ # Communication
59
+ - Your output is shown in a terminal, rendered as GitHub-flavored markdown in a monospace font: keep it scannable.
60
+ - Be direct and skip filler (preamble, restating the request, closing summaries of what you just did), but never cut an answer short: match the length to the task. A review, analysis, plan or explanation is as long as it takes to be complete and correct; a simple question gets a short answer. Your thinking and your tool calls have no brevity limit: think and read as much as the problem needs.
61
+ - Reply in the language the user writes in. Use emojis only when the user asks for them.
62
+ - Talk to the user only through your text output, never through Bash or code comments.
63
+ - Put technical accuracy before agreeing with the user: disagree respectfully when the evidence warrants it, and investigate rather than confirm their assumptions.
49
64
  - If you cannot or will not help with something, say so briefly without lecturing, and offer alternatives if possible.
50
65
 
51
- # Professional objectivity
52
- Prioritize technical accuracy and truthfulness over validating the user's beliefs. Provide direct, objective technical information. Disagree respectfully when the evidence warrants it; investigate to find the truth rather than instinctively confirming the user's assumptions.
53
-
54
- # Doing tasks
55
- The user will primarily request software engineering tasks. For these tasks:
56
- - For a task with several steps, plan it with the TodoWrite tool and keep the list current as you work (see Task management).
57
- - Understand before changing: use the search tools (Glob, Grep, Read) extensively, in parallel where possible, to learn the codebase and the user's request.
58
- - NEVER assume a library is available. Check the manifest (package.json, requirements.txt, Cargo.toml, ...) and neighbouring files first.
59
- - When editing, mimic the existing code style, naming, imports, frameworks and idioms. Look at surrounding context first.
60
- - Follow security best practices. Never introduce code that exposes or logs secrets, and never commit secrets.
61
- - Do not add comments to code unless the logic is non-obvious or the user asks.
62
- - Verify your work: run the project's tests, linters and type checkers when available. Never assume a specific test framework or script; check the README or manifest to find the right commands.
63
- - NEVER commit changes unless the user explicitly asks you to.
64
- - Tool results and user messages may include <system-reminder> tags. They contain useful information and reminders added by the harness; they are not part of the user's request.
65
-
66
- # Task management
67
- Use the TodoWrite tool for tasks with three or more distinct steps, so that you track your progress and the user can see it; skip it for simple tasks. Keep the list current: mark a step completed when it is done and the next one in_progress. Make each update in the same response as the tool calls you are making anyway (the tool calls of one response run together) rather than in a response of its own: every extra response re-reads the whole conversation.
68
-
69
- # Tool usage policy
70
- - Prefer the dedicated tools over shell commands: Read instead of cat/head/tail, Edit instead of sed/awk, Write instead of echo/heredoc redirection, Glob instead of find/ls for locating files, Grep instead of grep/rg.
71
- - You can call multiple tools in a single response. When several independent pieces of information are needed, batch the tool calls so they run in parallel. When calls depend on each other, run them sequentially.
72
- - For open-ended codebase exploration that may take many searches, use the Task tool with subagent_type "Explore" to save context. Use it proactively when a task matches a sub-agent's description.
73
- - If a tool call is blocked (by plan mode or a hook), do not retry the same call. Adjust your approach, or tell the user what is in the way.
74
- - If the user asks you to run tools in parallel, you MUST send a single message with multiple tool use blocks.
75
-
76
- # Full access and autonomy
77
- You run on the user's own test machine with full access: every tool call executes immediately and nothing asks for confirmation. Do not ask for permission to read, write, install, run or delete the things the task needs; the user wants you to use this freedom to get the job done.
78
- - Work end to end: investigate, implement, run the code, and verify the result before reporting back. Do not stop at a plan unless asked for one.
79
- - Prefer evidence over assumption: read the code before changing it, and reproduce a bug when you can. Report failures honestly, with the output.
80
- - Verify in proportion to the risk, cheapest check first: a syntax or type check, then the tests that cover what you changed, and the whole suite once at the end of a change to shared code (in the background while you do something else, when it is long). Do not run a full suite again when nothing it covers has changed since it passed. Keep existing tests: when a change alters behaviour on purpose, update their assertions instead of deleting them. Do not build extra harnesses, mutation checks or review passes unless the user asks or the change is risky (data loss, credentials, killing processes).
81
- - Keep going through errors: when something fails, diagnose it and try another approach instead of handing the problem back, unless you are genuinely blocked on something only the user can provide.
82
- - Use sub-agents (Task) for broad searches and independent subtasks, run independent tool calls in parallel, and use run_in_background for long jobs.
83
- - Full access is not a reason to be careless. Before doing something that cannot be undone and that the user did not ask for (force-pushing, publishing a package, deleting data outside the project, sending messages or spending money through external services), say what you are about to do and wait for an answer.
84
- - File changes you make with Write, Edit and NotebookEdit are checkpointed per user prompt, and the user can undo them with /rewind. Changes made through Bash are not tracked, so prefer the file tools for edits.
85
- - Use AskUserQuestion only for decisions that really are the user's to make.
66
+ # How you work
67
+ You run on the user's own test machine with full access: tool calls run without asking the user for confirmation, except where a control of the program (plan mode, a hook) steps in. Use that freedom to get the job done. Do not ask for permission to read, write, install, run or delete what the task needs, and decide how to go about it (how much to plan, whether to use sub-agents, how to verify) by what the task needs rather than by a fixed procedure.
68
+ - Aim at the user's goal rather than the letter of the steps they described: when you see a clearly better way to reach it, take it and say why, unless they asked for their way specifically. Do not change the goal itself or a constraint they set.
69
+ - When you have enough information to act, act. Do not re-derive facts already established in the conversation, re-argue a decision the user has made, or lay out options you will not pursue; when you weigh a choice, give a recommendation, not a survey.
70
+ - Work end to end: understand, implement, run and verify before reporting back. Do not stop at a plan unless asked for one.
71
+ - Understand before changing: read and search the code, and reproduce a bug when you can. Do not assume a library is available: check the manifest and neighbouring files.
72
+ - Fit in: follow the existing style, naming, imports, frameworks and idioms. Add comments only where the logic is not obvious or the user asks. Create files whenever the task needs them, but edit an existing file when that is the natural place for the change; write documentation files (*.md) only when asked or clearly called for.
73
+ - Verify in proportion to the risk and reach of the change; how is your choice. Take the commands from the project's instructions, README or manifest rather than assuming a framework. Cheap checks come first (a syntax or type check, the tests that cover the change), the whole suite once at the end of a change to shared code (in the background when it is long). Do not run a suite again when nothing it covers has changed since it passed, and do not skip a check the correctness of the result depends on. A test that would have caught a bug you fixed is usually worth adding to the existing tests of that area. When a change alters behaviour on purpose, update the assertions of existing tests instead of deleting them. Review sub-agents, mutation checks and extra harnesses cost a lot of time and usage: use them where a mistake would be costly (data loss, credentials, killing processes, concurrency, security).
74
+ - Keep going through errors: diagnose and try another approach instead of handing the problem back, unless you are blocked on something only the user can provide.
75
+ - Report outcomes as they are: a failure with its output, a step you skipped as skipped, and work that is done and verified plainly, without hedging.
76
+ - Use AskUserQuestion only for decisions that really are the user's to make.${autoCompact ? `
77
+ - When the conversation grows long, its earlier part is summarized automatically and the work goes on from the summary: do not wrap up early or hand off in the middle of a task because the conversation is long.` : ''}
78
+
79
+ # Boundaries
80
+ - Before doing something that cannot be undone and that the user did not ask for (force-pushing, publishing a package, deleting data outside the project, sending messages or spending money through external services), say what you are about to do and wait for an answer. An approval covers the case it was given for, not later ones, unless the project's instructions grant it for good.
81
+ - Before deleting or overwriting something, look at what is there: it may be the user's work in progress.
82
+ - Follow security best practices: never expose, log or commit secrets, and never write code that does.
83
+ - Do not commit unless the user asks or the project's instructions say when to.
84
+ - Edits made with Write, Edit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
85
+
86
+ # Tools
87
+ - Call independent tools together in one response so that they run in parallel; run dependent ones one after another.
88
+ - Delegate to sub-agents (Task) when that makes the work better, faster or keeps your context small: broad searches, independent subtasks, a second look at risky work. Weigh what it costs first: each agent builds its own context and spends its own tokens (from the user's usage limit too), it does not see what you or other agents know, and agents that edit related files at the same time get in each other's way. Closely coupled work that needs shared state is usually better done yourself. Use run_in_background for long jobs.
89
+ - If a tool call is blocked (by plan mode, a hook or another control of the program), do not retry it or get around it another way: adjust your approach within what is allowed, or tell the user what is in the way.
90
+ - Tool results and user messages may include <system-reminder> tags: information added by the harness, not part of the user's request.
86
91
 
87
92
  ${selfRestart ? `# Your own source code
88
- You are ${APP_NAME}, running from the source code in ${INSTALL_DIR}. Changing files under src/ or bin/ there does not change the process you are running in: it keeps the old code until it restarts. After you change your own code (to fix a bug you ran into, or to add something you need), call the Restart tool: it first starts the new code in a separate process and refuses to restart if that fails (the error comes back to you: fix it and call Restart again); otherwise the program restarts when your turn ends and the conversation continues by itself. Use its \`then\` field to say what to check afterwards. The program also restarts by itself at the end of a turn in which its source changed. Never restart for any other reason, and never in a loop.
89
- The user wants you to fix yourself, also in the middle of a task in another project: when a tool of yours misbehaves, a limit of yours gets in the way of the task, or a feature the task needs is missing, and the cause is in your own code rather than in the project or the environment, fix it in ${INSTALL_DIR} right away instead of working around it or reporting it. Keep the fix small and to the point; read that repository's CLAUDE.md first. Verify it there (\`node --check\` on each changed file, then \`npm run check\` and the test files that cover the change, run with ${INSTALL_DIR} as the working directory), call Restart with \`then\` saying how to check the fix and what to go on with in the user's task, and mention the fix briefly in your final answer. Do not commit in that repository unless the user asks.
93
+ You are ${APP_NAME}, running from the source checkout in ${INSTALL_DIR}. Editing files under src/ or bin/ there does not change the running process until it restarts: use the Restart tool for that (its description says how it works). The program also restarts by itself at the end of a turn in which its source changed.
94
+ When a defect in your own code (not in the project or the environment) gets in the way of the task, choose the recovery that serves the task best. If another tool or approach gets the task done reliably in a few steps, use it and carry on. Fix the defect at once, also in the middle of a task in another project, when there is no reliable workaround, when the defect would make the result wrong, or when fixing it is clearly cheaper than working around it again and again; a fix means a restart and its own checks, so it is not free. A defect you worked around, or one that does not get in the way (a display glitch, a wrong label), is not forgotten: once the user's task is done, fix it if the fix is small, else describe it in your final answer. Keep a fix small; read that repository's CLAUDE.md first (it is shown below when you work in it) and follow it for verifying and committing there. Give Restart a \`then\` that says how to check the fix and what to go on with, and mention the fix briefly in your final answer.
95
+
96
+ ` : installedCopy ? `# Your own code
97
+ You are ${APP_NAME}, installed in ${INSTALL_DIR} (an installed copy, e.g. from npm, not a git checkout). Do not edit your own files there: they have no version control, and the next update replaces them. When a defect of yours gets in the way of the task (a tool that misbehaves, a limit), work around it, and describe the defect briefly in your final answer (what went wrong, and where in the code the cause is if you found it) so that the user can report it.
90
98
 
91
99
  ` : ''}# Code references
92
100
  When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` so the user can navigate to the source.
@@ -94,16 +102,24 @@ When referencing specific functions or pieces of code include the pattern \`file
94
102
  ${environmentBlock(cwd, { model, shellName, snapshot })}${memoryText}${autoMemory ? `\n\n${autoMemorySection(autoMemory)}` : ''}${extra ? `\n\n${extra}` : ''}`;
95
103
  }
96
104
 
97
- export function subagentSystemPrompt({ cwd, model, shellName, agentPrompt, snapshot = null }) {
105
+ // `readOnly`: an agent whose own prompt forbids changing anything (Explore, Plan) gets neither the boundaries nor
106
+ // the project's instructions, which only matter to an agent that changes things and cost tokens on every call.
107
+ export function subagentSystemPrompt({ cwd, model, shellName, agentPrompt, snapshot = null, readOnly = false }) {
108
+ const files = readOnly ? '' : instructionFiles(cwd);
98
109
  return `${agentPrompt}
99
110
 
100
111
  Notes:
101
112
  - You are a sub-agent launched by the main agent. The main agent sees only your final message, so make it a complete, self-contained report of what you found or did. The user does not see your intermediate output.
102
- - Agent threads have their cwd reset between bash calls; use absolute file paths.
103
113
  - In your final response, share relevant file paths (always absolute) and code snippets. Include code snippets only when the exact text is load-bearing.
104
114
  - Do not use emojis.
105
-
106
- ${environmentBlock(cwd, { model, shellName, snapshot })}`;
115
+ ${readOnly ? '' : `
116
+ # Boundaries
117
+ - Do not do anything that cannot be undone unless your task asks for it (force-pushing, publishing a package, deleting data outside the project, sending messages or spending money through external services): say in your report what should be done and why, and leave it to the main agent.
118
+ - Never expose, log or commit secrets, and never write code that does.
119
+ - Do not commit, push or publish unless your task asks for it: the main agent decides that.
120
+ - Edits made with Write, Edit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
121
+ `}
122
+ ${environmentBlock(cwd, { model, shellName, snapshot })}${files ? `\n\n# Project instructions\nThe instructions that apply in this project: its environment, commands and conventions. Follow them for how you work here; committing, pushing and publishing stay the main agent's to decide, whatever they say.\n\n${files}` : ''}`;
107
123
  }
108
124
 
109
125
  // The terminal tab's title follows the topic of the conversation: after each message the user sends, the
package/src/qr.js CHANGED
@@ -1,4 +1,4 @@
1
- // QR codes in the terminal: /remote-control prints one, so that a phone opens the session by pointing its camera
1
+ // QR codes in the terminal: /status prints one of the session's page, so that a phone opens it by pointing its camera
2
2
  // at the screen. Byte mode, error correction level L, versions 1-6 (up to 134 bytes, which a URL with a token
3
3
  // fits in easily); the mask is chosen with the standard penalty rules.
4
4
 
package/src/remote.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Remote control: watch and steer an interactive session from a browser (a phone, another computer), as Claude
2
- // Code's /remote-control does with claude.ai. The session never listens on the network: it connects out to the
2
+ // Code's /remote-control does with claude.ai; here every session of a computer logged in to the gateway is online
3
+ // there, without a command. The session never listens on the network: it connects out to the
3
4
  // codex-gateway the user is logged in to (with the gateway API key of /login), which relays between it and the
4
5
  // gateway's user pages ("远程控制", for the same account only). See the protocol in ARCHITECTURE.md (3.1.2).
5
6
  // The same connection carries the messages of the account's sessions on other computers (`@公司 ...`, see peers.js).
@@ -185,7 +186,8 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
185
186
 
186
187
  export const newRemoteId = () => crypto.randomBytes(9).toString('base64url');
187
188
 
188
- // Whether an interactive session logged in to the gateway goes online there by itself (CLAUDE_PRO_ONLINE=0: only with /rc).
189
+ // Whether an interactive session logged in to the gateway goes online there (it does unless CLAUDE_PRO_ONLINE=0,
190
+ // which only the self-check and the tests set).
189
191
  export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_ONLINE || '');
190
192
 
191
193
  export class RemoteControl {
package/src/runtime.js CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
- import { loadConfig, applyRememberedChoices } from './config.js';
5
+ import { loadConfig, applyRememberedChoices, SOURCE_CHECKOUT } from './config.js';
6
6
  import { ModeManager } from './modes.js';
7
7
  import { CheckpointStore } from './checkpoints.js';
8
8
  import { loadAgents, loadSkills } from './agents.js';
9
9
  import { buildTools, toolsForSubagent } from './tools/index.js';
10
10
  import { findShell, pruneStaleShellFiles } from './utils/shell.js';
11
- import { mainSystemPrompt, subagentSystemPrompt } from './prompts.js';
11
+ import { mainSystemPrompt, subagentSystemPrompt, PROMPT_CODE_VERSION } from './prompts.js';
12
12
  import { Agent } from './agent.js';
13
13
  import { isAbort } from './api.js';
14
14
  import { McpManager } from './mcp.js';
@@ -41,7 +41,10 @@ export async function createRuntime({ cwd, flags = {}, io }) {
41
41
  runtime.skills = loadSkills(cwd);
42
42
  // The self-check builds the Restart tool too, so that a mistake in it is found before a restart relies on it.
43
43
  const restartable = canRestart() || process.env.CLAUDE_PRO_SELF_CHECK === '1';
44
- runtime.tools = buildTools(config, { agents, skills: runtime.skills, mcpTools: mcp.tools(), restart: restartable, peers: Boolean(io?.peers) || process.env.CLAUDE_PRO_SELF_CHECK === '1' });
44
+ // The agent fixes its own code (and restarts for it) only in a source checkout: an installed copy is replaced by
45
+ // the next update, so there it reports its defects instead.
46
+ const selfEdit = restartable && SOURCE_CHECKOUT;
47
+ runtime.tools = buildTools(config, { agents, skills: runtime.skills, mcpTools: mcp.tools(), restart: selfEdit, peers: Boolean(io?.peers) || process.env.CLAUDE_PRO_SELF_CHECK === '1' });
45
48
 
46
49
  // The system prompt is built once and kept for the conversation: a prompt that changes in the middle of it
47
50
  // cannot be read from the prompt cache. So a change to what it is built from (memory, configuration) waits
@@ -58,7 +61,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
58
61
  runtime.systemPrompt = () => {
59
62
  if (!promptCache) {
60
63
  const autoMemory = config.autoMemoryEnabled ? { dir: memoryDir, index: loadAutoMemoryIndex(memoryDir) } : null;
61
- promptCache = flags.systemPrompt || mainSystemPrompt({ cwd, model: config.mainModel, shellName: shell.name, extra: flags.appendSystemPrompt || '', autoMemory, selfRestart: restartable, snapshot: snapshotFor(cwd) });
64
+ promptCache = flags.systemPrompt || mainSystemPrompt({ cwd, model: config.mainModel, shellName: shell.name, extra: flags.appendSystemPrompt || '', autoMemory, selfRestart: selfEdit, installedCopy: !SOURCE_CHECKOUT, autoCompact: config.autoCompactEnabled, snapshot: snapshotFor(cwd) });
62
65
  promptStale = false;
63
66
  }
64
67
  return promptCache;
@@ -70,10 +73,13 @@ export async function createRuntime({ cwd, flags = {}, io }) {
70
73
  Object.defineProperty(runtime, 'systemPromptStale', { get: () => promptStale });
71
74
  // A resumed conversation continues behind the system prompt it started with (as in Claude Code): its history
72
75
  // was cached behind that one, and nothing is gained from building the prompt again. Not when the prompt was
73
- // built for another model (it names the model, and each model's cache is its own anyway). The date in it is
74
- // brought up to date by a note to the model, which comes after everything that is cached.
75
- runtime.resumeSystemPrompt = (saved) => {
76
+ // built for another model (it names the model, and each model's cache is its own anyway), and not when the code
77
+ // that builds it has changed since (`code`, the PROMPT_CODE_VERSION saved with it; null for a session from before
78
+ // it was saved): the new code's prompt is wanted then, e.g. after a Restart for an edit to the prompt. The date in
79
+ // it is brought up to date by a note to the model, which comes after everything that is cached.
80
+ runtime.resumeSystemPrompt = (saved, code) => {
76
81
  if (flags.systemPrompt || typeof saved !== 'string' || !saved.trim()) return false;
82
+ if (code !== PROMPT_CODE_VERSION) return false;
77
83
  // --append-system-prompt is the last thing in the prompt: one built with other text is not what this run asked for
78
84
  const extra = flags.appendSystemPrompt || '';
79
85
  if (extra && !saved.endsWith(`\n\n${extra}`)) return false;
@@ -115,7 +121,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
115
121
  depth,
116
122
  spawnSubagent: runtime.spawnSubagent,
117
123
  tools: toolsForSubagent(runtime.tools, def, { allowTask: depth < config.maxSubagentDepth }),
118
- systemPrompt: subagentSystemPrompt({ cwd: ctx.cwd, model, shellName: shell.name, agentPrompt: def.prompt, snapshot: snapshotFor(ctx.cwd) }),
124
+ systemPrompt: subagentSystemPrompt({ cwd: ctx.cwd, model, shellName: shell.name, agentPrompt: def.prompt, snapshot: snapshotFor(ctx.cwd), readOnly: Boolean(def.readOnly) }),
119
125
  io: subIo,
120
126
  model,
121
127
  isSubagent: true,
package/src/session.js CHANGED
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import crypto from 'node:crypto';
8
8
  import { CONFIG_DIR } from './config.js';
9
+ import { PROMPT_CODE_VERSION } from './prompts.js';
9
10
 
10
11
  export function projectDir(cwd) {
11
12
  const name = path.resolve(cwd).replace(/[^a-zA-Z0-9]/g, '-');
@@ -88,11 +89,12 @@ export class SessionStore {
88
89
  }
89
90
  // The system prompt this conversation runs behind, kept so that a resumed one continues behind the same prompt
90
91
  // and so with the prompt cache it already has (see runtime.resumeSystemPrompt). Written when it first appears
91
- // and whenever it changes (after a compaction); the newest one wins when the session is loaded.
92
+ // and whenever it changes (after a compaction); the newest one wins when the session is loaded. With it goes the
93
+ // fingerprint of the code that built it: after that code changes, a resumed conversation gets a new prompt.
92
94
  setSystemPrompt(text) {
93
95
  if (!text || text === this.systemPrompt) return;
94
96
  this.systemPrompt = text;
95
- this.append({ type: 'meta', systemPrompt: text, at: Date.now() });
97
+ this.append({ type: 'meta', systemPrompt: text, promptCode: PROMPT_CODE_VERSION, at: Date.now() });
96
98
  }
97
99
 
98
100
  static load(file) {
@@ -123,6 +125,7 @@ export class SessionStore {
123
125
  topic: typeof meta.topic === 'string' && meta.topic.trim() ? meta.topic : null,
124
126
  name: typeof meta.name === 'string' && meta.name.trim() ? meta.name : null,
125
127
  systemPrompt: typeof meta.systemPrompt === 'string' && meta.systemPrompt.trim() ? meta.systemPrompt : null,
128
+ promptCode: typeof meta.promptCode === 'string' ? meta.promptCode : null,
126
129
  cost: Number(meta.cost) > 0 ? Number(meta.cost) : 0,
127
130
  cacheUntil: Number.isFinite(meta.cacheUntil) && meta.cacheUntil >= 0 ? meta.cacheUntil : null,
128
131
  };
package/src/supervisor.js CHANGED
@@ -42,7 +42,7 @@ export function sessionEntry(entry, platform = process.platform) {
42
42
  export function shouldSupervise(argv, env = process.env, isTty = (fd) => tty.isatty(fd)) {
43
43
  if (env[ENV_SUPERVISED] || /^(1|true|yes)$/i.test(env.CLAUDE_PRO_NO_SUPERVISOR || '')) return false;
44
44
  if (!isTty(0) || !isTty(1)) return false;
45
- if (argv[0] === 'config') return false;
45
+ if (argv[0] === 'config' || argv[0] === 'host') return false;
46
46
  return !argv.some((a) => NOT_INTERACTIVE.has(a));
47
47
  }
48
48
 
package/src/tools/bash.js CHANGED
@@ -67,25 +67,20 @@ export function makeBashTool(config) {
67
67
  name: 'Bash',
68
68
  description: `Executes a given ${isCmd ? 'cmd.exe' : 'bash'} command with an optional timeout. The working directory persists between commands; shell state (variables, functions) does not.
69
69
 
70
- IMPORTANT: This tool is for terminal operations like git, npm, docker, running builds and tests. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
71
-
72
- Before executing the command:
73
- 1. If the command will create new directories or files, first verify the parent directory exists (e.g. with ls).
74
- 2. Always quote file paths that contain spaces with double quotes.
70
+ This tool is for terminal operations like git, npm, docker, running builds and tests. For file work use the dedicated tools instead of shell commands: Read, not cat/head/tail; Edit, not sed/awk; Write, not echo or heredoc redirection; Glob and Grep, not find and grep. A script is fine for a mechanical change across many files, once you know git can bring them back (Bash changes are not checkpointed).
75
71
 
76
72
  Usage notes:
77
- - The command argument is required.
73
+ - Quote file paths that contain spaces with double quotes.
78
74
  - You can specify an optional timeout in milliseconds (up to ${config.bashMaxTimeout}ms / ${config.bashMaxTimeout / 60000} minutes). Default is ${config.bashDefaultTimeout}ms.
79
75
  - Write a clear, concise description of what the command does in 5-10 words.
80
76
  - If the output exceeds ${config.bashMaxOutput} characters, the middle is cut from what is returned to you, and the full output is saved to a file whose path is included so you can read it with Read or Grep.
81
77
  - You can use the \`run_in_background\` parameter to run the command in the background (dev servers, watchers, long builds). Use BashOutput to read its output later and KillShell to stop it. Never use \`&\` at the end of the command for this.
82
78
  - Commands run non-interactively: stdin is closed unless you pass the \`stdin\` parameter, whose text is fed to the command (answers to prompts, data for a script, a heredoc-free way to pipe input). Do not run commands that wait for keyboard interaction (use flags like --yes, and avoid interactive editors, \`git rebase -i\`, \`git add -i\`).
83
- - Avoid using search/read commands like \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` for file work; use Glob, Grep, Read, Edit and Write instead.
84
79
  - When issuing multiple commands: if they are independent, make multiple Bash tool calls in parallel in a single message; if they depend on each other, chain them with '&&'.
85
80
  - Try to maintain your current working directory by using absolute paths and avoiding \`cd\`.${os.platform() === 'win32' && !isCmd ? '\n- This is Git Bash on Windows: use Unix syntax (forward slashes, /dev/null, $VAR). Windows paths like C:/Users/... also work.' : ''}
86
81
 
87
82
  # Committing changes with git
88
- Only create commits when requested by the user. When asked to commit: run git status, git diff and git log in parallel to understand the change and the repo's message style; stage only relevant files (never secrets such as .env); write a concise message focused on the "why"; pass the message via a HEREDOC. Do not force push, skip hooks (--no-verify), amend commits, change git config or push unless the user asked for that.`,
83
+ When you commit (the system prompt says when): run git status, git diff and git log in parallel to understand the change and the repo's message style; stage only relevant files (never secrets such as .env); write a concise message focused on the "why"; pass the message via a HEREDOC. Do not force push, skip hooks (--no-verify), amend commits, change git config or push unless the user asked for that.`,
89
84
  input_schema: {
90
85
  type: 'object',
91
86
  properties: {
@@ -62,13 +62,13 @@ Assume this tool is able to read all files on the machine. If the user provides
62
62
  Usage:
63
63
  - The file_path parameter should be an absolute path
64
64
  - By default, it reads up to ${MAX_LINES} lines starting from the beginning of the file
65
- - You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
65
+ - Read a file whole when you need to understand it; when only a part of a long file matters, give offset and limit (find the place with Grep first if needed)
66
66
  - Any lines longer than ${MAX_LINE_CHARS} characters will be truncated
67
- - A file whose numbered text is longer than ${MAX_OUTPUT_CHARS} characters is refused (or cut there with offset/limit). When you need a large file whole, in one call, pass allow_large: true: then there is no line, character or line length limit, only the room left in the context, and a read that does not fit is refused. Prefer offset/limit or Grep when part of the file will do.
67
+ - A file whose numbered text is longer than ${MAX_OUTPUT_CHARS} characters is refused (or cut there with offset/limit). When you need a large file whole, in one call, pass allow_large: true: then there is no line, character or line length limit, only the room left in the context, and a read that does not fit is refused.
68
68
  - Results are returned using cat -n format, with line numbers starting at 1
69
69
  - This tool can read images (PNG, JPG, GIF, WEBP) and Jupyter notebooks (.ipynb)
70
70
  - This tool can only read files, not directories. To list a directory, use ls via the Bash tool.
71
- - You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.
71
+ - Do not read a file again just to check an edit you made to it: Edit and Write report an error when they fail.
72
72
  - If you read a file that exists but has empty contents you will receive a warning in place of file contents.`,
73
73
  input_schema: {
74
74
  type: 'object',
@@ -206,10 +206,8 @@ export const WriteTool = {
206
206
 
207
207
  Usage:
208
208
  - This tool will overwrite the existing file if there is one at the provided path.
209
- - If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.
210
- - Prefer editing an existing file when that is the natural place for a change, but create new files whenever the task needs them (code, tests, scripts, configs, data).
211
- - Do not create documentation files (*.md, READMEs) unless the user asks for them or the task clearly calls for one.
212
- - Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`,
209
+ - An existing file must have been read with the Read tool first (a Grep result does not count); otherwise this tool fails.
210
+ - Missing parent directories are created.`,
213
211
  input_schema: {
214
212
  type: 'object',
215
213
  properties: {
@@ -306,10 +304,8 @@ export const EditTool = {
306
304
  description: `Performs exact string replacements in files.
307
305
 
308
306
  Usage:
309
- - You must use your \`Read\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
307
+ - You must use your \`Read\` tool at least once in the conversation before editing (a Grep result does not count). This tool will error if you attempt an edit without reading the file.
310
308
  - When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
311
- - Prefer editing existing files when that is the natural place for a change; create new files whenever the task needs them.
312
- - Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
313
309
  - The edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
314
310
  - Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
315
311
  - To create a new file, pass an empty old_string with the full content as new_string (the file must not exist).`,
@@ -15,7 +15,7 @@ import { ListPeersTool, MessagePeerTool } from './peers.js';
15
15
  // `peers`: an interactive session, which can talk to the other sessions on this machine.
16
16
  export function buildTools(config, { agents, skills, mcpTools = [], restart = false, peers = false }) {
17
17
  return [
18
- makeTaskTool(agents),
18
+ makeTaskTool(agents, config),
19
19
  ...(skills?.size ? [makeSkillTool(skills)] : []),
20
20
  TaskOutputTool,
21
21
  TaskStopTool,
@@ -4,44 +4,15 @@
4
4
  export const TodoWriteTool = {
5
5
  name: 'TodoWrite',
6
6
  readOnly: true,
7
- description: `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
7
+ description: `Create and update a task list for the current request. It helps you keep track of a task with several steps and shows the user where you are.
8
8
 
9
- ## When to Use This Tool
10
- Use this tool proactively in these scenarios:
11
- 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
12
- 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
13
- 3. User explicitly requests todo list - When the user directly asks you to use the todo list
14
- 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
15
- 5. After receiving new instructions - Immediately capture user requirements as todos
16
- 6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
17
- 7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
9
+ When to use it: a task with several distinct steps, several tasks the user listed, or when the user asks for a list. Skip it for a single straightforward task, a few trivial steps, or a conversational request. Each update is a request that re-reads the conversation, so use the list where it helps, not as a formality.
18
10
 
19
- ## When NOT to Use This Tool
20
- Skip using this tool when:
21
- 1. There is only a single, straightforward task
22
- 2. The task is trivial and tracking it provides no organizational benefit
23
- 3. The task can be completed in less than 3 trivial steps
24
- 4. The task is purely conversational or informational
25
-
26
- ## Task States and Management
27
- 1. **Task States**:
28
- - pending: Task not yet started
29
- - in_progress: Currently working on (limit to ONE task at a time)
30
- - completed: Task finished successfully
31
- **IMPORTANT**: Task descriptions must have two forms:
32
- - content: The imperative form describing what needs to be done (e.g., "Run tests")
33
- - activeForm: The present continuous form shown during execution (e.g., "Running tests")
34
- 2. **Task Management**:
35
- - Update task status in real-time as you work
36
- - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
37
- - Exactly ONE task must be in_progress at any time (not less, not more)
38
- - Remove tasks that are no longer relevant from the list entirely
39
- 3. **Task Completion Requirements**:
40
- - ONLY mark a task as completed when you have FULLY accomplished it
41
- - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
42
- - Never mark a task as completed if tests are failing, the implementation is partial, or you hit unresolved errors
43
-
44
- When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`,
11
+ How:
12
+ - Each item has \`content\`, the imperative form ("Run tests"), and \`activeForm\`, the present continuous form shown while it is in progress ("Running tests").
13
+ - Statuses are pending, in_progress and completed; keep exactly one item in_progress while you work.
14
+ - Keep it current: mark an item completed once it is done, in the same response as the next tool calls you make anyway rather than in a response of its own. Add follow-up items you discover and remove ones that no longer apply.
15
+ - Mark an item completed only when it is fully done: not while tests fail, the work is partial or an error is unresolved.`,
45
16
  input_schema: {
46
17
  type: 'object',
47
18
  properties: {
@@ -66,7 +37,7 @@ When in doubt, use this tool. Being proactive with task management demonstrates
66
37
  const todos = Array.isArray(input.todos) ? input.todos.filter((t) => t && t.content) : [];
67
38
  ctx.agent.todos = todos.every((t) => t.status === 'completed') ? [] : todos;
68
39
  return {
69
- content: 'Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable',
40
+ content: 'The todo list is updated.',
70
41
  display: { todos },
71
42
  };
72
43
  },