@yanzc/claude-pro 0.5.8 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -9
- package/package.json +1 -1
- package/src/agent.js +10 -1
- package/src/agents.js +3 -1
- package/src/commands.js +46 -47
- package/src/config.js +16 -7
- package/src/host.js +1031 -0
- package/src/main.js +19 -4
- package/src/prompts.js +74 -58
- package/src/qr.js +1 -1
- package/src/remote.js +4 -2
- package/src/runtime.js +14 -8
- package/src/session.js +5 -2
- package/src/supervisor.js +1 -1
- package/src/tools/bash.js +3 -8
- package/src/tools/files.js +6 -10
- package/src/tools/index.js +1 -1
- package/src/tools/interaction.js +8 -37
- package/src/tools/search.js +15 -10
- package/src/tools/task.js +29 -7
- package/src/ui/repl.js +89 -45
- package/src/utils/images.js +87 -24
package/src/tools/search.js
CHANGED
|
@@ -16,9 +16,7 @@ export const GlobTool = {
|
|
|
16
16
|
description: `- Fast file pattern matching tool that works with any codebase size
|
|
17
17
|
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
18
18
|
- Returns matching file paths sorted by modification time (most recent first)
|
|
19
|
-
- Use this tool when you need to find files by name patterns
|
|
20
|
-
- When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
|
|
21
|
-
- You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful.`,
|
|
19
|
+
- Use this tool when you need to find files by name patterns`,
|
|
22
20
|
input_schema: {
|
|
23
21
|
type: 'object',
|
|
24
22
|
properties: {
|
|
@@ -266,16 +264,24 @@ function runRg(bin, args, cwd, signal) {
|
|
|
266
264
|
});
|
|
267
265
|
}
|
|
268
266
|
|
|
267
|
+
// ripgrep takes inline flags at the start of a pattern, `(?i)` or `(?is)`; a JS RegExp does not, so they become
|
|
268
|
+
// flags. `m` is dropped: ^ and $ are line anchors here anyway, as in ripgrep.
|
|
269
|
+
export function inlineFlags(pattern) {
|
|
270
|
+
const m = /^\(\?([ims]+)\)/.exec(pattern);
|
|
271
|
+
return m ? { pattern: pattern.slice(m[0].length), i: m[1].includes('i'), s: m[1].includes('s') } : { pattern, i: false, s: false };
|
|
272
|
+
}
|
|
273
|
+
|
|
269
274
|
// JS scanner used when ripgrep isn't available. Returns output lines in rg's format.
|
|
270
275
|
async function jsGrep(input, base, mode, signal) {
|
|
271
276
|
const exts = input.type ? TYPE_EXT[String(input.type).toLowerCase()] : null;
|
|
272
277
|
if (input.type && !exts) throw new Error(`unrecognized file type: ${input.type} (known types: ${Object.keys(TYPE_EXT).join(', ')})`);
|
|
273
|
-
const
|
|
274
|
-
const
|
|
278
|
+
const inline = inlineFlags(input.pattern);
|
|
279
|
+
const flags = input['-i'] || inline.i ? 'i' : '';
|
|
280
|
+
const dotAll = input.multiline || inline.s ? 's' : '';
|
|
275
281
|
// ripgrep treats ^ and $ as line anchors, so whole-file matching needs the m flag.
|
|
276
|
-
const anyRe = new RegExp(
|
|
277
|
-
const allRe = new RegExp(
|
|
278
|
-
const lineRe = new RegExp(
|
|
282
|
+
const anyRe = new RegExp(inline.pattern, `${flags}m${dotAll}`);
|
|
283
|
+
const allRe = new RegExp(inline.pattern, `${flags}gm${dotAll}`);
|
|
284
|
+
const lineRe = new RegExp(inline.pattern, flags);
|
|
279
285
|
const content = mode === 'content';
|
|
280
286
|
const before = content ? Math.max(0, Number(input['-B'] ?? input['-C'] ?? 0) || 0) : 0;
|
|
281
287
|
const after = content ? Math.max(0, Number(input['-A'] ?? input['-C'] ?? 0) || 0) : 0;
|
|
@@ -359,11 +365,10 @@ export const GrepTool = {
|
|
|
359
365
|
description: `A powerful search tool built on ripgrep
|
|
360
366
|
|
|
361
367
|
Usage:
|
|
362
|
-
-
|
|
368
|
+
- Use this tool to search file contents rather than \`grep\` or \`rg\` through Bash (rg may not be installed on the machine).
|
|
363
369
|
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
|
|
364
370
|
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
|
|
365
371
|
- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
|
|
366
|
-
- Use Task tool for open-ended searches requiring multiple rounds
|
|
367
372
|
- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
|
|
368
373
|
- Multiline matching: By default patterns match within single lines only. For cross-line patterns like \`struct \\{[\\s\\S]*?field\`, use \`multiline: true\``,
|
|
369
374
|
input_schema: {
|
package/src/tools/task.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { taskResultText } from '../tasks.js';
|
|
6
6
|
import { EFFORTS } from '../agents.js';
|
|
7
|
+
import { priceOf } from '../pricing.js';
|
|
7
8
|
|
|
8
9
|
// Wait for `promise`, at most `ms`, or until `signal` aborts. The timer is always cleared so a
|
|
9
10
|
// finished wait never keeps the process alive.
|
|
@@ -20,14 +21,34 @@ function waitFor(promise, ms, signal) {
|
|
|
20
21
|
});
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
|
|
24
|
+
// How to pick a sub-agent's model, where the main agent chooses it (Config.subagentModelChosen): the models the
|
|
25
|
+
// aliases stand for, with their prices. Built from the configuration of the moment, so that it follows /model and
|
|
26
|
+
// /login (which start a new prompt cache anyway); it holds nothing that changes otherwise.
|
|
27
|
+
export function modelChoiceText(config) {
|
|
28
|
+
if (!config?.subagentModelChosen) return '';
|
|
29
|
+
const main = config.mainModel.id;
|
|
30
|
+
const option = (alias) => {
|
|
31
|
+
const id = config.resolveModel(alias).id;
|
|
32
|
+
const p = priceOf(id);
|
|
33
|
+
return `${alias} (${id}${id === main ? ', your own model' : ''}${p ? `, $${p.input}/$${p.output} per million input/output tokens` : ''})`;
|
|
34
|
+
};
|
|
35
|
+
return `
|
|
36
|
+
|
|
37
|
+
Choosing the model: there is no fixed sub-agent model. Choose one for each task by how hard it is and how much you will rely on the report, and give it in \`model\`:
|
|
38
|
+
- ${option('haiku')}: mechanical work with a clear target: find where something is defined or used, list files, read files and quote the relevant parts.
|
|
39
|
+
- ${option('sonnet')}: searches across a codebase and well-specified subtasks whose steps are clear: gather the call sites of a function and how they use it, run tests and summarize the failures, make a change that is fully described.
|
|
40
|
+
- ${option('opus')}: work whose quality your answer depends on and that you will not redo yourself: hard debugging, design and trade-offs, reviewing code for subtle bugs, analysis that spans many files.
|
|
41
|
+
A shallow or wrong report that you rely on costs more than the difference in price; a strong model on a lookup only wastes money. Set \`effort\` with it (low suits lookups); without it the agent runs at your session's effort. Without \`model\` an agent runs on its definition's model, else on ${config.subagentModel.id}.`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function makeTaskTool(agents, config = null) {
|
|
24
45
|
const list = [...agents.values()]
|
|
25
|
-
.map((a) => `- ${a.name}: ${a.description} (Tools: ${a.tools === '*' ? 'All tools' : a.tools.join(', ')})`)
|
|
46
|
+
.map((a) => `- ${a.name}: ${a.description} (Tools: ${a.tools === '*' ? 'All tools' : a.tools.join(', ')})${a.model ? ` (model: ${a.model})` : ''}`)
|
|
26
47
|
.join('\n');
|
|
27
48
|
return {
|
|
28
49
|
name: 'Task',
|
|
29
50
|
readOnly: true, // sub-agents ask for their own permissions; multiple tasks may run in parallel
|
|
30
|
-
description: `Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
51
|
+
description: () => `Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
31
52
|
|
|
32
53
|
Available agent types and the tools they have access to:
|
|
33
54
|
${list}
|
|
@@ -40,12 +61,13 @@ When NOT to use the Task tool:
|
|
|
40
61
|
- If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead
|
|
41
62
|
|
|
42
63
|
Usage notes:
|
|
43
|
-
-
|
|
64
|
+
- When several independent tasks are worth delegating, start them in a single message with multiple tool uses so that they run concurrently. Do not split closely coupled work between agents: they do not see each other's work, and each one costs its own context and tokens
|
|
44
65
|
- When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
|
|
45
66
|
- Each agent invocation is stateless. Your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message.
|
|
46
|
-
-
|
|
67
|
+
- Once you have delegated a search or an investigation, do not also do it yourself: wait for the report, doing other work meanwhile. Never make up or predict the result of an agent that is still running; if the user asks before it is done, say that it is still running.
|
|
68
|
+
- A sub-agent may run on a smaller model than yours. Use its report to find your way, but before you build an answer or a change on one of its findings, check that finding yourself (read the lines it cites)
|
|
47
69
|
- Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
|
|
48
|
-
- Set run_in_background: true to start the agent and continue working while it runs (e.g. a long investigation, or several independent jobs). You get a task id back immediately, and the agent's final report arrives automatically in a <task-notification> once it finishes; you do not need to poll. Use TaskOutput to check on or wait for it early, and TaskStop to cancel it. Do not start background agents that edit the same files at the same time
|
|
70
|
+
- Set run_in_background: true to start the agent and continue working while it runs (e.g. a long investigation, or several independent jobs). You get a task id back immediately, and the agent's final report arrives automatically in a <task-notification> once it finishes; you do not need to poll. Use TaskOutput to check on or wait for it early, and TaskStop to cancel it. Do not start background agents that edit the same files at the same time.${modelChoiceText(config)}`,
|
|
49
71
|
input_schema: {
|
|
50
72
|
type: 'object',
|
|
51
73
|
properties: {
|
|
@@ -53,7 +75,7 @@ Usage notes:
|
|
|
53
75
|
prompt: { type: 'string', description: 'The task for the agent to perform' },
|
|
54
76
|
subagent_type: { type: 'string', description: 'The type of specialized agent to use for this task' },
|
|
55
77
|
run_in_background: { type: 'boolean', description: 'Run the agent in the background and return immediately with a task id' },
|
|
56
|
-
model: { type: 'string', description: '
|
|
78
|
+
model: { type: 'string', description: 'Model for this agent: haiku, sonnet, opus or a full model id. Pick it by how hard the task is: a smaller model is cheaper and faster for lookups and clear subtasks, a stronger one is right when you rely on the quality of its report. Defaults to the agent definition\'s model, else the sub-agent default.' },
|
|
57
79
|
effort: { type: 'string', enum: EFFORTS, description: 'Optional effort level for this agent (default: the agent definition\'s, else the session\'s). Low suits quick lookups, high or above hard reasoning.' },
|
|
58
80
|
},
|
|
59
81
|
required: ['description', 'prompt', 'subagent_type'],
|
package/src/ui/repl.js
CHANGED
|
@@ -6,7 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import readline from 'node:readline';
|
|
8
8
|
import { spawn } from 'node:child_process';
|
|
9
|
-
import { c, ESC, stringWidth, truncate, padEnd, wordWrap
|
|
9
|
+
import { c, ESC, stringWidth, truncate, padEnd, wordWrap } from './ansi.js';
|
|
10
10
|
import { Screen, queryCursorRow, mouseFilter } from './screen.js';
|
|
11
11
|
import { Editor, topBorder } from './editor.js';
|
|
12
12
|
import { SelectDialog } from './dialogs.js';
|
|
@@ -18,7 +18,7 @@ import { createRuntime } from '../runtime.js';
|
|
|
18
18
|
import { SessionStore, firstUserText } from '../session.js';
|
|
19
19
|
import { defaultEffort, effortSupported, effortToSend, quickQuery } from '../api.js';
|
|
20
20
|
import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
|
|
21
|
-
import { readGatewayLogin, formatUsd } from '../gateway.js';
|
|
21
|
+
import { readGatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
|
|
22
22
|
import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
|
|
23
23
|
import { buildCommands } from '../commands.js';
|
|
24
24
|
import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
|
|
@@ -34,7 +34,7 @@ import { copyUnique } from '../transfer.js';
|
|
|
34
34
|
import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer, CHECK_EVERY_MS } from '../updater.js';
|
|
35
35
|
import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
|
|
36
36
|
import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
|
|
37
|
-
import {
|
|
37
|
+
import { ensureHost as startHostIfNeeded, hostEnabled } from '../host.js';
|
|
38
38
|
|
|
39
39
|
// A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
|
|
40
40
|
export const modelTag = (model) => String(model?.id ?? '').replace(/^claude-/, '').replace(/-\d{8}$/, '');
|
|
@@ -187,7 +187,8 @@ export class App {
|
|
|
187
187
|
this.remoteMuted = 0; // > 0 while printing something the page is told about in its own terms
|
|
188
188
|
this.remoteDialogs = 0;
|
|
189
189
|
this.remoteStarting = null;
|
|
190
|
-
this.
|
|
190
|
+
this.remoteRefused = null; // a gateway key the gateway refused: not tried again by itself (a new /login is)
|
|
191
|
+
this.selfCheck = selfCheck;
|
|
191
192
|
this.sessionName = flags?.restart?.peerName || null; // this session's name when the sessions of this computer do not know it (CLAUDE_PRO_PEERS=0)
|
|
192
193
|
this.customTitle = null; // the conversation's name given with /rename: the title, instead of the topic
|
|
193
194
|
this.remotePeers = []; // the account's sessions on other computers, as last listed by the gateway (see peers.js)
|
|
@@ -279,6 +280,7 @@ export class App {
|
|
|
279
280
|
if (restart) this.resumeAfterRestart(restart, resumable);
|
|
280
281
|
else if (this.flags.resumeFile) this.loadSession(this.flags.resumeFile, this.flags.resumeId);
|
|
281
282
|
else if (this.flags.resume) await this.commands.get('resume').run('');
|
|
283
|
+
if (!restart && this.flags.name?.trim()) this.renameSession(this.flags.name); // --name, as /rename does
|
|
282
284
|
this.autoStartRemote(restart);
|
|
283
285
|
|
|
284
286
|
this.screen.setLive((w) => this.renderLive(w));
|
|
@@ -300,6 +302,11 @@ export class App {
|
|
|
300
302
|
// and every few minutes while it runs, so that a release reaches a session that stays open for days
|
|
301
303
|
this.updateTimer = setInterval(() => { if (!this.exiting) this.autoUpdate({ quiet: true }); }, CHECK_EVERY_MS);
|
|
302
304
|
this.updateTimer.unref?.();
|
|
305
|
+
// online or offline as this computer's gateway login changes (/login or /logout in another window)
|
|
306
|
+
this.loginTimer = setInterval(() => this.syncRemote(), 10_000);
|
|
307
|
+
this.loginTimer.unref?.();
|
|
308
|
+
// the computer service (a process of its own, see host.js), once the session is up
|
|
309
|
+
setTimeout(() => this.ensureHost(), 3000).unref?.();
|
|
303
310
|
}
|
|
304
311
|
return new Promise((resolve) => { this.resolveExit = resolve; });
|
|
305
312
|
}
|
|
@@ -388,6 +395,7 @@ export class App {
|
|
|
388
395
|
this.runtime?.mcp.close();
|
|
389
396
|
this.peers?.close();
|
|
390
397
|
clearInterval(this.remotePeersTimer);
|
|
398
|
+
clearInterval(this.loginTimer);
|
|
391
399
|
const remoteClosed = this.remote?.close({ restarting: restart });
|
|
392
400
|
const u = this.agent?.totalUsage();
|
|
393
401
|
if (!restart && u && u.requests) {
|
|
@@ -451,12 +459,12 @@ export class App {
|
|
|
451
459
|
let found = resolvePeer(local, this.remotePeers, target);
|
|
452
460
|
if (!found.peer && !found.error && this.remote) found = resolvePeer(local, await this.refreshRemotePeers(), target);
|
|
453
461
|
if (!found.peer) {
|
|
454
|
-
const offline = this.remote ? '' : ' Sessions on your other computers can be reached once this one is online at the gateway (/login
|
|
462
|
+
const offline = this.remote ? '' : ' Sessions on your other computers can be reached once this one is online at the gateway (/login).';
|
|
455
463
|
throw new Error(found.error || `No running session called "${String(target).replace(/^[@&]/, '')}". /peers lists them.${offline}`);
|
|
456
464
|
}
|
|
457
465
|
peer = found.peer;
|
|
458
466
|
}
|
|
459
|
-
if (peer.remote && !this.remote) throw new Error(`&${peer.label} is on another computer, and this session is not online at the gateway (/
|
|
467
|
+
if (peer.remote && !this.remote) throw new Error(`&${peer.label} is on another computer, and this session is not online at the gateway (/status says why).`);
|
|
460
468
|
if (!peer.remote && !this.peers) throw new Error('Talking to other sessions on this computer is off (CLAUDE_PRO_PEERS=0).');
|
|
461
469
|
const send = async () => {
|
|
462
470
|
let r;
|
|
@@ -724,34 +732,68 @@ export class App {
|
|
|
724
732
|
this.remote?.emit({ t: 'user', text: images ? `${text}\n[${images} image${images === 1 ? '' : 's'}]` : String(text) });
|
|
725
733
|
}
|
|
726
734
|
|
|
727
|
-
//
|
|
728
|
-
//
|
|
729
|
-
//
|
|
730
|
-
|
|
735
|
+
// Whether this session should be online at the gateway (see remote.js): whenever this computer is logged in to
|
|
736
|
+
// it. CLAUDE_PRO_ONLINE=0 keeps it off (the self-check sets it); the tests, which drive the App themselves, go
|
|
737
|
+
// online only with CLAUDE_PRO_ONLINE=1.
|
|
738
|
+
onlineWanted() {
|
|
739
|
+
const env = this.config.env;
|
|
740
|
+
if (!onlineEnabled(env)) return false;
|
|
741
|
+
if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
|
|
742
|
+
return Boolean(readGatewayLogin(this.config.gatewayUrl));
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// Online at the gateway from the start, without holding the start up: when this computer is logged in to it; with
|
|
746
|
+
// --remote-id (a session the gateway's web page opened through claude-pro host: online at once, with the id the
|
|
747
|
+
// page waits for); and after a restart as before (with the same id, so that open pages and messages on their way
|
|
748
|
+
// find it again).
|
|
731
749
|
autoStartRemote(restart) {
|
|
732
|
-
const
|
|
733
|
-
if (
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
this.startRemote({ id: carried?.id, quiet: !explicit || Boolean(carried?.id), persistent: !explicit }).catch((e) => {
|
|
738
|
-
this.notice(`${explicit ? 'Remote control could not start' : 'This session could not go online at the gateway'}: ${e.message}${e.code === 'NO_GATEWAY_LOGIN' ? '' : ' (/rc tries again)'}`, 'warn');
|
|
750
|
+
const id = restart?.remote?.id || this.flags.remoteId || null;
|
|
751
|
+
if (!id && !this.onlineWanted()) return;
|
|
752
|
+
this.startRemote({ id }).catch((e) => {
|
|
753
|
+
if (e.code === 'NO_GATEWAY_LOGIN' && !this.flags.remoteId) return;
|
|
754
|
+
this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
|
|
739
755
|
});
|
|
740
756
|
}
|
|
741
757
|
|
|
742
758
|
// Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
|
|
743
|
-
// computers reach it from then on. Needs the gateway login of /login (the provider
|
|
744
|
-
// {code: 'NO_GATEWAY_LOGIN'} without it.
|
|
745
|
-
// the background
|
|
746
|
-
startRemote({ id
|
|
759
|
+
// computers reach it from then on. Needs the gateway login of /login (the provider of the model requests can be
|
|
760
|
+
// another one); throws {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried
|
|
761
|
+
// again in the background; one that refuses the key throws, and that key is not tried again (see syncRemote).
|
|
762
|
+
startRemote({ id } = {}) {
|
|
747
763
|
if (this.remote) return Promise.resolve(this.remote);
|
|
748
|
-
this.remoteStarting ??= this.connectRemote({ id
|
|
764
|
+
this.remoteStarting ??= this.connectRemote({ id }).finally(() => { this.remoteStarting = null; });
|
|
749
765
|
return this.remoteStarting;
|
|
750
766
|
}
|
|
751
767
|
|
|
752
|
-
|
|
768
|
+
// Online or offline as this computer's gateway login is now: after /login and /logout, and every few seconds (a
|
|
769
|
+
// login or a logout in another window, another account). Resolves with the connection, or null.
|
|
770
|
+
syncRemote() {
|
|
771
|
+
if (this.exiting) return Promise.resolve(null);
|
|
772
|
+
if (this.remoteStarting) return this.remoteStarting.catch(() => null);
|
|
773
|
+
const login = readGatewayLogin(this.config.gatewayUrl);
|
|
774
|
+
const r = this.remote;
|
|
775
|
+
// logged out, or another account: not this account's session any more
|
|
776
|
+
if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
|
|
777
|
+
if (this.remote) return Promise.resolve(this.remote);
|
|
778
|
+
if (!login || login.apiKey === this.remoteRefused || !(this.flags.remoteId || this.onlineWanted())) return Promise.resolve(null);
|
|
779
|
+
return this.startRemote().catch((e) => {
|
|
780
|
+
this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
|
|
781
|
+
return null;
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// The computer service (see host.js): started in the background when none runs, so that the gateway's web page can
|
|
786
|
+
// open sessions on this computer even when no session is open. Not in the tests nor in the self-check.
|
|
787
|
+
ensureHost() {
|
|
788
|
+
const env = this.config.env;
|
|
789
|
+
if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
|
|
790
|
+
if (!onlineEnabled(env) || !hostEnabled(env) || !readGatewayLogin(this.config.gatewayUrl)) return;
|
|
791
|
+
try { startHostIfNeeded(); } catch { /* the next session tries again */ }
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
async connectRemote({ id }) {
|
|
753
795
|
const login = readGatewayLogin(this.config.gatewayUrl);
|
|
754
|
-
if (!login) throw Object.assign(new Error(`
|
|
796
|
+
if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login logs in)`), { code: 'NO_GATEWAY_LOGIN' });
|
|
755
797
|
const remote = new RemoteControl({
|
|
756
798
|
gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
|
|
757
799
|
id,
|
|
@@ -770,13 +812,17 @@ export class App {
|
|
|
770
812
|
},
|
|
771
813
|
});
|
|
772
814
|
remote.account = login.account?.email || login.account?.name || null;
|
|
773
|
-
|
|
815
|
+
try {
|
|
816
|
+
await remote.start({ persistent: true });
|
|
817
|
+
} catch (e) {
|
|
818
|
+
if (e.status === 401 || e.status === 403) this.remoteRefused = login.apiKey;
|
|
819
|
+
throw e;
|
|
820
|
+
}
|
|
774
821
|
if (this.exiting) { remote.close(); return remote; }
|
|
775
822
|
this.remote = remote;
|
|
776
|
-
this.
|
|
823
|
+
this.remoteRefused = null;
|
|
777
824
|
this.remotePeersTimer ??= setInterval(() => { if (this.remote?.online) this.refreshRemotePeers(); }, 60_000);
|
|
778
825
|
this.remotePeersTimer.unref?.();
|
|
779
|
-
if (!quiet) this.logLocal(this.remoteInfo({ fresh: true }));
|
|
780
826
|
this.screen.schedule();
|
|
781
827
|
return remote;
|
|
782
828
|
}
|
|
@@ -785,26 +831,24 @@ export class App {
|
|
|
785
831
|
this.remote?.close();
|
|
786
832
|
this.remote = null;
|
|
787
833
|
this.remotePeers = [];
|
|
788
|
-
this.remoteStopped = true;
|
|
789
834
|
this.screen.schedule();
|
|
790
835
|
}
|
|
791
836
|
|
|
792
|
-
//
|
|
793
|
-
|
|
837
|
+
// This session at the gateway, for /status: {text, url} (url: its page, once registered).
|
|
838
|
+
remoteState() {
|
|
794
839
|
const r = this.remote;
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
return lines;
|
|
840
|
+
if (r) {
|
|
841
|
+
const who = r.account ? ` as ${r.account}` : '';
|
|
842
|
+
const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
|
|
843
|
+
const text = r.online ? `${c.green('online')}${who}${pages}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
|
|
844
|
+
return { text, url: r.url };
|
|
845
|
+
}
|
|
846
|
+
if (this.remoteStarting) return { text: 'connecting…', url: null };
|
|
847
|
+
const login = readGatewayLogin(this.config.gatewayUrl);
|
|
848
|
+
if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`), url: null };
|
|
849
|
+
if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)'), url: null };
|
|
850
|
+
if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)'), url: null };
|
|
851
|
+
return { text: c.dim('offline'), url: null };
|
|
808
852
|
}
|
|
809
853
|
|
|
810
854
|
// The state the page shows below the transcript; sent whenever it changes.
|
|
@@ -954,7 +998,7 @@ export class App {
|
|
|
954
998
|
restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), now],
|
|
955
999
|
peerName: this.peers?.name || this.sessionName,
|
|
956
1000
|
peerId: this.peers?.id,
|
|
957
|
-
remote: this.remote?.handoff() ||
|
|
1001
|
+
remote: this.remote?.handoff() || null,
|
|
958
1002
|
};
|
|
959
1003
|
try {
|
|
960
1004
|
writeRestartState(state);
|
|
@@ -1795,7 +1839,7 @@ export class App {
|
|
|
1795
1839
|
this.agent.lastContextTokens = estimateTokens(loaded.messages);
|
|
1796
1840
|
// Continue behind the system prompt the conversation had (and its cache), not a freshly built one.
|
|
1797
1841
|
this.store.systemPrompt = loaded.systemPrompt;
|
|
1798
|
-
this.runtime.resumeSystemPrompt(loaded.systemPrompt);
|
|
1842
|
+
this.runtime.resumeSystemPrompt(loaded.systemPrompt, loaded.promptCode);
|
|
1799
1843
|
if (!this.topic) this.refreshTopic(this.latestPrompt()); // a session from before topics were kept
|
|
1800
1844
|
this.remote?.resync();
|
|
1801
1845
|
if (quiet) return;
|
package/src/utils/images.js
CHANGED
|
@@ -4,7 +4,13 @@
|
|
|
4
4
|
// the model loses nothing it would have seen, and the conversation never carries an image that a later request
|
|
5
5
|
// is refused for. There is no image library: Windows scales with System.Drawing (PowerShell), macOS with sips,
|
|
6
6
|
// elsewhere ImageMagick when it is installed.
|
|
7
|
+
//
|
|
8
|
+
// A heavy PNG goes as JPEG (see PNG_AS_JPEG_BYTES). A screenshot of a 3D scene or a photo hardly compresses as
|
|
9
|
+
// PNG (2.3MB at 723×1568, 180KB as JPEG), and every request carries the whole conversation: a session that
|
|
10
|
+
// looked at eleven of them sent 31MB a request, which took the gateway past its memory limit and is close to the
|
|
11
|
+
// API's 32MB. Images are billed by their pixels, not their bytes, so tokens stay the same.
|
|
7
12
|
|
|
13
|
+
import crypto from 'node:crypto';
|
|
8
14
|
import fs from 'node:fs';
|
|
9
15
|
import os from 'node:os';
|
|
10
16
|
import path from 'node:path';
|
|
@@ -13,6 +19,7 @@ import { spawn } from 'node:child_process';
|
|
|
13
19
|
export const MAX_IMAGE_EDGE = 1568;
|
|
14
20
|
const API_MAX_EDGE = 2000; // what a request with many images accepts: sent as it is when it cannot be scaled
|
|
15
21
|
export const MAX_IMAGE_BYTES = 3_750_000; // ~5MB once base64 encoded
|
|
22
|
+
export const PNG_AS_JPEG_BYTES = 512 * 1024; // a PNG larger than this goes as JPEG (quality 85) when that is smaller
|
|
16
23
|
|
|
17
24
|
// {width, height} from the header of a PNG, JPEG, GIF or WebP; null for anything else.
|
|
18
25
|
export function imageSize(buf) {
|
|
@@ -75,60 +82,80 @@ $g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
|
|
75
82
|
$g.DrawImage($img, 0, 0, $w, $h)
|
|
76
83
|
$g.Dispose(); $img.Dispose()
|
|
77
84
|
$out = $env:CLAUDE_PRO_IMG_OUT
|
|
85
|
+
$jpegOnly = $env:CLAUDE_PRO_IMG_JPEG -eq '1'
|
|
78
86
|
$format = 'png'
|
|
79
|
-
if (
|
|
80
|
-
if ($
|
|
87
|
+
if (-not $jpegOnly) { $bmp.Save($out, [System.Drawing.Imaging.ImageFormat]::Png) }
|
|
88
|
+
if ($jpegOnly -or (Get-Item $out).Length -gt [int]$env:CLAUDE_PRO_IMG_BYTES) {
|
|
89
|
+
# JPEG has no transparency: flatten onto white (a screenshot has none to lose)
|
|
90
|
+
$flat = New-Object System.Drawing.Bitmap $w, $h
|
|
91
|
+
$g = [System.Drawing.Graphics]::FromImage($flat)
|
|
92
|
+
$g.Clear([System.Drawing.Color]::White)
|
|
93
|
+
$g.DrawImage($bmp, 0, 0, $w, $h)
|
|
94
|
+
$g.Dispose()
|
|
81
95
|
$codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq 'image/jpeg' }
|
|
82
96
|
$params = New-Object System.Drawing.Imaging.EncoderParameters 1
|
|
83
97
|
$params.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality), 85L
|
|
84
|
-
$
|
|
85
|
-
$
|
|
98
|
+
$jpg = "$out.jpg"
|
|
99
|
+
$flat.Save($jpg, $codec, $params)
|
|
100
|
+
$flat.Dispose()
|
|
101
|
+
if ($jpegOnly -or (Get-Item $jpg).Length -lt (Get-Item $out).Length) { Move-Item -Force $jpg $out; $format = 'jpeg' } else { Remove-Item $jpg }
|
|
86
102
|
}
|
|
87
103
|
$bmp.Dispose()
|
|
88
104
|
Write-Output "IMG $format"
|
|
89
105
|
`;
|
|
90
106
|
|
|
91
107
|
// The image file `input` scaled to fit `max` px into a new file: {buffer, media_type}, or null when nothing here
|
|
92
|
-
// can scale images.
|
|
108
|
+
// can scale images. `jpeg`: as JPEG; else as PNG, or as JPEG when the PNG is over PNG_AS_JPEG_BYTES and the JPEG
|
|
109
|
+
// is smaller.
|
|
93
110
|
async function scaleFile(input, { max, jpeg }) {
|
|
94
111
|
const out = path.join(os.tmpdir(), `claude-pro-img-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
|
|
95
112
|
try {
|
|
96
113
|
if (process.platform === 'win32') {
|
|
97
114
|
const r = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(PS_SCALE, 'utf16le').toString('base64')], {
|
|
98
|
-
env: { CLAUDE_PRO_IMG_IN: input, CLAUDE_PRO_IMG_OUT: out, CLAUDE_PRO_IMG_MAX: String(max), CLAUDE_PRO_IMG_JPEG: jpeg ? '1' : '', CLAUDE_PRO_IMG_BYTES: String(
|
|
115
|
+
env: { CLAUDE_PRO_IMG_IN: input, CLAUDE_PRO_IMG_OUT: out, CLAUDE_PRO_IMG_MAX: String(max), CLAUDE_PRO_IMG_JPEG: jpeg ? '1' : '', CLAUDE_PRO_IMG_BYTES: String(PNG_AS_JPEG_BYTES) },
|
|
99
116
|
});
|
|
100
117
|
const m = /IMG (png|jpeg)/.exec(r.out);
|
|
101
118
|
if (r.code !== 0 || !m) return null;
|
|
102
119
|
return { buffer: fs.readFileSync(out), media_type: `image/${m[1]}` };
|
|
103
120
|
}
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
121
|
+
const produce = async (format) => {
|
|
122
|
+
const target = `${out}.${format === 'jpeg' ? 'jpg' : 'png'}`;
|
|
123
|
+
const asJpeg = format === 'jpeg' ? ['-background', 'white', '-flatten', '-quality', '85'] : [];
|
|
124
|
+
const tries = process.platform === 'darwin'
|
|
125
|
+
? [['sips', ['-Z', String(max), '-s', 'format', format, ...(format === 'jpeg' ? ['-s', 'formatOptions', '85'] : []), input, '--out', target]]]
|
|
126
|
+
: [['magick', [input, '-resize', `${max}x${max}>`, ...asJpeg, target]], ['convert', [input, '-resize', `${max}x${max}>`, ...asJpeg, target]]];
|
|
127
|
+
for (const [cmd, args] of tries) {
|
|
128
|
+
const r = await run(cmd, args);
|
|
129
|
+
if (r.code === 0 && fs.existsSync(target)) {
|
|
130
|
+
try { return { buffer: fs.readFileSync(target), media_type: `image/${format}` }; } finally { fs.rm(target, { force: true }, () => {}); }
|
|
131
|
+
}
|
|
112
132
|
}
|
|
113
|
-
|
|
114
|
-
|
|
133
|
+
return null;
|
|
134
|
+
};
|
|
135
|
+
if (jpeg) return await produce('jpeg');
|
|
136
|
+
const png = await produce('png');
|
|
137
|
+
if (!png || png.buffer.length <= PNG_AS_JPEG_BYTES) return png;
|
|
138
|
+
const jpg = await produce('jpeg');
|
|
139
|
+
return jpg && jpg.buffer.length < png.buffer.length ? jpg : png;
|
|
115
140
|
} catch {
|
|
116
141
|
return null;
|
|
117
142
|
} finally {
|
|
118
143
|
fs.rm(out, { force: true }, () => {});
|
|
144
|
+
fs.rm(`${out}.jpg`, { force: true }, () => {});
|
|
119
145
|
}
|
|
120
146
|
}
|
|
121
147
|
|
|
122
|
-
// The image as the model should get it. `data` is base64. Returns {data, media_type, width, height, from}
|
|
123
|
-
// `from` is the size it had when it was scaled (null when
|
|
124
|
-
// and cannot be scaled here.
|
|
148
|
+
// The image as the model should get it. `data` is base64. Returns {data, media_type, width, height, from, changed}
|
|
149
|
+
// where `from` is the size it had when it was scaled (null when its size stays) and `changed` says whether `data`
|
|
150
|
+
// is new (scaled, or a heavy PNG as JPEG), or {error} when it is too large and cannot be scaled here.
|
|
125
151
|
export async function fitImage({ data, media_type }) {
|
|
126
152
|
const buf = Buffer.from(data, 'base64');
|
|
127
153
|
const size = imageSize(buf);
|
|
128
|
-
const keep = { data, media_type, width: size?.width ?? null, height: size?.height ?? null, from: null };
|
|
154
|
+
const keep = { data, media_type, width: size?.width ?? null, height: size?.height ?? null, from: null, changed: false };
|
|
129
155
|
if (!size) return keep; // not a format it knows: the API will say what it thinks of it
|
|
130
156
|
const edge = Math.max(size.width, size.height);
|
|
131
|
-
|
|
157
|
+
const heavyPng = media_type === 'image/png' && buf.length > PNG_AS_JPEG_BYTES;
|
|
158
|
+
if (edge <= MAX_IMAGE_EDGE && buf.length <= MAX_IMAGE_BYTES && !heavyPng) return keep;
|
|
132
159
|
const ext = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp' }[media_type] || '.img';
|
|
133
160
|
const input = path.join(os.tmpdir(), `claude-pro-img-in-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}${ext}`);
|
|
134
161
|
let scaled = null;
|
|
@@ -139,8 +166,10 @@ export async function fitImage({ data, media_type }) {
|
|
|
139
166
|
fs.rm(input, { force: true }, () => {});
|
|
140
167
|
}
|
|
141
168
|
const got = scaled && imageSize(scaled.buffer);
|
|
142
|
-
|
|
143
|
-
|
|
169
|
+
const smaller = edge > MAX_IMAGE_EDGE; // in pixels
|
|
170
|
+
// the new one when it fits, and is needed or at least lighter (a PNG that stayed PNG may not be)
|
|
171
|
+
if (got && Math.max(got.width, got.height) <= API_MAX_EDGE && scaled.buffer.length <= MAX_IMAGE_BYTES && (smaller || buf.length > MAX_IMAGE_BYTES || scaled.buffer.length < buf.length)) {
|
|
172
|
+
return { data: scaled.buffer.toString('base64'), media_type: scaled.media_type, width: got.width, height: got.height, from: smaller ? size : null, changed: true };
|
|
144
173
|
}
|
|
145
174
|
if (edge <= API_MAX_EDGE && buf.length <= MAX_IMAGE_BYTES) return keep;
|
|
146
175
|
return { error: `the image is ${size.width}×${size.height} px${buf.length > MAX_IMAGE_BYTES ? ` and ${(buf.length / 1e6).toFixed(1)}MB` : ''}, more than the API accepts (${API_MAX_EDGE} px a side when a conversation has many images), and it could not be scaled down here` };
|
|
@@ -164,7 +193,7 @@ export async function fitImagesIn(blocks) {
|
|
|
164
193
|
for (const k of Object.keys(b)) delete b[k];
|
|
165
194
|
Object.assign(b, { type: 'text', text: `[image left out: ${fit.error}]` }, mark ? { cache_control: mark } : {});
|
|
166
195
|
changed++;
|
|
167
|
-
} else if (fit.
|
|
196
|
+
} else if (fit.changed) {
|
|
168
197
|
b.source = { type: 'base64', media_type: fit.media_type, data: fit.data };
|
|
169
198
|
changed++;
|
|
170
199
|
}
|
|
@@ -173,3 +202,37 @@ export async function fitImagesIn(blocks) {
|
|
|
173
202
|
await visit(blocks);
|
|
174
203
|
return changed;
|
|
175
204
|
}
|
|
205
|
+
|
|
206
|
+
// Heavy PNGs (see PNG_AS_JPEG_BYTES) already in a conversation (messages or content blocks) re-encoded in place:
|
|
207
|
+
// those from before images were, or from a tool that left them as they were. Nothing else in it changes. Returns
|
|
208
|
+
// how many changed. A few at a time, as each is a process; one that stays as it is (nothing here can re-encode
|
|
209
|
+
// it, or the JPEG is not smaller) is remembered, so that it is not tried again before every request.
|
|
210
|
+
const keptAsPng = new Set(); // sha1 of the base64 data
|
|
211
|
+
export async function lightenImagesIn(blocks) {
|
|
212
|
+
const heavy = [];
|
|
213
|
+
const visit = (list) => {
|
|
214
|
+
if (!Array.isArray(list)) return;
|
|
215
|
+
for (const b of list) {
|
|
216
|
+
if (!b || typeof b !== 'object') continue;
|
|
217
|
+
if (Array.isArray(b.content)) visit(b.content); // a message, or a tool_result
|
|
218
|
+
else if (b.type === 'image' && b.source?.type === 'base64' && b.source.media_type === 'image/png' && typeof b.source.data === 'string'
|
|
219
|
+
&& b.source.data.length * 0.75 > PNG_AS_JPEG_BYTES) heavy.push(b);
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
visit(blocks);
|
|
223
|
+
let changed = 0;
|
|
224
|
+
const lighten = async (b) => {
|
|
225
|
+
const key = crypto.createHash('sha1').update(b.source.data).digest('base64');
|
|
226
|
+
if (keptAsPng.has(key)) return;
|
|
227
|
+
const fit = await fitImage(b.source);
|
|
228
|
+
if (fit.error || !fit.changed) {
|
|
229
|
+
if (keptAsPng.size >= 1000) keptAsPng.clear();
|
|
230
|
+
keptAsPng.add(key);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
b.source = { type: 'base64', media_type: fit.media_type, data: fit.data };
|
|
234
|
+
changed++;
|
|
235
|
+
};
|
|
236
|
+
for (let i = 0; i < heavy.length; i += 4) await Promise.all(heavy.slice(i, i + 4).map(lighten));
|
|
237
|
+
return changed;
|
|
238
|
+
}
|