@yanzc/claude-pro 0.5.9 → 0.7.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/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).
@@ -12,7 +13,7 @@ import fs from 'node:fs';
12
13
  import os from 'node:os';
13
14
  import crypto from 'node:crypto';
14
15
  import { stripAnsi } from './ui/ansi.js';
15
- import { toolHeader, renderToolResult } from './ui/render.js';
16
+ import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
16
17
  import { uploadFile, downloadFile } from './transfer.js';
17
18
 
18
19
  export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
@@ -119,6 +120,8 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
119
120
  if (b.type === 'text') {
120
121
  const raw = String(b.text || '');
121
122
  if (raw.startsWith('This session is being continued')) { items.push({ k: 'summary', text: raw }); continue; }
123
+ const bash = bashModeLines(raw); // `!command`: as it was shown when it ran
124
+ if (bash) { items.push({ k: 'output', lines: [...bash, ''] }); continue; }
122
125
  const text = raw.startsWith('<system-reminder>') ? '' : shownUserText(raw);
123
126
  if (text) items.push({ k: 'user', text });
124
127
  } else if (b.type === 'image') {
@@ -185,12 +188,14 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
185
188
 
186
189
  export const newRemoteId = () => crypto.randomBytes(9).toString('base64url');
187
190
 
188
- // Whether an interactive session logged in to the gateway goes online there by itself (CLAUDE_PRO_ONLINE=0: only with /rc).
191
+ // Whether an interactive session logged in to the gateway goes online there (it does unless CLAUDE_PRO_ONLINE=0,
192
+ // which only the self-check and the tests set).
189
193
  export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_ONLINE || '');
190
194
 
191
195
  export class RemoteControl {
192
196
  // gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model}, seed() -> items, status() -> object,
193
- // send(text), interrupt(), answer(body) (each returns an object or throws), changed() (online or viewers changed).
197
+ // send(text, images), interrupt(), answer(body), options(body), suggest(body), list(body) (each returns an object
198
+ // or a promise of one, or throws), changed() (online or viewers changed).
194
199
  constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
195
200
  this.base = String(gateway.url).replace(/\/+$/, '');
196
201
  this.apiKey = gateway.apiKey;
@@ -216,6 +221,7 @@ export class RemoteControl {
216
221
  this.registered = false;
217
222
  this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
218
223
  this.peerPending = new Set(); // messages being handled now, acknowledged when done
224
+ this.replying = new Set(); // answers to the page's commands on their way
219
225
  }
220
226
 
221
227
  get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
@@ -333,20 +339,33 @@ export class RemoteControl {
333
339
  if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
334
340
  if (!cmd.cid) return;
335
341
  if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
336
- let result;
342
+ // close() waits for it: a /cd from the page restarts the session before its answer goes out
343
+ const reply = (result) => {
344
+ const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
345
+ this.replying.add(sent);
346
+ sent.finally(() => this.replying.delete(sent));
347
+ this.scheduleFlush(30);
348
+ };
349
+ const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
350
+ let r;
337
351
  try {
338
- const body = cmd.body || {};
339
- let r;
340
- if (cmd.type === 'send') r = this.handlers.send(String(body.text ?? ''));
352
+ const body = cmd.body && typeof cmd.body === 'object' ? cmd.body : {};
353
+ // send, interrupt and dialog act; options, suggest and list only look (and are answered while it works)
354
+ if (cmd.type === 'send') r = this.handlers.send(String(body.text ?? ''), body.images);
341
355
  else if (cmd.type === 'interrupt') r = this.handlers.interrupt();
342
356
  else if (cmd.type === 'dialog') r = this.handlers.answer(body);
357
+ else if (cmd.type === 'options' && this.handlers.options) r = this.handlers.options(body);
358
+ else if (cmd.type === 'suggest' && this.handlers.suggest) r = this.handlers.suggest(body);
359
+ else if (cmd.type === 'list' && this.handlers.list) r = this.handlers.list(body);
360
+ else if (cmd.type === 'output' && this.handlers.output) r = this.handlers.output(body);
343
361
  else throw new Error(`Unknown command: ${cmd.type}`);
344
- result = { cid: cmd.cid, ok: true, ...(r || {}) };
345
362
  } catch (e) {
346
- result = { cid: cmd.cid, ok: false, error: e.message };
363
+ failed(e);
364
+ return;
347
365
  }
348
- this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
349
- this.scheduleFlush(30);
366
+ // an answer that takes a while (a list of models from the gateway, a directory) is sent when it is there
367
+ if (typeof r?.then === 'function') r.then((v) => reply({ cid: cmd.cid, ok: true, ...(v || {}) }), failed);
368
+ else reply({ cid: cmd.cid, ok: true, ...(r || {}) });
350
369
  }
351
370
 
352
371
  // ------------------------------------------------------------ messages of the account's other sessions
@@ -473,12 +492,17 @@ export class RemoteControl {
473
492
 
474
493
  // What decides whether the status is sent again: all of it while a page watches; while none does, only what
475
494
  // the gateway's session list shows (the token count of a busy session would otherwise go out every few seconds).
495
+ // `asking` (a question waits) is in it too: the gateway tells the user about it even with no page open.
476
496
  statusKey(status) {
477
497
  if (this.viewing) return JSON.stringify({ ...status, elapsed: 0 });
478
- const { busy, title, model, cwd, name } = status;
479
- return JSON.stringify({ busy, title, model, cwd, name });
498
+ const { busy, asking, title, model, cwd, name } = status;
499
+ return JSON.stringify({ busy, asking, title, model, cwd, name });
480
500
  }
481
501
 
502
+ // What is sent at once, without the wait between statuses of an unwatched session: a task that started or ended,
503
+ // a question that came or was answered.
504
+ urgentKey(status) { return `${Boolean(status.busy)}|${Boolean(status.asking)}`; }
505
+
482
506
  // What has changed goes into the next upload: a snapshot when one is due, else the events; and the status.
483
507
  flush() {
484
508
  if (this.closed || !this.registered) return;
@@ -489,6 +513,7 @@ export class RemoteControl {
489
513
  this.events = [];
490
514
  this.sinceSnapshot = 0;
491
515
  this.lastStatus = this.statusKey(status);
516
+ this.lastUrgent = this.urgentKey(status);
492
517
  this.lastStatusAt = Date.now();
493
518
  this.outbox.push({ t: 'snapshot', seq: this.seq, items: snapshotItems(this.state.items), status });
494
519
  } else if (this.events.length) {
@@ -497,8 +522,10 @@ export class RemoteControl {
497
522
  this.events = [];
498
523
  }
499
524
  const key = this.statusKey(status);
500
- if (key !== this.lastStatus && Date.now() - this.lastStatusAt >= (this.viewing ? 0 : IDLE_STATUS_MS)) {
525
+ const urgent = this.urgentKey(status);
526
+ if (key !== this.lastStatus && (urgent !== this.lastUrgent || Date.now() - this.lastStatusAt >= (this.viewing ? 0 : IDLE_STATUS_MS))) {
501
527
  this.lastStatus = key;
528
+ this.lastUrgent = urgent;
502
529
  this.lastStatusAt = Date.now();
503
530
  this.outbox.push({ t: 'status', status });
504
531
  }
@@ -525,8 +552,18 @@ export class RemoteControl {
525
552
 
526
553
  // Ends the connection; resolves once the gateway was told (or gave up waiting). `restarting`: the session comes
527
554
  // back at once with the same id, and the pages wait for it.
528
- async close({ restarting = false } = {}) {
529
- if (this.closed) return;
555
+ close({ restarting = false } = {}) {
556
+ this.closeDone ??= this.shutdown(restarting);
557
+ return this.closeDone;
558
+ }
559
+
560
+ async shutdown(restarting) {
561
+ // First the answers on their way, while the command stream is still open (the gateway fails what is still
562
+ // waiting once it closes). Among them the answer to the command that ends the session: a /cd or /exit from the
563
+ // page closes it from inside that command, and its answer is sent when the command returns, hence the wait for
564
+ // the current call to finish first.
565
+ await null;
566
+ if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
530
567
  this.closing = true; // what flush() collects now goes out with the last message, not on its own
531
568
  this.flush();
532
569
  this.closed = true;
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, '-');
@@ -51,6 +52,30 @@ export function autoMemoryDir(cwd) {
51
52
  return path.join(projectDir(cwd), 'memory');
52
53
  }
53
54
 
55
+ // /cd: the conversation in `file` goes on in another working directory, so its file goes to that directory's project
56
+ // (where /resume there finds it, and where a SessionStore(cwd, id) appends), with the new directory in its first
57
+ // line. The copy is written now; commit() removes the old file, undo() the copy. {file, commit, undo}.
58
+ export function moveSession(file, id, cwd) {
59
+ const target = path.join(projectDir(cwd), `${id}.jsonl`);
60
+ const none = { file: target, commit() {}, undo() {} };
61
+ if (path.resolve(target) === path.resolve(file)) return none;
62
+ let text;
63
+ try { text = fs.readFileSync(file, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return none; throw e; } // nothing written yet
64
+ const nl = text.indexOf('\n');
65
+ let first = nl >= 0 ? text.slice(0, nl) : text;
66
+ try {
67
+ const meta = JSON.parse(first);
68
+ if (meta?.type === 'meta') first = JSON.stringify({ ...meta, cwd });
69
+ } catch { /* not a meta line: kept as it is */ }
70
+ fs.mkdirSync(path.dirname(target), { recursive: true });
71
+ fs.writeFileSync(target, first + (nl >= 0 ? text.slice(nl) : '\n'));
72
+ return {
73
+ file: target,
74
+ commit() { try { fs.rmSync(file, { force: true }); } catch { /* two copies: /resume shows it in both places */ } },
75
+ undo() { try { fs.rmSync(target, { force: true }); } catch { /* left behind */ } },
76
+ };
77
+ }
78
+
54
79
  export class SessionStore {
55
80
  constructor(cwd, id = crypto.randomUUID()) {
56
81
  this.cwd = cwd;
@@ -88,11 +113,12 @@ export class SessionStore {
88
113
  }
89
114
  // The system prompt this conversation runs behind, kept so that a resumed one continues behind the same prompt
90
115
  // 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.
116
+ // and whenever it changes (after a compaction); the newest one wins when the session is loaded. With it goes the
117
+ // fingerprint of the code that built it: after that code changes, a resumed conversation gets a new prompt.
92
118
  setSystemPrompt(text) {
93
119
  if (!text || text === this.systemPrompt) return;
94
120
  this.systemPrompt = text;
95
- this.append({ type: 'meta', systemPrompt: text, at: Date.now() });
121
+ this.append({ type: 'meta', systemPrompt: text, promptCode: PROMPT_CODE_VERSION, at: Date.now() });
96
122
  }
97
123
 
98
124
  static load(file) {
@@ -123,6 +149,7 @@ export class SessionStore {
123
149
  topic: typeof meta.topic === 'string' && meta.topic.trim() ? meta.topic : null,
124
150
  name: typeof meta.name === 'string' && meta.name.trim() ? meta.name : null,
125
151
  systemPrompt: typeof meta.systemPrompt === 'string' && meta.systemPrompt.trim() ? meta.systemPrompt : null,
152
+ promptCode: typeof meta.promptCode === 'string' ? meta.promptCode : null,
126
153
  cost: Number(meta.cost) > 0 ? Number(meta.cost) : 0,
127
154
  cacheUntil: Number.isFinite(meta.cacheUntil) && meta.cacheUntil >= 0 ? meta.cacheUntil : null,
128
155
  };
package/src/supervisor.js CHANGED
@@ -39,16 +39,18 @@ export function sessionEntry(entry, platform = process.platform) {
39
39
  }
40
40
 
41
41
  // Whether this invocation is an interactive session that should run under the supervisor.
42
+ // A background session (--headless, started by the computer service) has no terminal and is one all the same.
42
43
  export function shouldSupervise(argv, env = process.env, isTty = (fd) => tty.isatty(fd)) {
43
44
  if (env[ENV_SUPERVISED] || /^(1|true|yes)$/i.test(env.CLAUDE_PRO_NO_SUPERVISOR || '')) return false;
44
- if (!isTty(0) || !isTty(1)) return false;
45
- if (argv[0] === 'config') return false;
45
+ if (['config', 'host', 'attach', 'connect'].includes(argv[0])) return false;
46
+ if ((!isTty(0) || !isTty(1)) && !argv.includes('--headless')) return false;
46
47
  return !argv.some((a) => NOT_INTERACTIVE.has(a));
47
48
  }
48
49
 
49
50
  function putTerminalRight() {
50
51
  // The child may have died with the terminal in the mode it had set for itself.
51
52
  // (the fullscreen renderer's alternate screen and mouse reporting included)
53
+ if (!tty.isatty(1)) return; // a background session's log
52
54
  try { process.stdout.write('\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1049l\x1b[?2004l\x1b[?25h'); } catch { /* nothing to do */ }
53
55
  try { if (tty.isatty(0)) process.stdin.setRawMode(false); } catch { /* nothing to do */ }
54
56
  }
@@ -84,7 +86,8 @@ export function supervise(argv, { entry, env = process.env, execPath = process.e
84
86
  const childEnv = { ...env, [ENV_SUPERVISED]: '1', [ENV_RESTART_FILE]: stateFile };
85
87
  if (restarted) childEnv[ENV_RESTARTED] = '1'; else delete childEnv[ENV_RESTARTED];
86
88
  const startedAt = Date.now();
87
- child = spawn(execPath, [sessionEntry(entry), ...argv], { stdio: 'inherit', env: childEnv });
89
+ // a background session has no console: without windowsHide Windows would give its child a window of its own
90
+ child = spawn(execPath, [sessionEntry(entry), ...argv], { stdio: 'inherit', env: childEnv, windowsHide: argv.includes('--headless') });
88
91
  child.on('error', (e) => {
89
92
  child = null;
90
93
  err.write(`claude-pro: could not start (${e.message})\n`);
package/src/tools/bash.js CHANGED
@@ -57,7 +57,7 @@ export function shutdownBackgroundShells() {
57
57
  }
58
58
 
59
59
  export function listBackgroundShells() {
60
- return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, status: bg.status, exitCode: bg.exitCode }));
60
+ return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, description: bg.description || '', status: bg.status, exitCode: bg.exitCode, startedAt: bg.startedAt }));
61
61
  }
62
62
 
63
63
  export function makeBashTool(config) {
@@ -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: {
@@ -109,7 +104,7 @@ Only create commits when requested by the user. When asked to commit: run git st
109
104
  if (input.run_in_background) {
110
105
  const child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
111
106
  const id = `bash_${++bgCounter}`;
112
- const bg = { child, command, output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
107
+ const bg = { child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
113
108
  background.set(id, bg);
114
109
  // Decode as a stream: a multi-byte character (CJK text) can be split between two chunks.
115
110
  child.stdout.setEncoding('utf8');