@yanzc/claude-pro 0.7.2 → 0.7.3
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 +13 -1
- 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/peers.js +3 -6
- package/src/print.js +1 -1
- package/src/ratelimit.js +6 -19
- package/src/remote.js +6 -40
- package/src/runtime.js +4 -2
- package/src/tools/peers.js +5 -9
- package/src/ui/repl.js +24 -204
- 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/config.js
CHANGED
|
@@ -15,7 +15,6 @@ import path from 'node:path';
|
|
|
15
15
|
import os from 'node:os';
|
|
16
16
|
import { fileURLToPath } from 'node:url';
|
|
17
17
|
import { normalizeTtl } from './cache.js';
|
|
18
|
-
import { codexModels, codexConfigDefaults } from './codex/client.js';
|
|
19
18
|
|
|
20
19
|
export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
21
20
|
// A source checkout (a git clone, also when npm links to one), as opposed to a copy installed from npm: the agent
|
|
@@ -23,48 +22,29 @@ export const INSTALL_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.u
|
|
|
23
22
|
export const SOURCE_CHECKOUT = fs.existsSync(path.join(INSTALL_DIR, '.git'));
|
|
24
23
|
export const CONFIG_DIR = process.env.CLAUDE_PRO_CONFIG_DIR || path.join(os.homedir(), '.claude-pro');
|
|
25
24
|
export const APP_NAME = 'claude-pro';
|
|
26
|
-
export const PROVIDERS = ['
|
|
25
|
+
export const PROVIDERS = ['gateway'];
|
|
27
26
|
export const GATEWAY_DEFAULT_URL = 'https://gw.predix.icu';
|
|
28
|
-
// The codex provider's model when neither CLAUDE_PRO_CODEX_MODEL nor the Codex config.toml names one.
|
|
29
|
-
export const CODEX_DEFAULT_MODEL = 'gpt-6.1-sol';
|
|
30
27
|
export const VERSION = JSON.parse(fs.readFileSync(path.join(INSTALL_DIR, 'package.json'), 'utf8')).version;
|
|
31
28
|
|
|
32
29
|
// Every key we understand, with a short description (shown by /config).
|
|
33
30
|
export const KNOWN_KEYS = {
|
|
34
|
-
CLAUDE_PRO_PROVIDER: 'Authentication backend: gateway
|
|
35
|
-
CLAUDE_PRO_GATEWAY_URL: `codex-gateway address
|
|
31
|
+
CLAUDE_PRO_PROVIDER: 'Authentication backend: gateway only (codex-gateway account, /login)',
|
|
32
|
+
CLAUDE_PRO_GATEWAY_URL: `codex-gateway address (default https://gw.predix.icu)`,
|
|
33
|
+
CLAUDE_PRO_GATEWAY_API_KEY: 'Gateway API key (normally saved by /login in gateway.json)',
|
|
36
34
|
CLAUDE_PRO_GATEWAY_MODEL: 'Model with the gateway provider (default: opus; also sonnet, haiku, gpt-6.1-sol)',
|
|
37
|
-
CLAUDE_PRO_CODEX_MODEL: 'Model with the codex provider (default: the model in ~/.codex/config.toml, else gpt-6.1-sol)',
|
|
38
|
-
CLAUDE_PRO_CLAUDE_CONFIG_FILE: 'Claude subscription: the account metadata file of the claude command (default: ~/.claude.json)',
|
|
39
|
-
CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE: 'Claude subscription: the credentials file of the claude command (default: ~/.claude/.credentials.json)',
|
|
40
|
-
CLAUDE_PRO_CLAUDE_CODE_VERSION: 'Claude subscription: the claude command version sent in the User-Agent (default: the installed one)',
|
|
41
|
-
CLAUDE_PRO_DISABLE_TOKEN_REFRESH: 'Set to 1 to stop this program renewing the Claude subscription login by itself (it then only reads what the official client keeps up to date)',
|
|
42
35
|
CLAUDE_PRO_ONLINE: 'Internal (the self-check and the tests set it): 0 keeps interactive sessions off the gateway. Otherwise a session is online there whenever this computer is logged in to the gateway: its 远程控制 page shows it, and sessions on your other computers can send it tasks (&computer/name)',
|
|
43
36
|
CLAUDE_PRO_HOST: 'Set to 0 so that sessions do not start the computer service (claude-pro host) by themselves; the service lets the gateway\'s 远程控制 page open new sessions on this computer',
|
|
44
|
-
CLAUDE_PRO_DOWNLOAD_DIR: 'Where files that other sessions send this one are saved (default: the Downloads folder)',
|
|
45
37
|
CLAUDE_PRO_MACHINE_NAME: 'This computer\'s name for sessions on your other computers (@公司 ...; default: the host name)',
|
|
46
38
|
CLAUDE_PRO_TUI: 'fullscreen (default: the input box fixed at the bottom, the conversation scrolled inside) or default (classic: it scrolls in the terminal); /tui switches',
|
|
47
39
|
CLAUDE_PRO_AUTO_RESTART: 'Restart by itself when a turn ends and claude-pro\'s own source files changed (default 1; 0 = only on /restart or the Restart tool)',
|
|
48
|
-
|
|
49
|
-
CLAUDE_CONFIG_DIR: 'Configuration directory of the claude command, for selecting its signed-in account (Claude subscription)',
|
|
50
|
-
ANTHROPIC_BASE_URL: 'API base URL (Anthropic compatible endpoint)',
|
|
51
|
-
ANTHROPIC_AUTH_TOKEN: 'Bearer token sent as Authorization header',
|
|
52
|
-
ANTHROPIC_API_KEY: 'API key sent as x-api-key header (used if no auth token)',
|
|
53
|
-
ANTHROPIC_CUSTOM_HEADERS: 'Extra headers, "Name: Value" separated by newlines',
|
|
54
|
-
ANTHROPIC_MODEL: 'Main model (name or alias opus/sonnet/haiku; suffix [1m] = 1M context)',
|
|
55
|
-
ANTHROPIC_DEFAULT_OPUS_MODEL: 'Model used for the "opus" alias',
|
|
56
|
-
ANTHROPIC_DEFAULT_SONNET_MODEL: 'Model used for the "sonnet" alias',
|
|
57
|
-
ANTHROPIC_DEFAULT_HAIKU_MODEL: 'Small/fast model (web page summarising, titles)',
|
|
58
|
-
ANTHROPIC_SMALL_FAST_MODEL: 'Deprecated alias of ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
|
59
|
-
CLAUDE_CODE_SUBAGENT_MODEL: 'Model used by Task sub-agents (API providers; default: the main model)',
|
|
60
|
-
CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL: 'Model used by Task sub-agents with the claude-code provider (default: sonnet)',
|
|
40
|
+
|
|
61
41
|
CLAUDE_CODE_EFFORT_LEVEL: 'Reasoning effort: none|minimal|low|medium|high|xhigh|max (sent as output_config.effort)',
|
|
62
42
|
CLAUDE_CODE_AUTO_COMPACT_WINDOW: 'Context size (tokens) used for auto-compaction calculations',
|
|
63
43
|
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE: 'Percentage (1-100) of the window at which auto-compaction triggers',
|
|
64
44
|
DISABLE_AUTOCOMPACT: 'Set to 1 to disable auto-compaction',
|
|
65
|
-
CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default
|
|
45
|
+
CLAUDE_CODE_MAX_OUTPUT_TOKENS: 'max_tokens for each model response (default 48000; lowered automatically if the gateway allows less)',
|
|
66
46
|
MAX_THINKING_TOKENS: 'Thinking budget: 0 disables thinking, N enables with budget N',
|
|
67
|
-
CLAUDE_CODE_PROMPT_CACHE_TTL: 'Prompt cache TTL of the conversation itself: 5m or 1h (default: 1h with the
|
|
47
|
+
CLAUDE_CODE_PROMPT_CACHE_TTL: 'Prompt cache TTL of the conversation itself: 5m or 1h (default: 1h with the gateway; 1h writes cost more, they pay off when you pause for more than 5 minutes). Also the promptCacheTtl setting',
|
|
68
48
|
CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: 'Prompt cache TTL of everything else (sub-agents, compaction, side queries): 5m (default) or 1h. Also the subagentPromptCacheTtl setting',
|
|
69
49
|
ENABLE_PROMPT_CACHING_1H: 'Set to 1 to request the 1-hour TTL for both (the two TTL variables above win over it)',
|
|
70
50
|
FORCE_PROMPT_CACHING_5M: 'Set to 1 to force the 5-minute TTL for both, over every other TTL setting',
|
|
@@ -89,7 +69,7 @@ export const KNOWN_KEYS = {
|
|
|
89
69
|
CLAUDE_PRO_DISABLE_TOPIC_TITLE: 'Set to 1 to stop asking the small model for the current topic after each message (the tab title then shows the first message of the session)',
|
|
90
70
|
};
|
|
91
71
|
|
|
92
|
-
const SECRET_KEYS = new Set(['
|
|
72
|
+
const SECRET_KEYS = new Set(['CLAUDE_PRO_GATEWAY_API_KEY']);
|
|
93
73
|
|
|
94
74
|
export function parseDotEnv(text) {
|
|
95
75
|
const env = {};
|
|
@@ -129,15 +109,7 @@ export function settingsFiles(cwd) {
|
|
|
129
109
|
};
|
|
130
110
|
}
|
|
131
111
|
|
|
132
|
-
|
|
133
|
-
// models, and how hard and how long that model works. The subscription provider (claude-code) does not take that
|
|
134
|
-
// tuning over: it starts from Claude Code's own defaults (the model's default effort, the model's whole context
|
|
135
|
-
// window), which is what makes it work without any setting. The same keys in a settings file, in the shell, as a
|
|
136
|
-
// flag, or chosen with /effort do apply there.
|
|
137
|
-
export const API_ONLY_DOTENV_KEYS = ['CLAUDE_CODE_EFFORT_LEVEL', 'CLAUDE_CODE_AUTO_COMPACT_WINDOW', 'CLAUDE_AUTOCOMPACT_PCT_OVERRIDE', 'CLAUDE_CODE_MAX_OUTPUT_TOKENS', 'MAX_THINKING_TOKENS'];
|
|
138
|
-
|
|
139
|
-
// The variable that holds the model, per provider.
|
|
140
|
-
const MODEL_KEYS = { api: 'ANTHROPIC_MODEL', 'claude-code': 'CLAUDE_PRO_CLAUDE_CODE_MODEL', gateway: 'CLAUDE_PRO_GATEWAY_MODEL', codex: 'CLAUDE_PRO_CODEX_MODEL' };
|
|
112
|
+
const MODEL_KEYS = { gateway: 'CLAUDE_PRO_GATEWAY_MODEL' };
|
|
141
113
|
|
|
142
114
|
export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.join(INSTALL_DIR, '.env') } = {}) {
|
|
143
115
|
const env = {};
|
|
@@ -167,7 +139,7 @@ export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.
|
|
|
167
139
|
for (const [event, entries] of Object.entries(json.hooks || {})) {
|
|
168
140
|
if (Array.isArray(entries)) (settings.hooks[event] ||= []).push(...entries);
|
|
169
141
|
}
|
|
170
|
-
if (json.model) { env.
|
|
142
|
+
if (json.model) { env.CLAUDE_PRO_GATEWAY_MODEL = json.model; sources.CLAUDE_PRO_GATEWAY_MODEL = `${file} (model)`; }
|
|
171
143
|
settings[scope] = json;
|
|
172
144
|
}
|
|
173
145
|
// Project level .mcp.json, same format as Claude Code.
|
|
@@ -180,24 +152,13 @@ export function loadConfig({ cwd = process.cwd(), flags = {}, dotEnvFile = path.
|
|
|
180
152
|
|
|
181
153
|
if (flags.provider) { env.CLAUDE_PRO_PROVIDER = flags.provider; sources.CLAUDE_PRO_PROVIDER = '--provider flag'; }
|
|
182
154
|
if (flags.model) {
|
|
183
|
-
const key = MODEL_KEYS[(env.CLAUDE_PRO_PROVIDER || '').trim().toLowerCase()] || '
|
|
155
|
+
const key = MODEL_KEYS[(env.CLAUDE_PRO_PROVIDER || 'gateway').trim().toLowerCase()] || 'CLAUDE_PRO_GATEWAY_MODEL';
|
|
184
156
|
env[key] = flags.model;
|
|
185
157
|
sources[key] = '--model flag';
|
|
186
158
|
}
|
|
187
159
|
if (flags.effort) { env.CLAUDE_CODE_EFFORT_LEVEL = flags.effort; sources.CLAUDE_CODE_EFFORT_LEVEL = '--effort flag'; }
|
|
188
160
|
|
|
189
|
-
|
|
190
|
-
if (!['', 'api'].includes((env.CLAUDE_PRO_PROVIDER || '').trim().toLowerCase())) {
|
|
191
|
-
for (const key of API_ONLY_DOTENV_KEYS) {
|
|
192
|
-
if (sources[key] !== dotEnvFile) continue;
|
|
193
|
-
delete env[key];
|
|
194
|
-
delete sources[key];
|
|
195
|
-
ignoredFromDotEnv.push(key);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
const config = new Config(env, sources, settings, cwd);
|
|
199
|
-
config.ignoredFromDotEnv = ignoredFromDotEnv; // shown by /config
|
|
200
|
-
return config;
|
|
161
|
+
return new Config(env, sources, settings, cwd);
|
|
201
162
|
}
|
|
202
163
|
|
|
203
164
|
const int = (v, d) => {
|
|
@@ -217,64 +178,19 @@ export class Config {
|
|
|
217
178
|
this.effortBoost = null; // set by the model with the Effort tool, for the rest of the user's current request
|
|
218
179
|
this.effortBoostKeepNext = false; // a restart continues the request: the next turn keeps the boost
|
|
219
180
|
this.verifyOverride = null; // set by /verify or --verify during a session
|
|
220
|
-
this.ignoredFromDotEnv = []; // .env keys that are not applied because of the provider (see API_ONLY_DOTENV_KEYS)
|
|
221
181
|
}
|
|
222
182
|
|
|
223
|
-
// Not set: an API endpoint, key or model that is configured (.env, settings) means the api provider, as before;
|
|
224
|
-
// otherwise the gateway, where /login gets an account in the browser.
|
|
225
183
|
get provider() {
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
return value;
|
|
184
|
+
const value = (this.env.CLAUDE_PRO_PROVIDER || 'gateway').trim().toLowerCase();
|
|
185
|
+
if (value !== 'gateway') throw new Error(`Only the gateway provider is supported. Set CLAUDE_PRO_PROVIDER=gateway (received ${value}).`);
|
|
186
|
+
return 'gateway';
|
|
230
187
|
}
|
|
231
|
-
get
|
|
232
|
-
get usesGateway() { return this.provider === 'gateway'; }
|
|
233
|
-
get usesCodex() { return this.provider === 'codex'; }
|
|
188
|
+
get usesGateway() { return true; }
|
|
234
189
|
get gatewayUrl() { return (this.env.CLAUDE_PRO_GATEWAY_URL || GATEWAY_DEFAULT_URL).trim().replace(/\/+$/, ''); }
|
|
235
|
-
|
|
236
|
-
// Claude through a subscription login too).
|
|
237
|
-
get claudeIds() { return this.usesClaudeCode || this.usesGateway; }
|
|
238
|
-
get claudeCodeConfigFile() { return path.resolve(this.cwd, this.env.CLAUDE_PRO_CLAUDE_CONFIG_FILE || path.join(os.homedir(), '.claude.json')); }
|
|
239
|
-
get claudeCodeCredentialsFile() {
|
|
240
|
-
return path.resolve(this.cwd, this.env.CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE || path.join(
|
|
241
|
-
this.env.CLAUDE_CONFIG_DIR || path.join(path.dirname(this.claudeCodeConfigFile), '.claude'), '.credentials.json'));
|
|
242
|
-
}
|
|
243
|
-
get endpointLabel() {
|
|
244
|
-
if (this.usesClaudeCode) return 'https://api.anthropic.com (Claude subscription)';
|
|
245
|
-
if (this.usesGateway) return `${this.gatewayUrl} (codex-gateway)`;
|
|
246
|
-
if (this.usesCodex) return 'https://chatgpt.com/backend-api/codex (Codex login)';
|
|
247
|
-
return this.baseURL;
|
|
248
|
-
}
|
|
249
|
-
get baseURL() { return this.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com'; }
|
|
250
|
-
get authToken() { return this.env.ANTHROPIC_AUTH_TOKEN || null; }
|
|
251
|
-
get apiKey() { return this.env.ANTHROPIC_API_KEY || null; }
|
|
252
|
-
get customHeaders() {
|
|
253
|
-
const headers = {};
|
|
254
|
-
for (const line of (this.env.ANTHROPIC_CUSTOM_HEADERS || '').split(/\n/)) {
|
|
255
|
-
const i = line.indexOf(':');
|
|
256
|
-
if (i > 0) headers[line.slice(0, i).trim()] = line.slice(i + 1).trim();
|
|
257
|
-
}
|
|
258
|
-
return headers;
|
|
259
|
-
}
|
|
190
|
+
get endpointLabel() { return `${this.gatewayUrl} (codex-gateway)`; }
|
|
260
191
|
|
|
261
192
|
aliasTarget(alias) {
|
|
262
|
-
|
|
263
|
-
return { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' }[alias] || null;
|
|
264
|
-
}
|
|
265
|
-
// The gateway prices models by their undated names.
|
|
266
|
-
if (this.usesGateway) return { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' }[alias] || null;
|
|
267
|
-
if (this.usesCodex) {
|
|
268
|
-
// No Claude here: the big aliases mean the Codex model, haiku the small one when the Codex install has it.
|
|
269
|
-
if (alias === 'haiku') return codexModels(this.env).models.some((m) => m.slug === 'gpt-6-luna') ? 'gpt-6-luna' : this.codexModelSpec;
|
|
270
|
-
return alias === 'opus' || alias === 'sonnet' ? this.codexModelSpec : null;
|
|
271
|
-
}
|
|
272
|
-
switch (alias) {
|
|
273
|
-
case 'opus': return this.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'claude-opus-4-5';
|
|
274
|
-
case 'sonnet': return this.env.ANTHROPIC_DEFAULT_SONNET_MODEL || 'claude-sonnet-4-5';
|
|
275
|
-
case 'haiku': return this.env.ANTHROPIC_DEFAULT_HAIKU_MODEL || this.env.ANTHROPIC_SMALL_FAST_MODEL || 'claude-haiku-4-5';
|
|
276
|
-
default: return null;
|
|
277
|
-
}
|
|
193
|
+
return { opus: 'claude-opus-5-5', sonnet: 'claude-sonnet-5-5', haiku: 'claude-haiku-5-5' }[alias] || null;
|
|
278
194
|
}
|
|
279
195
|
|
|
280
196
|
// Resolve a model spec (alias or name, maybe with [1m]) to {id, contextWindow, label}.
|
|
@@ -287,36 +203,18 @@ export class Config {
|
|
|
287
203
|
const inner = this.resolveModel(aliased);
|
|
288
204
|
return { ...inner, contextWindow: oneM ? 1_000_000 : inner.contextWindow, label: `${name}${oneM ? '[1m]' : ''} (${inner.label})` };
|
|
289
205
|
}
|
|
290
|
-
const nativeOneM =
|
|
291
|
-
//
|
|
292
|
-
|
|
293
|
-
if (/^gpt-/i.test(name)) {
|
|
294
|
-
const known = codexModels(this.env).models.find((m) => m.slug === name)?.contextWindow;
|
|
295
|
-
return { id: name, contextWindow: known || 272_000, label: name };
|
|
296
|
-
}
|
|
206
|
+
const nativeOneM = /^claude-(?:(?:sonnet|haiku)-5(?:-|$)|opus-(?:5(?:-|$)|4-[78](?:-|$)))/i.test(name);
|
|
207
|
+
// GPT models are served by the gateway's Codex backend and use its standard context window.
|
|
208
|
+
if (/^gpt-/i.test(name)) return { id: name, contextWindow: 272_000, label: name };
|
|
297
209
|
return { id: name, contextWindow: oneM || nativeOneM ? 1_000_000 : 200_000, label: `${name}${oneM ? '[1m]' : ''}` };
|
|
298
210
|
}
|
|
299
211
|
|
|
300
|
-
// The model the
|
|
301
|
-
get configuredModelSpec() {
|
|
302
|
-
if (this.usesGateway) return this.env.CLAUDE_PRO_GATEWAY_MODEL || 'opus';
|
|
303
|
-
if (this.usesCodex) return this.codexModelSpec;
|
|
304
|
-
return (this.usesClaudeCode ? this.env.CLAUDE_PRO_CLAUDE_CODE_MODEL : this.env.ANTHROPIC_MODEL) || 'sonnet';
|
|
305
|
-
}
|
|
306
|
-
get codexModelSpec() { return this.env.CLAUDE_PRO_CODEX_MODEL || codexConfigDefaults(this.env).model || CODEX_DEFAULT_MODEL; }
|
|
212
|
+
// The model the gateway is configured with, before any /model override.
|
|
213
|
+
get configuredModelSpec() { return this.env.CLAUDE_PRO_GATEWAY_MODEL || 'opus'; }
|
|
307
214
|
get mainModelSpec() { return this.modelOverride || this.configuredModelSpec; }
|
|
308
215
|
get mainModel() { return this.resolveModel(this.mainModelSpec); }
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
// well-specified subtasks they are given. CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL (or a sub-agent's own model) changes it.
|
|
312
|
-
if (this.usesClaudeCode) return this.resolveModel(this.env.CLAUDE_PRO_CLAUDE_CODE_SUBAGENT_MODEL || 'sonnet');
|
|
313
|
-
// The gateway: no fixed sub-agent model. Under a Claude main model the main agent picks one for each Task by how
|
|
314
|
-
// hard the task is (see subagentModelChosen and the Task tool's description); this is what an agent runs on when
|
|
315
|
-
// it was not given one: the main model. A GPT main model keeps its own.
|
|
316
|
-
if (this.usesGateway) return this.mainModel;
|
|
317
|
-
if (this.usesCodex) return this.mainModel;
|
|
318
|
-
return this.env.CLAUDE_CODE_SUBAGENT_MODEL ? this.resolveModel(this.env.CLAUDE_CODE_SUBAGENT_MODEL) : this.mainModel;
|
|
319
|
-
}
|
|
216
|
+
// The gateway lets the main agent choose Claude sub-agent models by task difficulty.
|
|
217
|
+
get subagentModel() { return this.mainModel; }
|
|
320
218
|
// The main agent chooses each sub-agent's model (haiku, sonnet, opus) by the task, rather than one being set.
|
|
321
219
|
get subagentModelChosen() { return this.usesGateway && /^claude-/i.test(this.mainModel.id); }
|
|
322
220
|
get smallModel() { return this.resolveModel('haiku'); }
|
|
@@ -331,15 +229,14 @@ export class Config {
|
|
|
331
229
|
// The gateway holds back balance for max_tokens of output before each request, so a smaller default there keeps a
|
|
332
230
|
// modest balance usable. 48K: in 812 Opus requests through it (2026-10-12) p99 was 14K, three went over 24K (the
|
|
333
231
|
// longest that finished: 27K) and one was cut off at the old 32K; the hold is $0.96 on Opus instead of $0.64.
|
|
334
|
-
get maxOutputTokens() { return int(this.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS,
|
|
232
|
+
get maxOutputTokens() { return int(this.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS, 48_000); }
|
|
335
233
|
get thinkingBudget() {
|
|
336
234
|
return this.env.MAX_THINKING_TOKENS === undefined ? null : int(this.env.MAX_THINKING_TOKENS, null);
|
|
337
235
|
}
|
|
338
236
|
// Prompt cache TTL for a request bucket, by Claude Code's rules: "main" is the conversation itself, "other"
|
|
339
237
|
// is everything else (sub-agents, compaction, side queries). In order: FORCE_PROMPT_CACHING_5M; the bucket's
|
|
340
|
-
// own variable or setting; ENABLE_PROMPT_CACHING_1H; then the default:
|
|
341
|
-
//
|
|
342
|
-
// usage); with an API key or another endpoint, and for everything else, 5 minutes.
|
|
238
|
+
// own variable or setting; ENABLE_PROMPT_CACHING_1H; then the gateway default: the conversation's own
|
|
239
|
+
// requests use 1 hour and everything else uses 5 minutes.
|
|
343
240
|
cacheTtl(bucket = 'main') {
|
|
344
241
|
if (isOn(this.env.FORCE_PROMPT_CACHING_5M)) return '5m';
|
|
345
242
|
// an invalid value is ignored, and the next rule applies (as in Claude Code)
|
|
@@ -350,7 +247,7 @@ export class Config {
|
|
|
350
247
|
if (isOn(this.env.ENABLE_PROMPT_CACHING_1H)) return '1h';
|
|
351
248
|
// The gateway too: measured on its usage records (533 Opus requests), pauses of 5 to 60 minutes rewrote the whole
|
|
352
249
|
// conversation 9 times at 1.25x, $14.77; writing every turn at 2x instead costs $2.80 more.
|
|
353
|
-
return bucket === 'main' &&
|
|
250
|
+
return bucket === 'main' && this.usesGateway ? '1h' : '5m';
|
|
354
251
|
}
|
|
355
252
|
// DISABLE_PROMPT_CACHING turns it off for everything; the per-model variables only for the model that
|
|
356
253
|
// their alias resolves to (a different version pinned as the model keeps its caching), wherever it runs.
|
|
@@ -394,11 +291,9 @@ export class Config {
|
|
|
394
291
|
get bashMaxOutput() { return int(this.env.BASH_MAX_OUTPUT_LENGTH, 60_000); }
|
|
395
292
|
// Tool results longer than this are saved to a file and only a preview is sent.
|
|
396
293
|
get maxToolResultChars() { return 100_000; }
|
|
397
|
-
// Clearing old tool results after a long pause (see Agent.clearAfterIdle):
|
|
398
|
-
//
|
|
399
|
-
get clearAfterIdle() {
|
|
400
|
-
return this.usesClaudeCode || this.usesGateway || /^https:\/\/api\.anthropic\.com\/?$/i.test(this.baseURL);
|
|
401
|
-
}
|
|
294
|
+
// Clearing old tool results after a long pause (see Agent.clearAfterIdle): the gateway prompt cache has
|
|
295
|
+
// expired by then, so retaining old tool payloads would only make the next request larger.
|
|
296
|
+
get clearAfterIdle() { return true; }
|
|
402
297
|
// How deep sub-agents may nest: the main agent is depth 0; an agent below this depth gets the Task tool.
|
|
403
298
|
get maxSubagentDepth() { return 2; }
|
|
404
299
|
|
package/src/gateway.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The codex-gateway provider: model requests go to a shared gateway (https://gw.predix.icu by default) with an
|
|
2
|
-
// API key of the user's gateway account, which pays for them from its balance. /login
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// API key of the user's gateway account, which pays for them from its balance. /login starts a local callback
|
|
3
|
+
// server, opens the gateway login page in the browser, and exchanges a one-time code for a key belonging to this machine
|
|
4
|
+
// (see handleCli in codex-gateway's server.mjs).
|
|
5
5
|
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import fs from 'node:fs';
|
|
@@ -28,6 +28,12 @@ export function readGatewayLogin(url) {
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
// A key supplied for a headless run is equivalent to a saved login for model and remote requests.
|
|
32
|
+
// It has no account metadata, so the UI uses a neutral account label.
|
|
33
|
+
export function gatewayLogin(url, apiKey = process.env.CLAUDE_PRO_GATEWAY_API_KEY) {
|
|
34
|
+
return readGatewayLogin(url) || (apiKey ? { url: normalizeGatewayUrl(url), apiKey, account: {} } : null);
|
|
35
|
+
}
|
|
36
|
+
|
|
31
37
|
export function saveGatewayLogin(login) {
|
|
32
38
|
const file = gatewayLoginFile();
|
|
33
39
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
package/src/host.js
CHANGED
|
@@ -27,7 +27,7 @@ import path from 'node:path';
|
|
|
27
27
|
import crypto from 'node:crypto';
|
|
28
28
|
import { spawn, spawnSync } from 'node:child_process';
|
|
29
29
|
import { CONFIG_DIR, INSTALL_DIR, VERSION, GATEWAY_DEFAULT_URL, loadConfig } from './config.js';
|
|
30
|
-
import {
|
|
30
|
+
import { gatewayLogin, normalizeGatewayUrl } from './gateway.js';
|
|
31
31
|
import { machineName, cleanName, listPeers } from './peers.js';
|
|
32
32
|
import { BackgroundSessions, markEnded, tailFile } from './background.js';
|
|
33
33
|
import { listConversations, deleteConversation, CONVERSATION_ID } from './history.js';
|
|
@@ -411,7 +411,7 @@ const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
|
411
411
|
// The settings of this service's environment that a session it opens needs too (the config directory, the
|
|
412
412
|
// gateway's address, the computer's name ...): Windows Terminal starts the program with its own environment, and
|
|
413
413
|
// tmux and a desktop's terminal with theirs. Not the secrets: those stay where they were set.
|
|
414
|
-
const PASS_ENV = /^(CLAUDE_PRO_|
|
|
414
|
+
const PASS_ENV = /^(CLAUDE_PRO_|CLAUDE_CODE_)/;
|
|
415
415
|
const SECRET = /TOKEN|KEY|SECRET|PASSWORD|HEADERS/i;
|
|
416
416
|
export function passedEnv(env = process.env) {
|
|
417
417
|
const out = {};
|
|
@@ -527,7 +527,10 @@ export class HostService {
|
|
|
527
527
|
this.launch = launch;
|
|
528
528
|
this.home = home;
|
|
529
529
|
this.loadConfig = load || (() => loadConfig({ cwd: home }));
|
|
530
|
-
this.readLogin = readLogin || (() =>
|
|
530
|
+
this.readLogin = readLogin || (() => {
|
|
531
|
+
const cfg = this.cfg();
|
|
532
|
+
return gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
533
|
+
});
|
|
531
534
|
this.config = null;
|
|
532
535
|
this.configAt = 0;
|
|
533
536
|
this.login = null; // {url, apiKey, account} of gateway.json
|
|
@@ -1119,7 +1122,7 @@ export async function runHost({ background = false } = {}) {
|
|
|
1119
1122
|
|
|
1120
1123
|
async function gatewayRequest(method, route) {
|
|
1121
1124
|
const cfg = loadConfig({ cwd: os.homedir() });
|
|
1122
|
-
const login =
|
|
1125
|
+
const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
1123
1126
|
if (!login) return false;
|
|
1124
1127
|
const res = await fetch(`${normalizeGatewayUrl(login.url || cfg.gatewayUrl)}${route}`, { method, headers: { authorization: `Bearer ${login.apiKey}` }, signal: AbortSignal.timeout(8000) });
|
|
1125
1128
|
return res.ok || res.status === 404;
|
|
@@ -1138,7 +1141,7 @@ async function startCommand() {
|
|
|
1138
1141
|
const now = readHostState();
|
|
1139
1142
|
if (hostRunning(now)) {
|
|
1140
1143
|
const cfg = loadConfig({ cwd: os.homedir() });
|
|
1141
|
-
const login =
|
|
1144
|
+
const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
|
|
1142
1145
|
console.log(`claude-pro host started in the background (pid ${now.pid}). Log: ${hostFiles().log}`);
|
|
1143
1146
|
if (!login) console.log(`This computer is not logged in to the gateway ${cfg.gatewayUrl}: it waits until /login in a session.`);
|
|
1144
1147
|
return 0;
|
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/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/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, 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 || '';
|