@yanzc/claude-pro 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +240 -62
  4. package/src/agents.js +3 -2
  5. package/src/api.js +83 -41
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +177 -71
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +153 -153
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +2 -1
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +6 -62
  27. package/src/ratelimit.js +3 -5
  28. package/src/remote.js +26 -10
  29. package/src/restart.js +3 -0
  30. package/src/runtime.js +33 -10
  31. package/src/selfcheck.js +3 -3
  32. package/src/session.js +93 -3
  33. package/src/supervisor.js +10 -1
  34. package/src/tools/bash.js +19 -18
  35. package/src/tools/browser.js +365 -0
  36. package/src/tools/code.js +430 -0
  37. package/src/tools/effort.js +3 -4
  38. package/src/tools/files.js +92 -19
  39. package/src/tools/index.js +6 -0
  40. package/src/tools/notebook.js +11 -4
  41. package/src/tools/processes.js +274 -0
  42. package/src/tools/search.js +104 -21
  43. package/src/tools/web.js +316 -46
  44. package/src/trace.js +0 -4
  45. package/src/ui/ansi.js +92 -13
  46. package/src/ui/dialogs.js +16 -54
  47. package/src/ui/editor.js +231 -34
  48. package/src/ui/markdown.js +1 -2
  49. package/src/ui/render.js +1 -2
  50. package/src/ui/repl.js +246 -119
  51. package/src/ui/screen.js +139 -31
  52. package/src/updater.js +135 -165
  53. package/src/utils/clipboard.js +5 -3
  54. package/src/utils/paths.js +15 -17
  55. package/src/utils/shell.js +75 -21
  56. package/.env.example +0 -29
  57. package/src/verify.js +0 -57
package/src/print.js CHANGED
@@ -2,6 +2,9 @@
2
2
  // (or JSON), tool activity goes to stderr with --verbose.
3
3
 
4
4
  import { createRuntime } from './runtime.js';
5
+ import { closeBrowser } from './browser/session.js';
6
+ import { shutdownInterpreters } from './tools/code.js';
7
+ import { shutdownBackgroundShells } from './tools/bash.js';
5
8
  import { SessionStore } from './session.js';
6
9
  import { describePause, resumeText, shouldAnnounce } from './ratelimit.js';
7
10
  import { c } from './ui/ansi.js';
@@ -88,9 +91,10 @@ export async function runPrint({ prompt, flags, cwd, stdout = process.stdout, st
88
91
  result = await runtime.agent.run(runtime.agent.drainNotifications(), { signal: ctrl.signal });
89
92
  }
90
93
  } catch (e) {
91
- if (format === 'json') emit({ type: 'result', is_error: true, error: e.message });
94
+ // stream-json ends with a result as well, or its reader waits for one that never comes
95
+ if (format === 'json' || format === 'stream-json') emit({ type: 'result', subtype: 'error', is_error: true, error: e.message });
92
96
  else err(c.red(`Error: ${e.message}`));
93
- runtime.tasks.killAll(); runtime.mcp.close();
97
+ runtime.tasks.killAll(); runtime.mcp.close(); closeBrowser(); shutdownInterpreters(); shutdownBackgroundShells();
94
98
  return 1;
95
99
  } finally {
96
100
  process.off('SIGINT', onSigint);
@@ -111,6 +115,8 @@ export async function runPrint({ prompt, flags, cwd, stdout = process.stdout, st
111
115
  } else {
112
116
  stdout.write(result.text + '\n');
113
117
  }
114
- runtime.tasks.killAll(); runtime.mcp.close();
118
+ // an open connection, interpreter or background shell (a dev server started with run_in_background) keeps the
119
+ // process alive: -p never ended
120
+ runtime.tasks.killAll(); runtime.mcp.close(); closeBrowser(); shutdownInterpreters(); shutdownBackgroundShells();
115
121
  return result.interrupted ? 130 : 0;
116
122
  }
@@ -31,12 +31,6 @@ export function activePromptName() {
31
31
  return isPromptName(name) ? String(name).trim() : null;
32
32
  }
33
33
 
34
- export function loadPrompt(name) {
35
- const file = profileFile(name);
36
- const text = fs.readFileSync(file, 'utf8');
37
- return { name: String(name), file, text };
38
- }
39
-
40
34
  // Returns null for the built-in prompt, or a descriptor with an error when the selected file disappeared.
41
35
  export function loadActivePrompt() {
42
36
  const name = activePromptName();
package/src/prompts.js CHANGED
@@ -1,4 +1,4 @@
1
- // System prompts for the main agent, sub-agents and compaction.
1
+ // System prompts for the main agent and sub-agents (the compaction's own are in compaction.js).
2
2
 
3
3
  import fs from 'node:fs';
4
4
  import crypto from 'node:crypto';
@@ -43,8 +43,7 @@ function instructionFiles(cwd) {
43
43
  .join('\n\n');
44
44
  }
45
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, mcpInstructions = '', selfRestart = false, installedCopy = false, autoCompact = true, snapshot = null }) {
46
+ export function mainSystemPrompt({ cwd, model, shellName, extra = '', autoMemory = null, mcpInstructions = '', selfRestart = false, installedCopy = false, snapshot = null }) {
48
47
  const files = instructionFiles(cwd);
49
48
  const memoryText = files
50
49
  ? `\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}`
@@ -70,8 +69,8 @@ You run on the user's own test machine with full access: tool calls run without
70
69
  - 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).
71
70
  - 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.
72
71
  - 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.
73
- - Use AskUserQuestion only for decisions that really are the user's to make.${autoCompact ? `
74
- - 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.` : ''}
72
+ - Use AskUserQuestion only for decisions that really are the user's to make.
73
+ - 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.
75
74
 
76
75
  # Boundaries
77
76
  - 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,8 +80,9 @@ You run on the user's own test machine with full access: tool calls run without
81
80
  - Edits made with Write, Edit, MultiEdit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
82
81
 
83
82
  # Tools
84
- - Call independent tools together in one response so that they run in parallel; run dependent ones one after another.
83
+ - Call independent tools together in one response so that they run in parallel. Calls that change something (edits, commands) run one after another in the order you wrote them, so steps that depend only on each other's effect go in one response too: the edits of a change and the command that builds or tests it. When an edit fails, the commands after it in that response are not run. Start a new response when what you send next depends on what a result shows.
85
84
  - 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.
85
+ - For GitHub (repositories, code, issues, pull requests, releases, Actions), use the gh CLI through Bash (gh search repos|code|issues, gh issue view, gh pr view, gh api) rather than fetching github.com pages: it returns exact and complete data, private repositories included. When gh is missing or not logged in, use WebSearch and WebFetch.
86
86
  - If a tool call is blocked (by 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.
87
87
  - Tool results and user messages may include <system-reminder> tags: information added by the harness, not part of the user's request.
88
88
 
@@ -134,62 +134,6 @@ ${message}
134
134
  ${current ? 'Does this message start a new topic (a different task or question), or does it continue the current one (a follow-up, "continue", an answer, a correction)? ' : ''}Reply with only a JSON object: {"isNewTopic": ${current ? 'true or false' : 'true'}, "title": ...}. For a new topic, "title" names it in 2 to 6 words (at most about 16 characters in Chinese or Japanese), in the language of the user's message, with no quotes, no emoji and no punctuation at the end. Otherwise "title" is null.`;
135
135
  }
136
136
 
137
- // The system prompt of the plain summary request (see Agent.requestSummary).
138
- export const SUMMARY_SYSTEM = 'You are a helpful AI assistant tasked with summarizing conversations.';
139
-
140
- export function compactPrompt(instructions) {
141
- return `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools: the conversation above is complete, and the only thing wanted now is the structured state and summary below.
142
-
143
- Your task is to preserve the state needed to continue the work after this conversation is compacted and to create a detailed summary of the conversation. Pay close attention to the user's explicit requests, your previous actions, exact file paths, commands, test results, failures and unresolved questions.
144
-
145
- First write exactly one <work-state> block containing one valid JSON object. Do not use markdown fences inside the block. Use this schema exactly; use an empty string or [] when a field has no value:
146
- <work-state>
147
- {"schema_version":1,"objective":"","constraints":[],"decisions":[],"files":[],"edits":[],"tests":[],"failures":[],"open_questions":[],"next_action":"","tool_artifacts":[]}
148
- </work-state>
149
- All array items must be strings. Keep paths, commands, error messages and next actions precise. The state is machine-validated, so do not add prose before or after the JSON inside <work-state>.
150
-
151
- Then write a detailed narrative in <summary> tags. Do your reasoning in your thinking, not in the reply: only the work-state and the summary are kept, so text outside them is thrown away (and writing it makes the compaction take minutes longer). The narrative should retain technical details, code patterns and architectural decisions that would be useful if the structured state is incomplete.
152
-
153
- Use these summary sections:
154
- 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
155
- 2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
156
- 3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Include full code snippets where applicable and a summary of why each file read or edit is important.
157
- 4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback.
158
- 5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
159
- 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the user's feedback and changing intent.
160
- 7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
161
- 8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, including file names and code snippets.
162
- 9. Optional Next Step: The next step directly in line with the user's most recent explicit request. Include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off.
163
-
164
- Write the summary in the same language the user has been using.
165
- Do NOT call any tools. Respond with text only.${instructions ? `\n\nAdditional instructions from the user for this summary:\n${instructions}` : ''}`;
166
- }
167
-
168
- // The instruction for /rewind's "Summarize from here" (part 'after') and "Summarize up to here" ('before'): only
169
- // that part of the conversation is summarized, the rest stays in it word for word.
170
- export function partialCompactPrompt(part, label, instructions = '') {
171
- const at = label ? `the user's message that begins "${String(label).slice(0, 200)}"` : 'the point the user chose';
172
- const scope = part === 'before'
173
- ? `Summarize ONLY the part of the conversation BEFORE ${at}. That message and everything after it stay in the conversation word for word: do not summarize them. The summary replaces only what comes before that message, so it has to carry everything from that earlier part that the rest of the conversation builds on.`
174
- : `Summarize ONLY the part of the conversation that starts with ${at} (that message included) and goes on to the end. Everything before that message stays in the conversation word for word: do not summarize it. The summary replaces only that later part.`;
175
- return compactPrompt(`${scope}${instructions ? `\n${instructions}` : ''}`);
176
- }
177
-
178
- // The message that stands in the conversation for the part a partial summary replaced.
179
- export function partialSummaryMessage(part, summary, workState = null) {
180
- const state = workState ? `\n\nThe validated structured work state for this summarized section is:\n<work-state>\n${JSON.stringify(workState, null, 2)}\n</work-state>` : '';
181
- return part === 'before'
182
- ? `[Summarized conversation] The earlier part of this conversation was summarized at the user's request; the messages after this one are as they were. The summary of the earlier part:${state}\n${summary}`
183
- : `[Summarized conversation] The later part of this conversation, from the user's message where this summary stands to where it was, was summarized at the user's request. The summary of that part:${state}\n${summary}`;
184
- }
185
-
186
- export function continuationMessage(summary, { auto, workState = null, workStateWarning = '' }) {
187
- const state = workState ? `\n\nThe validated structured work state is:\n<work-state>\n${JSON.stringify(workState, null, 2)}\n</work-state>` : '';
188
- const warning = workStateWarning ? `\n\n<system-reminder>${workStateWarning}</system-reminder>` : '';
189
- return `This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:${state}${warning}
190
- ${summary}${auto ? '\n\nPlease continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.' : ''}`;
191
- }
192
-
193
137
  export const INIT_PROMPT = `Please analyze this codebase and create a CLAUDE.md file, which will be given to future instances of this coding agent to operate in this repository.
194
138
 
195
139
  What to add:
package/src/ratelimit.js CHANGED
@@ -161,10 +161,8 @@ function limitMessage(err, rl, state, budget, now, why) {
161
161
  // - a short announced wait: a few quick retries, counted like any other;
162
162
  // - nothing announced: back off 1s, 2s, 4s ... up to rateLimitPoll (5 minutes) between attempts, within the budget.
163
163
  //
164
- // An overloaded API (529, overloaded_error) backs off from CLAUDE_CODE_OVERLOADED_RETRY_BASE_DELAY_MS (1s) to
165
- // CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS (32s), as in Claude Code. When the usual retries are used up it does not
166
- // give up but pauses and tries again at the longest delay, like Claude Code's unattended retry mode, for at most
167
- // overloadedMaxWait (CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS, by default the rate limit budget) in all.
164
+ // An overloaded API (529, overloaded_error) backs off from 1s to 32s. When the usual retries are used up it does not
165
+ // give up but pauses and tries again at the longest delay, within the same wait budget as a rate limit.
168
166
  export function planRetry(err, state, config, { now = Date.now(), rand = Math.random, allowWait = true } = {}) {
169
167
  if (!err.retryable) return { action: 'throw' };
170
168
  const maxRetries = config.maxRetries;
@@ -247,7 +245,7 @@ export function describePause(ev, now = Date.now()) {
247
245
  // announced for the same pause (null at the first one). Polling repeats every few minutes and the
248
246
  // announced reset moves a little between waits: those only continue the pause already announced,
249
247
  // unless the reset moved by more than two minutes.
250
- export const resumeText = (ev) => (ev?.overloaded ? 'The API is answering again; continuing.' : 'The limit has cleared; continuing.');
248
+ export const resumeText = (ev) => (ev?.woken ? 'Going on with the model you chose.' : ev?.overloaded ? 'The API is answering again; continuing.' : 'The limit has cleared; continuing.');
251
249
 
252
250
  export function shouldAnnounce(prev, ev) {
253
251
  if (!prev) return true;
package/src/remote.js CHANGED
@@ -14,6 +14,7 @@ import os from 'node:os';
14
14
  import crypto from 'node:crypto';
15
15
  import { stripAnsi } from './ui/ansi.js';
16
16
  import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
17
+ import { shownQuotes } from './ui/editor.js';
17
18
 
18
19
  export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
19
20
  const MAX_ITEMS = 800; // kept for a snapshot; the oldest are dropped beyond that
@@ -98,9 +99,10 @@ export function hydrate(items) {
98
99
  return state;
99
100
  }
100
101
 
101
- // What a user message of the conversation looks like on the page: without the notes for the model.
102
+ // What a user message of the conversation looks like on the page: without the notes for the model, a quote as its
103
+ // first lines (see Editor.insertQuote).
102
104
  function shownUserText(text) {
103
- return String(text)
105
+ return shownQuotes(text)
104
106
  .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')
105
107
  .replace(/<peer-message from="([^"]*)" kind="(task|reply)">\n?/g, (_, from, kind) => `✉ ${kind === 'reply' ? 'answer from' : 'task from'} @${from}: `)
106
108
  .replace(/\n?<\/peer-message>/g, '')
@@ -210,7 +212,6 @@ export class RemoteControl {
210
212
  this.id = /^[\w-]{8,64}$/.test(id || '') ? id : newRemoteId();
211
213
  this.handlers = handlers;
212
214
  this.fetch = fetchImpl;
213
- this.url = null; // the session's page on the gateway
214
215
  this.online = false; // the command stream is open
215
216
  this.viewers = null; // pages watching, as the gateway counts them (null: not told yet)
216
217
  this.closed = false;
@@ -277,7 +278,6 @@ export class RemoteControl {
277
278
  const commands = this.commands;
278
279
  const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...info, ...(commands.length ? { commands } : {}) });
279
280
  if (data.id) this.id = data.id;
280
- this.url = data.url || this.url || `${this.base}/user`;
281
281
  this.registered = true;
282
282
  this.needSnapshot = true;
283
283
  }
@@ -288,7 +288,15 @@ export class RemoteControl {
288
288
  while (!this.closed) {
289
289
  const began = Date.now();
290
290
  try {
291
- if (!this.registered) await this.register();
291
+ if (!this.registered) {
292
+ await this.register();
293
+ // closed while it registered (/logout, another account): the session that ended must not go online again,
294
+ // and the registration that just went through gets the bye that close() could not send yet
295
+ if (this.closed) {
296
+ this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'bye', restarting: false }] }, { timeout: 1500 }).catch(() => {});
297
+ break;
298
+ }
299
+ }
292
300
  await this.listen();
293
301
  } catch (e) {
294
302
  if (e.status === 404) this.registered = false; // the gateway forgot the session (restarted): register again
@@ -325,6 +333,7 @@ export class RemoteControl {
325
333
  }
326
334
 
327
335
  async listen() {
336
+ if (this.closed) return;
328
337
  const abort = new AbortController();
329
338
  this.streamAbort = abort;
330
339
  const res = await this.fetch(`${this.base}/v1/remote/sessions/${encodeURIComponent(this.id)}/commands`, {
@@ -367,6 +376,7 @@ export class RemoteControl {
367
376
  }
368
377
 
369
378
  command(cmd) {
379
+ if (this.closed) return; // the page of a session that has gone offline steers nothing
370
380
  if (cmd.type === 'viewers') {
371
381
  const was = this.viewers;
372
382
  this.viewers = Math.max(0, Number(cmd.count) || 0);
@@ -380,7 +390,7 @@ export class RemoteControl {
380
390
  if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
381
391
  // A command of the page, answered with POST …/results {cid, ok: true, …fields} or {cid, ok: false, error} (the
382
392
  // gateway waits 15 s for it, and takes it until 3 s after the stream closed). close() waits for the answers on
383
- // their way: a /cd or /exit from the page ends the session from inside its command.
393
+ // their way: a /cd from the page restarts the session from inside its command.
384
394
  const reply = (result) => {
385
395
  const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
386
396
  this.replying.add(sent);
@@ -449,8 +459,14 @@ export class RemoteControl {
449
459
  ev.seq = ++this.seq;
450
460
  applyEvent(this.state, ev);
451
461
  if (this.state.items.length > MAX_ITEMS) this.state.items.splice(0, this.state.items.length - MAX_ITEMS + 100);
462
+ if (ev.t === 'done') this.progress.delete(ev.id); // also while offline, when nothing takes it: it holds all the tool's output
452
463
  if (this.viewing && !this.needSnapshot) {
453
- this.events.push(ev);
464
+ // A streamed reply's deltas in a row go out as one: one event each made a full snapshot (up to 1.5 MB) due every
465
+ // few seconds of a long reply, since SNAPSHOT_EVERY counts events. The page takes the newest seq of the merged
466
+ // ones; it only skips events at or below the seq it has.
467
+ const last = this.events[this.events.length - 1];
468
+ if (ev.t === 'delta' && last?.t === 'delta' && last.kind === ev.kind) { last.text += ev.text; last.seq = ev.seq; }
469
+ else this.events.push(ev);
454
470
  this.scheduleFlush();
455
471
  }
456
472
  }
@@ -569,9 +585,9 @@ export class RemoteControl {
569
585
 
570
586
  async shutdown(restarting) {
571
587
  // First the answers on their way, while the command stream is still open (the gateway takes them until 3 s
572
- // after it closes). Among them the answer to the command that ends the session: a /cd, /restart or /exit from
573
- // the page closes it from inside that command, and its answer is sent when the command returns, hence the
574
- // wait for the current call to finish first.
588
+ // after it closes). Among them the answer to the command that restarts the session: a /cd from the page closes
589
+ // it from inside that command (the page may not end, restart or update it otherwise, see App.remoteSend), and its answer
590
+ // is sent when the command returns, hence the wait for the current call to finish first.
575
591
  await null;
576
592
  if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
577
593
  this.closing = true; // what flush() collects now goes out with the last message, not on its own
package/src/restart.js CHANGED
@@ -13,6 +13,9 @@ export { RESTART_EXIT_CODE };
13
13
 
14
14
  export const MAX_RESTARTS = 5; // more than this many within RESTART_WINDOW_MS is a loop, not a workflow
15
15
  export const RESTART_WINDOW_MS = 5 * 60_000;
16
+ // A change of the source that an idle session sees is loaded once the source has not changed for quietMs (plus up to
17
+ // spreadMs, so that the sessions of a machine do not all check and restart at the same moment): see App.startSourceWatch.
18
+ export const reloadTiming = { quietMs: 3 * 60_000, spreadMs: 10_000 };
16
19
 
17
20
  // True in a session that runs under the supervisor, so that it can restart.
18
21
  export function canRestart(env = process.env) {
package/src/runtime.js CHANGED
@@ -13,19 +13,20 @@ import { isAbort } from './api.js';
13
13
  import { McpManager } from './mcp.js';
14
14
  import { HookRunner } from './hooks.js';
15
15
  import { BackgroundTasks, taskNotification } from './tasks.js';
16
- import { autoMemoryDir, pruneToolResults, pruneCheckpoints, projectDir } from './session.js';
17
- import { loadAutoMemoryIndex, takeEnvSnapshot, localDate } from './context.js';
16
+ import { autoMemoryDir, pruneToolResults, pruneCheckpoints, pruneTraces, projectDir } from './session.js';
17
+ import { loadAutoMemoryIndex, takeEnvSnapshot, takeEnvSnapshotAsync, localDate } from './context.js';
18
18
  import { canRestart } from './restart.js';
19
19
  import { RuntimeTrace } from './trace.js';
20
20
  import { loadActivePrompt } from './prompt-profiles.js';
21
21
 
22
22
  export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
23
23
  const config = loadConfig({ cwd, flags });
24
- const trace = new RuntimeTrace({ cwd, sessionId, enabled: config.traceEnabled, dir: config.traceDir, maxBytes: config.traceMaxBytes });
24
+ const trace = new RuntimeTrace({ cwd, sessionId, enabled: config.traceEnabled });
25
25
  applyRememberedChoices(config, flags); // what /model and /effort chose last time
26
26
  if (flags.verify) config.verifyOverride = flags.verify;
27
27
  pruneToolResults(cwd);
28
28
  pruneCheckpoints(cwd);
29
+ pruneTraces(cwd);
29
30
  pruneStaleShellFiles();
30
31
  // Full access: nothing is ever asked.
31
32
  const checkpoints = new CheckpointStore(path.join(projectDir(cwd), 'checkpoints', `${Date.now()}-${crypto.randomBytes(3).toString('hex')}`));
@@ -56,9 +57,25 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
56
57
  const snapshots = new Map(); // directory -> {date, git}
57
58
  const snapshotFor = (dir) => {
58
59
  const key = path.resolve(dir);
59
- if (!snapshots.has(key)) snapshots.set(key, takeEnvSnapshot(key));
60
+ if (!snapshots.has(key)) snapshots.set(key, takeEnvSnapshot(key)); // blocks on git: prepareSnapshot usually came first
60
61
  return snapshots.get(key);
61
62
  };
63
+ // The snapshot of the project's directory for the prompt built next, taken without blocking: at the start, and
64
+ // waited for before a turn and after a compaction (see beforeTurn, refreshSystemPrompt), when the prompt is to be
65
+ // built again. Taken at the build itself, git blocked the program there.
66
+ let snapshotGen = 0; // invalidateSystemPrompt: a snapshot taken before is not the one wanted any more
67
+ let preparing = null;
68
+ runtime.prepareSnapshot = () => {
69
+ const key = path.resolve(cwd);
70
+ if (promptCache || snapshots.has(key)) return Promise.resolve();
71
+ if (preparing?.gen === snapshotGen) return preparing.promise;
72
+ const gen = snapshotGen;
73
+ const promise = takeEnvSnapshotAsync(key).then((s) => { if (gen === snapshotGen && !snapshots.has(key)) snapshots.set(key, s); }, () => {});
74
+ preparing = { gen, promise };
75
+ return promise;
76
+ };
77
+ // Whether the prompt can be built without waiting for git.
78
+ runtime.systemPromptReady = () => Boolean(promptCache) || snapshots.has(path.resolve(cwd));
62
79
  runtime.systemPrompt = () => {
63
80
  if (!promptCache) {
64
81
  const autoMemory = config.autoMemoryEnabled ? { dir: memoryDir, index: loadAutoMemoryIndex(memoryDir) } : null;
@@ -67,13 +84,13 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
67
84
  ? flags.systemPrompt
68
85
  : savedPrompt?.text != null
69
86
  ? savedPrompt.text
70
- : mainSystemPrompt({ cwd, model: config.model, shellName: shell.name, extra: flags.appendSystemPrompt || '', autoMemory, mcpInstructions: mcp.promptInstructions(), selfRestart: selfEdit, installedCopy: !SOURCE_CHECKOUT, autoCompact: config.autoCompactEnabled, snapshot: snapshotFor(cwd) });
87
+ : mainSystemPrompt({ cwd, model: config.model, shellName: shell.name, extra: flags.appendSystemPrompt || '', autoMemory, mcpInstructions: mcp.promptInstructions(), selfRestart: selfEdit, installedCopy: !SOURCE_CHECKOUT, snapshot: snapshotFor(cwd) });
71
88
  promptStale = false;
72
89
  }
73
90
  return promptCache;
74
91
  };
75
92
  // Build the prompt again at the next request: for a new conversation (/clear), another model, a compaction.
76
- runtime.invalidateSystemPrompt = () => { promptCache = null; promptStale = false; snapshots.clear(); notedDate = null; };
93
+ runtime.invalidateSystemPrompt = () => { promptCache = null; promptStale = false; snapshots.clear(); snapshotGen++; preparing = null; notedDate = null; };
77
94
  // Something it is built from changed in the middle of a conversation: note it, and leave the prompt as it is.
78
95
  runtime.deferSystemPromptRefresh = () => { if (promptCache) promptStale = true; };
79
96
  Object.defineProperty(runtime, 'systemPromptStale', { get: () => promptStale });
@@ -91,6 +108,10 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
91
108
  if (extra && !saved.endsWith(`\n\n${extra}`)) return false;
92
109
  const modelIn = (text) => /^You are powered by the model (.+)\.$/m.exec(text)?.[1];
93
110
  if (modelIn(saved) !== config.model.id) return false;
111
+ // a prompt from before the project's directory got another name (see projectDir) points the model to the old
112
+ // memory directory, where it would write again
113
+ const memoryAt = /memory for this project at `([^`]+)`/.exec(saved)?.[1];
114
+ if (memoryAt && path.resolve(memoryAt) !== path.resolve(memoryDir)) return false;
94
115
  promptCache = saved;
95
116
  promptStale = false;
96
117
  const then = /^Today's date: (\d{4}-\d{2}-\d{2})$/m.exec(saved)?.[1];
@@ -115,7 +136,8 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
115
136
 
116
137
  // Every agent uses the model selected for this session; effort may still be specific to the task.
117
138
  runtime.spawnSubagent = async ({ def, prompt, description, ctx, effort }) => {
118
- const model = config.model;
139
+ const spec = config.modelSpec;
140
+ const model = config.resolveModel(spec);
119
141
  const subIo = io.subagentIo ? io.subagentIo({ def, description, parentCtx: ctx }) : {};
120
142
  // The main agent is depth 0; an agent below the nesting limit may start sub-agents itself.
121
143
  const depth = (ctx.depth ?? ctx.agent?.depth ?? 0) + 1;
@@ -128,7 +150,7 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
128
150
  tools: subTools,
129
151
  systemPrompt: subagentSystemPrompt({ cwd: ctx.cwd, model, shellName: shell.name, agentPrompt: def.prompt, snapshot: snapshotFor(ctx.cwd), mcpInstructions: subTools.some((tool) => tool.mcp) ? mcp.promptInstructions() : '', readOnly: Boolean(def.readOnly) }),
130
152
  io: subIo,
131
- model,
153
+ model: () => config.resolveModel(spec), // the model of now, with the window the gateway's model list gives it
132
154
  isSubagent: true,
133
155
  cwd: ctx.cwd,
134
156
  name: def.name,
@@ -166,8 +188,9 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
166
188
  spawnSubagent: runtime.spawnSubagent,
167
189
  hooks,
168
190
  tasks,
169
- refreshSystemPrompt: () => runtime.invalidateSystemPrompt(), // a compaction starts the conversation over
170
- beforeTurn: () => runtime.noteDateChange(),
191
+ // a compaction starts the conversation over, from a prompt built again
192
+ refreshSystemPrompt: async () => { runtime.invalidateSystemPrompt(); await runtime.prepareSnapshot(); },
193
+ beforeTurn: async () => { runtime.noteDateChange(); await runtime.prepareSnapshot(); },
171
194
  trace,
172
195
  });
173
196
 
package/src/selfcheck.js CHANGED
@@ -10,9 +10,9 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10
10
  async function check() {
11
11
  const problems = [];
12
12
  const fail = (text) => problems.push(text);
13
- // The App starts as a session does (the fullscreen renderer, the update timer, ...), so that code only a real
14
- // start runs is checked too, but this process must not show up as a session, go online or install an update.
15
- Object.assign(process.env, { CLAUDE_PRO_PEERS: '0', CLAUDE_PRO_ONLINE: '0', CLAUDE_PRO_AUTO_UPDATE: '0' });
13
+ // The App starts as a session does (the fullscreen renderer, ...), so that code only a real start runs is checked
14
+ // too, but this process must not show up as a session or go online.
15
+ Object.assign(process.env, { CLAUDE_PRO_PEERS: '0', CLAUDE_PRO_ONLINE: '0' });
16
16
 
17
17
  let App;
18
18
  try {
package/src/session.js CHANGED
@@ -8,9 +8,79 @@ import crypto from 'node:crypto';
8
8
  import { CONFIG_DIR } from './config.js';
9
9
  import { PROMPT_CODE_VERSION } from './prompts.js';
10
10
 
11
+ // The directory of a project's state (conversations, memory, checkpoints, traces): its path with every character
12
+ // but a-z, A-Z and 0-9 made '-', as Claude Code names it. A path with characters beyond ASCII in it also gets a hash
13
+ // of the whole path: those all became '-', so that D:\d\node\聊天 and D:\d\node\共享 were one directory, their
14
+ // conversations and memory shared. The directory such a project had before is taken over the first time (adoptOldDir).
11
15
  export function projectDir(cwd) {
12
- const name = path.resolve(cwd).replace(/[^a-zA-Z0-9]/g, '-');
13
- return path.join(CONFIG_DIR, 'projects', name);
16
+ const abs = path.resolve(cwd);
17
+ const name = abs.replace(/[^a-zA-Z0-9]/g, '-');
18
+ const base = path.join(CONFIG_DIR, 'projects');
19
+ if (!/[^\x00-\x7f]/.test(abs)) return path.join(base, name);
20
+ return adoptOldDir(abs, path.join(base, name), path.join(base, `${name}-${pathHash(abs)}`));
21
+ }
22
+
23
+ // A path as the file system tells paths apart: in any case on Windows, and in one Unicode form (macOS gives NFD).
24
+ function pathKey(p) {
25
+ const key = path.resolve(p).normalize('NFC');
26
+ return process.platform === 'win32' ? key.toLowerCase() : key;
27
+ }
28
+
29
+ function pathHash(abs) {
30
+ return crypto.createHash('sha256').update(pathKey(abs)).digest('hex').slice(0, 8);
31
+ }
32
+
33
+ const adopted = new Map(); // a project's new directory -> the directory this process uses for it
34
+
35
+ // The directory to use for `abs` (see projectDir): `dir`, after what was this project's in `oldDir` (the name from
36
+ // before the hash) has moved there. Its conversations say which directory they ran in (their first line). When they
37
+ // are all this project's, so is the rest: the directory is renamed. Else it was shared: this project's conversations
38
+ // (with their traces) move, its memory is copied (it cannot be told apart), and the rest stays for the other
39
+ // project, which takes the directory over in its turn. With no conversation to tell, the memory is copied and the
40
+ // directory left. Once per process; when the rename is refused (a file in it held open on Windows), the old
41
+ // directory is used as it is, and moved another time.
42
+ function adoptOldDir(abs, oldDir, dir) {
43
+ if (adopted.has(dir)) return adopted.get(dir);
44
+ let use = dir;
45
+ try {
46
+ if (!fs.existsSync(dir) && fs.existsSync(oldDir)) {
47
+ const key = pathKey(abs);
48
+ const sessions = fs.readdirSync(oldDir).filter((f) => f.endsWith('.jsonl')).map((f) => ({ f, cwd: sessionCwd(path.join(oldDir, f)) }));
49
+ const mine = sessions.filter((s) => s.cwd && pathKey(s.cwd) === key);
50
+ const others = sessions.filter((s) => s.cwd && pathKey(s.cwd) !== key);
51
+ if (mine.length && !others.length) {
52
+ try { fs.renameSync(oldDir, dir); } catch { use = fs.existsSync(dir) ? dir : oldDir; } // moved by another process first, or held open
53
+ } else {
54
+ fs.mkdirSync(dir, { recursive: true });
55
+ const memory = path.join(oldDir, 'memory');
56
+ if ((mine.length || !others.length) && fs.existsSync(memory)) fs.cpSync(memory, path.join(dir, 'memory'), { recursive: true });
57
+ for (const { f } of mine) {
58
+ const id = f.slice(0, -'.jsonl'.length);
59
+ const moves = [[f, f], [path.join('traces', `${id}.jsonl`), path.join('traces', `${id}.jsonl`)], [path.join('traces', `${id}.jsonl.1`), path.join('traces', `${id}.jsonl.1`)]];
60
+ for (const [from, to] of moves) {
61
+ if (!fs.existsSync(path.join(oldDir, from))) continue;
62
+ fs.mkdirSync(path.dirname(path.join(dir, to)), { recursive: true });
63
+ try { fs.renameSync(path.join(oldDir, from), path.join(dir, to)); } catch { /* left where it was */ }
64
+ }
65
+ }
66
+ }
67
+ }
68
+ } catch { /* the new directory, as it is */ }
69
+ adopted.set(dir, use);
70
+ return use;
71
+ }
72
+
73
+ // The directory a conversation file ran in, from its first line (a meta line with cwd), or null.
74
+ function sessionCwd(file) {
75
+ let fd;
76
+ try {
77
+ fd = fs.openSync(file, 'r');
78
+ const buf = Buffer.alloc(64 * 1024);
79
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
80
+ const first = buf.subarray(0, n).toString('utf8').split('\n')[0];
81
+ const meta = JSON.parse(first);
82
+ return meta?.type === 'meta' && typeof meta.cwd === 'string' ? meta.cwd : null;
83
+ } catch { return null; } finally { if (fd !== undefined) try { fs.closeSync(fd); } catch { /* ignore */ } }
14
84
  }
15
85
 
16
86
  // Where oversized tool output is saved (see persistLargeOutput in agent.js).
@@ -30,6 +100,19 @@ export function pruneToolResults(cwd, maxAgeMs = 7 * 24 * 3600_000) {
30
100
  }
31
101
  }
32
102
 
103
+ // Delete the traces (see trace.js) of conversations not traced for maxAgeMs: one file a conversation, up to 40 MB
104
+ // with its rotation, kept for good before (best effort, run at startup).
105
+ export function pruneTraces(cwd, maxAgeMs = 30 * 24 * 3600_000) {
106
+ const dir = path.join(projectDir(cwd), 'traces');
107
+ let entries = [];
108
+ try { entries = fs.readdirSync(dir); } catch { return; }
109
+ const cutoff = Date.now() - maxAgeMs;
110
+ for (const name of entries) {
111
+ const file = path.join(dir, name);
112
+ try { if (fs.statSync(file).mtimeMs < cutoff) fs.rmSync(file, { force: true }); } catch { /* ignore */ }
113
+ }
114
+ }
115
+
33
116
  // Where /rewind keeps file snapshots: one sub-directory per run of the program.
34
117
  export function checkpointsDir(cwd) {
35
118
  return path.join(projectDir(cwd), 'checkpoints');
@@ -77,6 +160,8 @@ export function moveSession(file, id, cwd) {
77
160
  }
78
161
 
79
162
  export class SessionStore {
163
+ static onError = null; // (error, store): a write of the conversation failed (the first time for a store)
164
+
80
165
  constructor(cwd, id = crypto.randomUUID()) {
81
166
  this.cwd = cwd;
82
167
  this.id = id;
@@ -93,7 +178,12 @@ export class SessionStore {
93
178
  if (!fs.existsSync(this.file)) fs.appendFileSync(this.file, JSON.stringify({ type: 'meta', cwd: this.cwd, created: new Date().toISOString() }) + '\n');
94
179
  }
95
180
  fs.appendFileSync(this.file, JSON.stringify(entry) + '\n');
96
- } catch { /* persistence is best effort */ }
181
+ } catch (e) {
182
+ // Best effort, but a message that did not get in leaves the file without it, and a restart or /resume would go
183
+ // on from a conversation that lacks it: noted (`lost`, see App.restartNow), and said once (SessionStore.onError).
184
+ this.lost = true;
185
+ if (!this.warned) { this.warned = true; try { SessionStore.onError?.(e, this); } catch { /* ignore */ } }
186
+ }
97
187
  }
98
188
 
99
189
  message(message) { this.append({ type: 'message', message, at: Date.now() }); }
package/src/supervisor.js CHANGED
@@ -68,7 +68,16 @@ export function supervise(argv, { entry, env = process.env, execPath = process.e
68
68
  const handlers = {
69
69
  SIGINT: () => { /* the terminal sends it to the child too, which decides what it means */ },
70
70
  SIGTERM: () => stop('SIGTERM'),
71
- SIGHUP: () => stop('SIGHUP'),
71
+ // The terminal closed. The child hears it too (the console's close event on Windows, the hangup of its process
72
+ // group elsewhere) and ends cleanly: background shells, MCP servers, its entry at the gateway. On Windows
73
+ // kill() is TerminateProcess whatever the signal, which cut that short and left the shells' processes running:
74
+ // there the child is only killed if it is still running a while later (Windows ends everything about 10 s
75
+ // after the close anyway). Elsewhere the signal is passed on, a real one.
76
+ SIGHUP: () => {
77
+ stopping = true;
78
+ if (process.platform !== 'win32') stop('SIGHUP');
79
+ setTimeout(() => stop('SIGKILL'), 5000).unref();
80
+ },
72
81
  };
73
82
  for (const [signal, fn] of Object.entries(handlers)) { try { process.on(signal, fn); } catch { /* not on this platform */ } }
74
83