@yanzc/claude-pro 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +342 -318
- package/package.json +1 -2
- package/src/agent.js +80 -14
- package/src/agents.js +3 -2
- package/src/api.js +39 -34
- package/src/browser/broker.js +367 -0
- package/src/browser/cdp.js +114 -0
- package/src/browser/render.js +242 -0
- package/src/browser/session.js +948 -0
- package/src/browser/snapshot.js +212 -0
- package/src/cache.js +1 -1
- package/src/checkpoints.js +1 -0
- package/src/commands.js +169 -67
- package/src/compaction.js +75 -0
- package/src/config.js +145 -144
- package/src/context.js +45 -18
- package/src/filestate.js +3 -2
- package/src/gateway.js +208 -164
- package/src/hooks.js +2 -2
- package/src/keepalive.js +1 -1
- package/src/main.js +52 -40
- package/src/mcp.js +2 -2
- package/src/peers.js +1 -10
- package/src/print.js +9 -3
- package/src/prompt-profiles.js +0 -6
- package/src/prompts.js +7 -63
- package/src/ratelimit.js +2 -4
- package/src/remote.js +76 -14
- package/src/runtime.js +33 -10
- package/src/selfcheck.js +3 -3
- package/src/session.js +93 -3
- package/src/supervisor.js +10 -1
- package/src/tools/bash.js +18 -17
- package/src/tools/browser.js +365 -0
- package/src/tools/code.js +430 -0
- package/src/tools/effort.js +3 -4
- package/src/tools/files.js +368 -45
- package/src/tools/index.js +9 -1
- package/src/tools/notebook.js +11 -4
- package/src/tools/processes.js +274 -0
- package/src/tools/search.js +33 -8
- package/src/tools/web.js +316 -46
- package/src/trace.js +0 -4
- package/src/ui/ansi.js +92 -13
- package/src/ui/dialogs.js +16 -54
- package/src/ui/editor.js +231 -34
- package/src/ui/markdown.js +1 -2
- package/src/ui/render.js +1 -2
- package/src/ui/repl.js +335 -101
- package/src/ui/screen.js +139 -31
- package/src/updater.js +135 -165
- package/src/utils/clipboard.js +5 -3
- package/src/utils/dirs.js +136 -0
- package/src/utils/encoding.js +23 -2
- package/src/utils/paths.js +15 -17
- package/src/utils/shell.js +66 -11
- package/.env.example +0 -29
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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/prompt-profiles.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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,19 +69,20 @@ 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
|
|
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.
|
|
78
77
|
- Before deleting or overwriting something, look at what is there: it may be the user's work in progress.
|
|
79
78
|
- Follow security best practices: never expose, log or commit secrets, and never write code that does.
|
|
80
79
|
- Do not commit unless the user asks or the project's instructions say when to.
|
|
81
|
-
- Edits made with Write, Edit and NotebookEdit are checkpointed per user prompt and can be undone with /rewind; changes made through Bash are not.
|
|
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
83
|
- Call independent tools together in one response so that they run in parallel; run dependent ones one after another.
|
|
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
|
|
|
@@ -114,7 +114,7 @@ ${readOnly ? '' : `
|
|
|
114
114
|
- 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.
|
|
115
115
|
- Never expose, log or commit secrets, and never write code that does.
|
|
116
116
|
- Do not commit, push or publish unless your task asks for it: the main agent decides that.
|
|
117
|
-
- Edits made with Write, Edit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
|
|
117
|
+
- Edits made with Write, Edit, MultiEdit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
|
|
118
118
|
`}
|
|
119
119
|
${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}` : ''}${mcpInstructions ? `\n\n${mcpInstructions}` : ''}`;
|
|
120
120
|
}
|
|
@@ -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
|
|
165
|
-
//
|
|
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;
|
package/src/remote.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
// Publish a local interactive session to the gateway so the account's browser can watch it
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// Publish a local interactive session to the gateway, so that the account's browser can watch it and steer it: send
|
|
2
|
+
// it messages (as if typed in its input box: /commands, !shell, #memory, pasted images), answer its questions, stop
|
|
3
|
+
// it, switch model and effort, complete input, browse directories for /cd and read a tool call's whole output. The
|
|
4
|
+
// session never listens on the network: it connects out to the codex-gateway with the gateway API key from /login,
|
|
5
|
+
// declares the commands it takes when it registers, and gets them on its command stream. With
|
|
6
|
+
// CLAUDE_PRO_REMOTE_COMMANDS=0 it declares none and is read-only on the page.
|
|
4
7
|
// The same connection carries the messages of the account's sessions on other computers (`@公司 ...`, see peers.js).
|
|
5
8
|
//
|
|
6
9
|
// The page is told what happens as a list of transcript items (user messages, assistant text, thinking, tool
|
|
@@ -11,6 +14,7 @@ import os from 'node:os';
|
|
|
11
14
|
import crypto from 'node:crypto';
|
|
12
15
|
import { stripAnsi } from './ui/ansi.js';
|
|
13
16
|
import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
|
|
17
|
+
import { shownQuotes } from './ui/editor.js';
|
|
14
18
|
|
|
15
19
|
export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
|
|
16
20
|
const MAX_ITEMS = 800; // kept for a snapshot; the oldest are dropped beyond that
|
|
@@ -95,9 +99,10 @@ export function hydrate(items) {
|
|
|
95
99
|
return state;
|
|
96
100
|
}
|
|
97
101
|
|
|
98
|
-
// 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).
|
|
99
104
|
function shownUserText(text) {
|
|
100
|
-
return
|
|
105
|
+
return shownQuotes(text)
|
|
101
106
|
.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')
|
|
102
107
|
.replace(/<peer-message from="([^"]*)" kind="(task|reply)">\n?/g, (_, from, kind) => `✉ ${kind === 'reply' ? 'answer from' : 'task from'} @${from}: `)
|
|
103
108
|
.replace(/\n?<\/peer-message>/g, '')
|
|
@@ -188,16 +193,25 @@ export const newRemoteId = () => crypto.randomBytes(9).toString('base64url');
|
|
|
188
193
|
// which only the self-check and the tests set).
|
|
189
194
|
export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(env.CLAUDE_PRO_ONLINE || '');
|
|
190
195
|
|
|
196
|
+
// Whether the page may steer the session, not only watch it (CLAUDE_PRO_REMOTE_COMMANDS=0: read-only).
|
|
197
|
+
export const remoteCommandsEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(String(env.CLAUDE_PRO_REMOTE_COMMANDS ?? '').trim());
|
|
198
|
+
|
|
199
|
+
// The commands of the page, and the handler of each (see App.connectRemote; each gets the command's body and
|
|
200
|
+
// returns the result's fields, or a promise of them, or throws what to tell the page). A session declares the ones
|
|
201
|
+
// it has handlers for when it registers (`commands`); the gateway forwards only those and answers the others itself.
|
|
202
|
+
// A session that declares none (0.8.x, CLAUDE_PRO_REMOTE_COMMANDS=0) is read-only on the page.
|
|
203
|
+
const COMMANDS = { send: 'send', interrupt: 'interrupt', dialog: 'answer', options: 'options', suggest: 'suggest', list: 'list', output: 'output' };
|
|
204
|
+
|
|
191
205
|
export class RemoteControl {
|
|
192
206
|
// gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model}, seed() -> items, status() -> object,
|
|
193
|
-
// peerMessage(message), changed() (online or viewers changed), refused(status) (the key was refused: closed)
|
|
207
|
+
// peerMessage(message), changed() (online or viewers changed), refused(status) (the key was refused: closed), and
|
|
208
|
+
// the page's commands: send, interrupt, answer (dialog), options, suggest, list, output (see COMMANDS).
|
|
194
209
|
constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
|
|
195
210
|
this.base = String(gateway.url).replace(/\/+$/, '');
|
|
196
211
|
this.apiKey = gateway.apiKey;
|
|
197
212
|
this.id = /^[\w-]{8,64}$/.test(id || '') ? id : newRemoteId();
|
|
198
213
|
this.handlers = handlers;
|
|
199
214
|
this.fetch = fetchImpl;
|
|
200
|
-
this.url = null; // the session's page on the gateway
|
|
201
215
|
this.online = false; // the command stream is open
|
|
202
216
|
this.viewers = null; // pages watching, as the gateway counts them (null: not told yet)
|
|
203
217
|
this.closed = false;
|
|
@@ -216,8 +230,12 @@ export class RemoteControl {
|
|
|
216
230
|
this.registered = false;
|
|
217
231
|
this.refused = null; // the status (401/403) of the gateway refusing the key after the start: the connection ended
|
|
218
232
|
this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
|
|
233
|
+
this.replying = new Set(); // answers to the page's commands on their way (close() waits for them)
|
|
219
234
|
}
|
|
220
235
|
|
|
236
|
+
// The commands this session takes, as declared to the gateway.
|
|
237
|
+
get commands() { return Object.keys(COMMANDS).filter((type) => typeof this.handlers[COMMANDS[type]] === 'function'); }
|
|
238
|
+
|
|
221
239
|
get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
|
|
222
240
|
|
|
223
241
|
// `persistent`: keep trying when the gateway cannot be reached now (a restart); otherwise the first failure is thrown.
|
|
@@ -257,9 +275,9 @@ export class RemoteControl {
|
|
|
257
275
|
|
|
258
276
|
async register() {
|
|
259
277
|
const info = this.handlers.info?.() || {};
|
|
260
|
-
const
|
|
278
|
+
const commands = this.commands;
|
|
279
|
+
const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...info, ...(commands.length ? { commands } : {}) });
|
|
261
280
|
if (data.id) this.id = data.id;
|
|
262
|
-
this.url = data.url || this.url || `${this.base}/user`;
|
|
263
281
|
this.registered = true;
|
|
264
282
|
this.needSnapshot = true;
|
|
265
283
|
}
|
|
@@ -270,7 +288,15 @@ export class RemoteControl {
|
|
|
270
288
|
while (!this.closed) {
|
|
271
289
|
const began = Date.now();
|
|
272
290
|
try {
|
|
273
|
-
if (!this.registered)
|
|
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
|
+
}
|
|
274
300
|
await this.listen();
|
|
275
301
|
} catch (e) {
|
|
276
302
|
if (e.status === 404) this.registered = false; // the gateway forgot the session (restarted): register again
|
|
@@ -307,6 +333,7 @@ export class RemoteControl {
|
|
|
307
333
|
}
|
|
308
334
|
|
|
309
335
|
async listen() {
|
|
336
|
+
if (this.closed) return;
|
|
310
337
|
const abort = new AbortController();
|
|
311
338
|
this.streamAbort = abort;
|
|
312
339
|
const res = await this.fetch(`${this.base}/v1/remote/sessions/${encodeURIComponent(this.id)}/commands`, {
|
|
@@ -349,6 +376,7 @@ export class RemoteControl {
|
|
|
349
376
|
}
|
|
350
377
|
|
|
351
378
|
command(cmd) {
|
|
379
|
+
if (this.closed) return; // the page of a session that has gone offline steers nothing
|
|
352
380
|
if (cmd.type === 'viewers') {
|
|
353
381
|
const was = this.viewers;
|
|
354
382
|
this.viewers = Math.max(0, Number(cmd.count) || 0);
|
|
@@ -360,8 +388,32 @@ export class RemoteControl {
|
|
|
360
388
|
if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
|
|
361
389
|
if (!cmd.cid) return;
|
|
362
390
|
if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
|
|
363
|
-
//
|
|
364
|
-
//
|
|
391
|
+
// A command of the page, answered with POST …/results {cid, ok: true, …fields} or {cid, ok: false, error} (the
|
|
392
|
+
// gateway waits 15 s for it, and takes it until 3 s after the stream closed). close() waits for the answers on
|
|
393
|
+
// their way: a /cd from the page restarts the session from inside its command.
|
|
394
|
+
const reply = (result) => {
|
|
395
|
+
const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
|
|
396
|
+
this.replying.add(sent);
|
|
397
|
+
sent.finally(() => this.replying.delete(sent));
|
|
398
|
+
this.scheduleFlush(30); // what the command changed, on the page soon
|
|
399
|
+
};
|
|
400
|
+
const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
|
|
401
|
+
const handler = Object.hasOwn(COMMANDS, cmd.type) ? this.handlers[COMMANDS[cmd.type]] : null;
|
|
402
|
+
if (typeof handler !== 'function') {
|
|
403
|
+
// an older gateway forwards every command, declared or not
|
|
404
|
+
failed(new Error(this.commands.length ? `Unknown command: ${cmd.type}` : 'This session is read-only on the web page (CLAUDE_PRO_REMOTE_COMMANDS=0 on its computer).'));
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
let r;
|
|
408
|
+
try {
|
|
409
|
+
r = handler(cmd.body && typeof cmd.body === 'object' && !Array.isArray(cmd.body) ? cmd.body : {});
|
|
410
|
+
} catch (e) {
|
|
411
|
+
failed(e);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
// an answer that takes a while (the gateway's list of models, a directory) is sent when it is there
|
|
415
|
+
if (typeof r?.then === 'function') r.then((v) => reply({ ...(v || {}), cid: cmd.cid, ok: true }), failed);
|
|
416
|
+
else reply({ ...(r || {}), cid: cmd.cid, ok: true });
|
|
365
417
|
}
|
|
366
418
|
|
|
367
419
|
// ------------------------------------------------------------ messages of the account's other sessions
|
|
@@ -407,8 +459,14 @@ export class RemoteControl {
|
|
|
407
459
|
ev.seq = ++this.seq;
|
|
408
460
|
applyEvent(this.state, ev);
|
|
409
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
|
|
410
463
|
if (this.viewing && !this.needSnapshot) {
|
|
411
|
-
|
|
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);
|
|
412
470
|
this.scheduleFlush();
|
|
413
471
|
}
|
|
414
472
|
}
|
|
@@ -526,8 +584,12 @@ export class RemoteControl {
|
|
|
526
584
|
}
|
|
527
585
|
|
|
528
586
|
async shutdown(restarting) {
|
|
529
|
-
//
|
|
587
|
+
// First the answers on their way, while the command stream is still open (the gateway takes them until 3 s
|
|
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.
|
|
530
591
|
await null;
|
|
592
|
+
if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
|
|
531
593
|
this.closing = true; // what flush() collects now goes out with the last message, not on its own
|
|
532
594
|
this.flush();
|
|
533
595
|
this.closed = true;
|
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
|
|
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,
|
|
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
|
|
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
|
-
|
|
170
|
-
|
|
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,
|
|
14
|
-
//
|
|
15
|
-
Object.assign(process.env, { CLAUDE_PRO_PEERS: '0', CLAUDE_PRO_ONLINE: '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
|
|
13
|
-
|
|
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 {
|
|
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
|
-
|
|
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
|
|