@yanzc/claude-pro 0.7.2 → 0.7.4
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/.env.example +24 -34
- package/README.md +317 -331
- package/package.json +2 -2
- package/src/agent.js +41 -4
- package/src/api.js +40 -173
- package/src/commands.js +19 -84
- package/src/config.js +32 -137
- package/src/gateway.js +9 -3
- package/src/host.js +8 -5
- package/src/main.js +19 -2
- package/src/mcp.js +14 -0
- package/src/peers.js +3 -6
- package/src/print.js +1 -1
- package/src/prompts.js +23 -14
- package/src/ratelimit.js +6 -19
- package/src/remote.js +6 -40
- package/src/runtime.js +7 -4
- package/src/tools/peers.js +5 -9
- package/src/ui/repl.js +24 -204
- package/src/work-state.js +62 -0
- package/src/claude-code.js +0 -60
- package/src/codex/client.js +0 -310
- package/src/codex/translate-request.js +0 -239
- package/src/codex/translate-stream.js +0 -328
- package/src/oauth.js +0 -287
- package/src/transfer.js +0 -260
- package/src/utils/downloads.js +0 -83
package/src/main.js
CHANGED
|
@@ -1,24 +1,26 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import { VERSION, KNOWN_KEYS, loadConfig, settingsFiles, updateSettingsFile, applyRememberedChoices } from './config.js';
|
|
3
|
+
import { resolvePath } from './utils/paths.js';
|
|
3
4
|
import { SessionStore } from './session.js';
|
|
4
5
|
import { takeRestartState } from './restart.js';
|
|
5
6
|
|
|
6
7
|
const HELP = `Usage: claude-pro [options] [prompt]
|
|
7
8
|
|
|
8
|
-
A command line coding agent
|
|
9
|
+
A command line coding agent using the codex-gateway.
|
|
9
10
|
Starts an interactive session by default; use -p for non-interactive output.
|
|
10
11
|
|
|
11
12
|
Options:
|
|
12
13
|
-p, --print Print the response and exit (useful for pipes)
|
|
13
14
|
-c, --continue Continue the most recent conversation in this directory
|
|
14
15
|
-r, --resume [sessionId] Resume a conversation (picker if no id given)
|
|
15
|
-
--provider <backend>
|
|
16
|
+
--provider <backend> gateway only (the codex-gateway account)
|
|
16
17
|
--model <model> Model for this session (name or alias: opus, sonnet, haiku)
|
|
17
18
|
--effort <level> Reasoning effort: none|minimal|low|medium|high|xhigh|max
|
|
18
19
|
--output-format <format> text | json | stream-json (with --print)
|
|
19
20
|
--verify <command> After the agent edits files, run this (e.g. "npm test") and send failures back to fix
|
|
20
21
|
--append-system-prompt <text> Append text to the system prompt
|
|
21
22
|
--system-prompt <text> Replace the system prompt
|
|
23
|
+
--system-prompt-file <file> Replace the system prompt with the contents of a file
|
|
22
24
|
--verbose Show thinking and full tool output
|
|
23
25
|
--no-mcp Do not start MCP servers
|
|
24
26
|
--name <name> Name this session, as /rename does (other sessions reach it with &name)
|
|
@@ -78,6 +80,7 @@ function parseArgs(argv) {
|
|
|
78
80
|
case '--verify': flags.verify = next(); break;
|
|
79
81
|
case '--append-system-prompt': flags.appendSystemPrompt = next(); break;
|
|
80
82
|
case '--system-prompt': flags.systemPrompt = next(); break;
|
|
83
|
+
case '--system-prompt-file': flags.systemPromptFile = next(); break;
|
|
81
84
|
case '--verbose': flags.verbose = true; break;
|
|
82
85
|
case '--no-mcp': flags.noMcp = true; break;
|
|
83
86
|
case '--remote-control': case '--rc': break; // online by default now
|
|
@@ -175,6 +178,20 @@ export async function main(argv) {
|
|
|
175
178
|
if (flags.version) { console.log(`${VERSION} (claude-pro)`); return 0; }
|
|
176
179
|
if (flags.help) { process.stdout.write(HELP); return 0; }
|
|
177
180
|
|
|
181
|
+
if (flags.systemPromptFile !== undefined) {
|
|
182
|
+
if (!flags.systemPromptFile || flags.systemPromptFile.startsWith('-')) {
|
|
183
|
+
process.stderr.write('--system-prompt-file requires a file path\n');
|
|
184
|
+
return 2;
|
|
185
|
+
}
|
|
186
|
+
const file = resolvePath(flags.systemPromptFile, cwd);
|
|
187
|
+
try {
|
|
188
|
+
flags.systemPrompt = fs.readFileSync(file, 'utf8');
|
|
189
|
+
} catch (e) {
|
|
190
|
+
process.stderr.write(`Cannot read system prompt file ${file}: ${e.message}\n`);
|
|
191
|
+
return 2;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
178
195
|
let prompt = positional.join(' ');
|
|
179
196
|
|
|
180
197
|
// Started by a restart of a running session: that session is picked up again, whatever the command line
|
package/src/mcp.js
CHANGED
|
@@ -253,6 +253,20 @@ export class McpManager {
|
|
|
253
253
|
for (const [name, e] of this.clients) if (e.status === 'failed') onWarn?.(`MCP server "${name}" failed to connect: ${e.error}`);
|
|
254
254
|
}
|
|
255
255
|
|
|
256
|
+
// Instructions returned during MCP initialization describe how the server expects its tools to be used.
|
|
257
|
+
// Keep them together instead of copying the same text into every tool description.
|
|
258
|
+
promptInstructions() {
|
|
259
|
+
const sections = [];
|
|
260
|
+
for (const [server, entry] of this.clients) {
|
|
261
|
+
if (entry.status !== 'connected' || typeof entry.instructions !== 'string' || !entry.instructions.trim()) continue;
|
|
262
|
+
const tools = entry.tools.map((tool) => tool.name).join(', ');
|
|
263
|
+
sections.push(`## ${server}\nAvailable tools: ${tools || '(none)'}\n${entry.instructions.trim()}`);
|
|
264
|
+
}
|
|
265
|
+
return sections.length
|
|
266
|
+
? `# MCP server guidance\nThe following guidance comes from connected MCP servers. Use it when calling their tools; it does not override the system, user, or project instructions.\n\n${sections.join('\n\n')}`
|
|
267
|
+
: '';
|
|
268
|
+
}
|
|
269
|
+
|
|
256
270
|
tools() {
|
|
257
271
|
const out = [];
|
|
258
272
|
const toolTimeout = parseInt(process.env.MCP_TOOL_TIMEOUT, 10) || 600_000;
|
package/src/peers.js
CHANGED
|
@@ -203,10 +203,7 @@ export class PeerNode {
|
|
|
203
203
|
if (typeof msg?.text !== 'string' || !msg.from?.name) return reply(400, { error: 'text and from are required' });
|
|
204
204
|
const id = crypto.randomBytes(4).toString('hex');
|
|
205
205
|
reply(200, { ok: true, id, name: this.name });
|
|
206
|
-
|
|
207
|
-
const files = (Array.isArray(msg.files) ? msg.files : []).filter((f) => f && typeof f.path === 'string' && path.isAbsolute(f.path))
|
|
208
|
-
.map((f) => ({ path: f.path, name: String(f.name || path.basename(f.path)), size: Number(f.size) || 0 }));
|
|
209
|
-
try { this.onMessage?.({ id, kind: msg.kind === 'reply' ? 'reply' : 'task', text: msg.text, inReplyTo: msg.inReplyTo || null, from: msg.from, ...(files.length ? { files } : {}) }); } catch { /* the receiver's problem */ }
|
|
206
|
+
try { this.onMessage?.({ id, kind: msg.kind === 'reply' ? 'reply' : 'task', text: msg.text, inReplyTo: msg.inReplyTo || null, from: msg.from }); } catch { /* the receiver's problem */ }
|
|
210
207
|
});
|
|
211
208
|
}
|
|
212
209
|
|
|
@@ -228,10 +225,10 @@ export class PeerNode {
|
|
|
228
225
|
}
|
|
229
226
|
|
|
230
227
|
// Send to a peer (an entry of peers(), or its name). Resolves with {id} (the id the receiver gave the message).
|
|
231
|
-
async send(target, { text, kind = 'task', inReplyTo = null
|
|
228
|
+
async send(target, { text, kind = 'task', inReplyTo = null }) {
|
|
232
229
|
const peer = typeof target === 'string' ? findPeer(this.peers(), target) : target;
|
|
233
230
|
if (!peer) throw new Error(`No running session called "${target}". /peers lists them.`);
|
|
234
|
-
const body = JSON.stringify({ kind, text, inReplyTo, from: { id: this.id, name: this.name, cwd: this.cwd }
|
|
231
|
+
const body = JSON.stringify({ kind, text, inReplyTo, from: { id: this.id, name: this.name, cwd: this.cwd } });
|
|
235
232
|
return await new Promise((resolve, reject) => {
|
|
236
233
|
const req = http.request({
|
|
237
234
|
host: '127.0.0.1', port: peer.port, path: '/message', method: 'POST', timeout: 10_000,
|
package/src/print.js
CHANGED
|
@@ -17,7 +17,7 @@ export async function runPrint({ prompt, flags, cwd, stdout = process.stdout, st
|
|
|
17
17
|
return (ev) => {
|
|
18
18
|
if (ev.type === 'rate_limit_wait') {
|
|
19
19
|
if (shouldAnnounce(paused, ev)) err(c.yellow(who + describePause(ev)));
|
|
20
|
-
paused = { resumeAt: ev.resumeAt
|
|
20
|
+
paused = { resumeAt: ev.resumeAt };
|
|
21
21
|
}
|
|
22
22
|
if (ev.type === 'rate_limit_resume') {
|
|
23
23
|
paused = null;
|
package/src/prompts.js
CHANGED
|
@@ -44,7 +44,7 @@ function instructionFiles(cwd) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
// `autoCompact`: the conversation is summarized when it grows long (Config.autoCompactEnabled), which the model is told.
|
|
47
|
-
export function mainSystemPrompt({ cwd, model, shellName, extra = '', autoMemory = null, selfRestart = false, installedCopy = false, autoCompact = true, snapshot = null }) {
|
|
47
|
+
export function mainSystemPrompt({ cwd, model, shellName, extra = '', autoMemory = null, mcpInstructions = '', selfRestart = false, installedCopy = false, autoCompact = true, snapshot = null }) {
|
|
48
48
|
const files = instructionFiles(cwd);
|
|
49
49
|
const memoryText = files
|
|
50
50
|
? `\n\n# Memory\nProject and user instructions are shown below: the facts of this project (its environment, mechanisms, commands) and how the user wants to work in it. Where they differ from the defaults above, they win.\n\n${files}`
|
|
@@ -96,12 +96,12 @@ You are ${APP_NAME}, installed in ${INSTALL_DIR} (an installed copy, e.g. from n
|
|
|
96
96
|
` : ''}# Code references
|
|
97
97
|
When referencing specific functions or pieces of code include the pattern \`file_path:line_number\` so the user can navigate to the source.
|
|
98
98
|
|
|
99
|
-
${environmentBlock(cwd, { model, shellName, snapshot })}${memoryText}${autoMemory ? `\n\n${autoMemorySection(autoMemory)}` : ''}${extra ? `\n\n${extra}` : ''}`;
|
|
99
|
+
${environmentBlock(cwd, { model, shellName, snapshot })}${memoryText}${autoMemory ? `\n\n${autoMemorySection(autoMemory)}` : ''}${mcpInstructions ? `\n\n${mcpInstructions}` : ''}${extra ? `\n\n${extra}` : ''}`;
|
|
100
100
|
}
|
|
101
101
|
|
|
102
102
|
// `readOnly`: an agent whose own prompt forbids changing anything (Explore, Plan) gets neither the boundaries nor
|
|
103
103
|
// the project's instructions, which only matter to an agent that changes things and cost tokens on every call.
|
|
104
|
-
export function subagentSystemPrompt({ cwd, model, shellName, agentPrompt, snapshot = null, readOnly = false }) {
|
|
104
|
+
export function subagentSystemPrompt({ cwd, model, shellName, agentPrompt, snapshot = null, mcpInstructions = '', readOnly = false }) {
|
|
105
105
|
const files = readOnly ? '' : instructionFiles(cwd);
|
|
106
106
|
return `${agentPrompt}
|
|
107
107
|
|
|
@@ -116,7 +116,7 @@ ${readOnly ? '' : `
|
|
|
116
116
|
- Do not commit, push or publish unless your task asks for it: the main agent decides that.
|
|
117
117
|
- Edits made with Write, Edit and NotebookEdit can be undone with /rewind; changes made through Bash cannot.
|
|
118
118
|
`}
|
|
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}` : ''}`;
|
|
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
|
}
|
|
121
121
|
|
|
122
122
|
// The terminal tab's title follows the topic of the conversation: after each message the user sends, the
|
|
@@ -138,19 +138,25 @@ ${current ? 'Does this message start a new topic (a different task or question),
|
|
|
138
138
|
export const SUMMARY_SYSTEM = 'You are a helpful AI assistant tasked with summarizing conversations.';
|
|
139
139
|
|
|
140
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 summary below.
|
|
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
142
|
|
|
143
|
-
Your task is to create a detailed summary of the conversation
|
|
144
|
-
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
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.
|
|
145
144
|
|
|
146
|
-
|
|
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>.
|
|
147
150
|
|
|
151
|
+
Then wrap your analysis in <analysis> tags to organize your thoughts, and write a detailed narrative in <summary> tags. 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:
|
|
148
154
|
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
149
155
|
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
150
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.
|
|
151
157
|
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback.
|
|
152
158
|
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
153
|
-
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the
|
|
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.
|
|
154
160
|
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
155
161
|
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, including file names and code snippets.
|
|
156
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.
|
|
@@ -170,14 +176,17 @@ export function partialCompactPrompt(part, label, instructions = '') {
|
|
|
170
176
|
}
|
|
171
177
|
|
|
172
178
|
// The message that stands in the conversation for the part a partial summary replaced.
|
|
173
|
-
export function partialSummaryMessage(part, summary) {
|
|
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>` : '';
|
|
174
181
|
return part === 'before'
|
|
175
|
-
? `[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
|
|
176
|
-
: `[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
|
|
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}`;
|
|
177
184
|
}
|
|
178
185
|
|
|
179
|
-
export function continuationMessage(summary, { auto }) {
|
|
180
|
-
|
|
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}
|
|
181
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.' : ''}`;
|
|
182
191
|
}
|
|
183
192
|
|
package/src/ratelimit.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
// Rate limits: reading when a limit resets from the response headers, deciding how long to wait
|
|
2
2
|
// before retrying, and the wording shown to the user.
|
|
3
3
|
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
// few quick retries used for transient errors.
|
|
4
|
+
// Gateway requests can be limited by rolling windows, 5 hours and 7 days. When one is used up the
|
|
5
|
+
// gateway answers 429, and the anthropic-ratelimit-unified-* headers say which window it was and when it
|
|
6
|
+
// resets (epoch seconds). Waiting for such a reset takes hours, so it is a pause that ends by itself
|
|
7
|
+
// rather than one of the few quick retries used for transient errors.
|
|
9
8
|
|
|
10
9
|
export const LONG_WAIT_MS = 30_000; // waits this long or longer are shown as "rate limit reached, resuming at ..."
|
|
11
10
|
export const MAX_RETRY_AFTER_MS = 5 * 60_000; // when waiting for limits is off, a longer Retry-After is reported instead
|
|
@@ -235,34 +234,22 @@ export function planRetry(err, state, config, { now = Date.now(), rand = Math.ra
|
|
|
235
234
|
|
|
236
235
|
// Words for the pause notice, shared by the interactive and the print mode.
|
|
237
236
|
export function describePause(ev, now = Date.now()) {
|
|
238
|
-
// The limit is over but the subscription login has expired meanwhile (its token lives 8 hours) and could
|
|
239
|
-
// not be renewed by this program: the request goes on as soon as there is a valid login in the file.
|
|
240
|
-
if (ev.waitingForLogin) {
|
|
241
|
-
const until = ev.giveUpAt ? ` Giving up at ${formatClock(ev.giveUpAt, now)}.` : '';
|
|
242
|
-
if (ev.renewError) return `The limit has reset, but the login could not be renewed: ${ev.renewError} Trying again every 5 minutes, and this continues by itself as soon as the login is valid.${until}`;
|
|
243
|
-
return `The limit has reset, but the Claude subscription login has expired and cannot be renewed from here. Waiting for it to be renewed: run claude once, and this continues by itself.${until}`;
|
|
244
|
-
}
|
|
245
237
|
const label = capitalize(ev.label || 'rate limit');
|
|
246
238
|
const left = humanDuration(Math.max(0, ev.resumeAt - now));
|
|
247
239
|
if (ev.overloaded) return `The API is overloaded and kept refusing the request. Trying again at ${formatClock(ev.resumeAt, now)} (in ${left}), and every so often after that, then continuing automatically.`;
|
|
248
240
|
const text = ev.polling
|
|
249
241
|
? `${label} reached and the server gave no reset time. Checking again at ${formatClock(ev.resumeAt, now)} (in ${left}), and every few minutes after that, then continuing automatically.`
|
|
250
242
|
: `${label} reached. Pausing until ${formatClock(ev.resumeAt, now)} (in ${left}), then continuing automatically.`;
|
|
251
|
-
|
|
252
|
-
? ` The Claude subscription login expires at ${formatClock(ev.loginExpiresAt, now)}, before that, and it cannot be renewed from here. If no claude command is running to renew it, run claude once after the reset: this continues by itself once the login is valid again.`
|
|
253
|
-
: '';
|
|
254
|
-
return text + warning;
|
|
243
|
+
return text;
|
|
255
244
|
}
|
|
256
245
|
|
|
257
246
|
// Whether a rate_limit_wait event should be announced to the user. `prev` is the wait that was last
|
|
258
247
|
// announced for the same pause (null at the first one). Polling repeats every few minutes and the
|
|
259
248
|
// announced reset moves a little between waits: those only continue the pause already announced,
|
|
260
|
-
// unless the reset moved by more than two minutes.
|
|
261
|
-
// kind of wait from waiting for the limit, and always worth saying when it begins.
|
|
249
|
+
// unless the reset moved by more than two minutes.
|
|
262
250
|
export const resumeText = (ev) => (ev?.overloaded ? 'The API is answering again; continuing.' : 'The limit has cleared; continuing.');
|
|
263
251
|
|
|
264
252
|
export function shouldAnnounce(prev, ev) {
|
|
265
253
|
if (!prev) return true;
|
|
266
|
-
if (Boolean(prev.waitingForLogin) !== Boolean(ev.waitingForLogin)) return true;
|
|
267
254
|
return !ev.polling && Math.abs(ev.resumeAt - prev.resumeAt) > 120_000;
|
|
268
255
|
}
|
package/src/remote.js
CHANGED
|
@@ -9,12 +9,10 @@
|
|
|
9
9
|
// calls, other terminal output) that events update. The same reducer (applyEvent) runs here, to send a snapshot
|
|
10
10
|
// when one is needed, and in the page, which carries a copy of it.
|
|
11
11
|
|
|
12
|
-
import fs from 'node:fs';
|
|
13
12
|
import os from 'node:os';
|
|
14
13
|
import crypto from 'node:crypto';
|
|
15
14
|
import { stripAnsi } from './ui/ansi.js';
|
|
16
15
|
import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
|
|
17
|
-
import { uploadFile, downloadFile } from './transfer.js';
|
|
18
16
|
|
|
19
17
|
export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
|
|
20
18
|
const MAX_ITEMS = 800; // kept for a snapshot; the oldest are dropped beyond that
|
|
@@ -220,7 +218,6 @@ export class RemoteControl {
|
|
|
220
218
|
this.streamAbort = null;
|
|
221
219
|
this.registered = false;
|
|
222
220
|
this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
|
|
223
|
-
this.peerPending = new Set(); // messages being handled now, acknowledged when done
|
|
224
221
|
this.replying = new Set(); // answers to the page's commands on their way
|
|
225
222
|
}
|
|
226
223
|
|
|
@@ -373,35 +370,22 @@ export class RemoteControl {
|
|
|
373
370
|
// A message from a session on another computer: handed to the App once, then acknowledged, so that the gateway
|
|
374
371
|
// drops it from the session's mailbox (it sends what was not acknowledged again when the stream reconnects).
|
|
375
372
|
peerMessage(cmd) {
|
|
376
|
-
if (this.peerPending.has(cmd.cid)) return; // still being handled (files on their way): acknowledged when done
|
|
377
373
|
const ack = () => this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, { cid: cmd.cid, ok: true }).catch(() => { /* sent again on reconnect, and dropped here as seen */ });
|
|
378
|
-
let handling = null;
|
|
379
374
|
try {
|
|
380
|
-
if (this.seenPeer.has(cmd.cid)) return;
|
|
375
|
+
if (this.seenPeer.has(cmd.cid)) { ack(); return; }
|
|
381
376
|
this.seenPeer.add(cmd.cid);
|
|
382
377
|
if (this.seenPeer.size > 500) this.seenPeer.delete(this.seenPeer.values().next().value);
|
|
383
378
|
const f = cmd.from || {};
|
|
384
379
|
const machine = f.machine || f.host || 'computer';
|
|
385
|
-
|
|
386
|
-
.filter((x) => x && typeof x.id === 'string')
|
|
387
|
-
.map((x) => ({ id: x.id, name: String(x.name || 'file'), size: Number(x.size) || 0, sha256: typeof x.sha256 === 'string' ? x.sha256 : null }));
|
|
388
|
-
handling = this.handlers.peerMessage?.({
|
|
380
|
+
this.handlers.peerMessage?.({
|
|
389
381
|
id: cmd.cid,
|
|
390
382
|
kind: cmd.kind === 'reply' ? 'reply' : 'task',
|
|
391
383
|
text: String(cmd.text ?? ''),
|
|
392
384
|
inReplyTo: cmd.inReplyTo || null,
|
|
393
385
|
from: { id: f.id, name: `${machine}/${f.name || 'session'}`, cwd: f.cwd || '', machine, remote: true },
|
|
394
|
-
...(files.length ? { files } : {}),
|
|
395
386
|
});
|
|
396
|
-
} catch { /* the App's problem: the message is acknowledged anyway, or it would come back forever */ }
|
|
397
|
-
|
|
398
|
-
// until it is done the gateway keeps it: a session that ends meanwhile gets it again, and continues
|
|
399
|
-
this.peerPending.add(cmd.cid);
|
|
400
|
-
handling.catch(() => {}).finally(() => { this.peerPending.delete(cmd.cid); if (!this.closed) ack(); });
|
|
401
|
-
} else {
|
|
402
|
-
ack();
|
|
403
|
-
}
|
|
404
|
-
}
|
|
387
|
+
} catch { /* the App's problem: the message is acknowledged anyway, or it would come back forever */ }
|
|
388
|
+
ack();
|
|
405
389
|
}
|
|
406
390
|
|
|
407
391
|
// The sessions of this gateway account, on every computer, as the gateway lists them (this one included).
|
|
@@ -411,31 +395,13 @@ export class RemoteControl {
|
|
|
411
395
|
}
|
|
412
396
|
|
|
413
397
|
// A message to another session of the account: resolves with {id} (the message's id, which a reply names).
|
|
414
|
-
|
|
415
|
-
async sendPeer(targetId, { kind = 'task', text, inReplyTo = null, files = [] }) {
|
|
398
|
+
async sendPeer(targetId, { kind = 'task', text, inReplyTo = null }) {
|
|
416
399
|
if (!this.registered) await this.register();
|
|
417
|
-
const body = { from: this.id, kind, text, ...(inReplyTo ? { inReplyTo } : {})
|
|
400
|
+
const body = { from: this.id, kind, text, ...(inReplyTo ? { inReplyTo } : {}) };
|
|
418
401
|
const data = await this.request('POST', `/v1/remote/sessions/${encodeURIComponent(targetId)}/messages`, body, { retry: false });
|
|
419
402
|
return { id: data.id, delivered: data.delivered !== false };
|
|
420
403
|
}
|
|
421
404
|
|
|
422
|
-
// ------------------------------------------------------------ files (for another computer's session)
|
|
423
|
-
|
|
424
|
-
get client() { return { base: this.base, apiKey: this.apiKey, fetch: this.fetch }; }
|
|
425
|
-
|
|
426
|
-
// A file of this computer (`{path, name, size}`) onto the gateway, resumably (see transfer.js): resolves with
|
|
427
|
-
// {id, name, size, sha256}, which a message's files refer to.
|
|
428
|
-
uploadFile(file, options) { return uploadFile(this.client, file, options); }
|
|
429
|
-
|
|
430
|
-
// A file another session sent (`{id, name, size, sha256}`) into `dir`: resolves with the path it got.
|
|
431
|
-
downloadFile(file, dir, options) { return downloadFile(this.client, file, dir, options); }
|
|
432
|
-
|
|
433
|
-
deleteFile(id) {
|
|
434
|
-
return this.fetch(`${this.base}/v1/remote/files/${encodeURIComponent(id)}`, {
|
|
435
|
-
method: 'DELETE', headers: { authorization: `Bearer ${this.apiKey}` }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
436
|
-
}).then(() => {}, () => {});
|
|
437
|
-
}
|
|
438
|
-
|
|
439
405
|
// ------------------------------------------------------------ events
|
|
440
406
|
|
|
441
407
|
emit(ev) {
|
package/src/runtime.js
CHANGED
|
@@ -59,7 +59,9 @@ export async function createRuntime({ cwd, flags = {}, io }) {
|
|
|
59
59
|
runtime.systemPrompt = () => {
|
|
60
60
|
if (!promptCache) {
|
|
61
61
|
const autoMemory = config.autoMemoryEnabled ? { dir: memoryDir, index: loadAutoMemoryIndex(memoryDir) } : null;
|
|
62
|
-
promptCache = flags.systemPrompt
|
|
62
|
+
promptCache = flags.systemPrompt !== undefined
|
|
63
|
+
? flags.systemPrompt
|
|
64
|
+
: mainSystemPrompt({ cwd, model: config.mainModel, shellName: shell.name, extra: flags.appendSystemPrompt || '', autoMemory, mcpInstructions: mcp.promptInstructions(), selfRestart: selfEdit, installedCopy: !SOURCE_CHECKOUT, autoCompact: config.autoCompactEnabled, snapshot: snapshotFor(cwd) });
|
|
63
65
|
promptStale = false;
|
|
64
66
|
}
|
|
65
67
|
return promptCache;
|
|
@@ -76,7 +78,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
|
|
|
76
78
|
// it was saved): the new code's prompt is wanted then, e.g. after a Restart for an edit to the prompt. The date in
|
|
77
79
|
// it is brought up to date by a note to the model, which comes after everything that is cached.
|
|
78
80
|
runtime.resumeSystemPrompt = (saved, code) => {
|
|
79
|
-
if (flags.systemPrompt || typeof saved !== 'string' || !saved.trim()) return false;
|
|
81
|
+
if (flags.systemPrompt !== undefined || flags.systemPromptFile !== undefined || typeof saved !== 'string' || !saved.trim()) return false;
|
|
80
82
|
if (code !== PROMPT_CODE_VERSION) return false;
|
|
81
83
|
// --append-system-prompt is the last thing in the prompt: one built with other text is not what this run asked for
|
|
82
84
|
const extra = flags.appendSystemPrompt || '';
|
|
@@ -112,13 +114,14 @@ export async function createRuntime({ cwd, flags = {}, io }) {
|
|
|
112
114
|
const subIo = io.subagentIo ? io.subagentIo({ def, description, parentCtx: ctx }) : {};
|
|
113
115
|
// The main agent is depth 0; an agent below the nesting limit may start sub-agents itself.
|
|
114
116
|
const depth = (ctx.depth ?? ctx.agent?.depth ?? 0) + 1;
|
|
117
|
+
const subTools = toolsForSubagent(runtime.tools, def, { allowTask: depth < config.maxSubagentDepth });
|
|
115
118
|
const sub = new Agent({
|
|
116
119
|
config,
|
|
117
120
|
checkpoints,
|
|
118
121
|
depth,
|
|
119
122
|
spawnSubagent: runtime.spawnSubagent,
|
|
120
|
-
tools:
|
|
121
|
-
systemPrompt: subagentSystemPrompt({ cwd: ctx.cwd, model, shellName: shell.name, agentPrompt: def.prompt, snapshot: snapshotFor(ctx.cwd), readOnly: Boolean(def.readOnly) }),
|
|
123
|
+
tools: subTools,
|
|
124
|
+
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) }),
|
|
122
125
|
io: subIo,
|
|
123
126
|
model,
|
|
124
127
|
isSubagent: true,
|
package/src/tools/peers.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
// ListPeers and MessagePeer: talk to the other claude-pro sessions, on this machine and, through the gateway, on the
|
|
2
2
|
// user's other computers (see peers.js and remote.js).
|
|
3
3
|
|
|
4
|
-
import { resolvePath } from '../utils/paths.js';
|
|
5
|
-
|
|
6
4
|
const unavailable = { isError: true, content: 'Talking to other sessions is only available in an interactive session.' };
|
|
7
5
|
|
|
8
6
|
export const ListPeersTool = {
|
|
@@ -32,20 +30,18 @@ Send it once and wait for the answer: do not send reminders or "please report" f
|
|
|
32
30
|
type: 'object',
|
|
33
31
|
properties: {
|
|
34
32
|
to: { type: 'string', description: 'The name of the session as ListPeers shows it (computer/name for one on another computer)' },
|
|
35
|
-
message: { type: 'string', description: 'The task or question
|
|
36
|
-
files: { type: 'array', items: { type: 'string' }, description: 'Paths of files on this computer to send along (at most 20, 5 GB each; large ones go in the background and continue after a network outage). The other session saves them in its computer\'s Downloads folder, and is told where. With files and no message it only saves them and confirms, without working on anything.' },
|
|
33
|
+
message: { type: 'string', description: 'The task or question to send, written so it stands on its own' },
|
|
37
34
|
},
|
|
38
|
-
required: ['to'],
|
|
35
|
+
required: ['to', 'message'],
|
|
39
36
|
},
|
|
40
37
|
summarize(input) { return `@${input.to}`; },
|
|
41
38
|
async call(input, ctx) {
|
|
42
39
|
if (!ctx.io?.sendToPeer) return unavailable;
|
|
43
|
-
const
|
|
44
|
-
if (!
|
|
40
|
+
const message = String(input.message || '').trim();
|
|
41
|
+
if (!message) return { isError: true, content: 'Give a message to send.' };
|
|
45
42
|
try {
|
|
46
|
-
const { peer
|
|
43
|
+
const { peer } = await ctx.io.sendToPeer(input.to, message, { byModel: true });
|
|
47
44
|
const name = peer.label || peer.name;
|
|
48
|
-
if (background) return { content: `Sending ${files.length} file${files.length === 1 ? '' : 's'} to ${name} in the background (the user sees the progress); the message goes out once they are uploaded, and the answer of ${name} comes back later as a message. Carry on meanwhile, or end your turn.`, display: { summary: `Sending ${files.length} file${files.length === 1 ? '' : 's'} to ${name}` } };
|
|
49
45
|
return { content: `Sent to ${name}. Its answer will arrive later as a message; carry on meanwhile, or end your turn if you need the answer first.`, display: { summary: `Sent to ${name}` } };
|
|
50
46
|
} catch (e) {
|
|
51
47
|
return { isError: true, content: e.message };
|