@yanzc/claude-pro 0.9.8 → 0.11.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.
@@ -0,0 +1,331 @@
1
+ // Model providers besides the gateway, connected with /connect: built-in ones (DeepSeek, OpenAI, Kimi, ...) and the
2
+ // user's own endpoints. Several can be connected at once. A model of one is named provider/model
3
+ // (deepseek/deepseek-v4-pro); a name without a known provider in front is the gateway's, as before, so the remembered
4
+ // /model choices and the model setting (opus) mean what they did.
5
+ //
6
+ // A provider speaks one of two protocols: anthropic (the Messages API, which the SDK sends as it is) or openai (Chat
7
+ // Completions, which openai-chat.js translates to and from). A provider that offers both is given its Anthropic
8
+ // endpoint: thinking, tool calls and images go through without translation.
9
+ //
10
+ // The connections (key, address, the models the provider listed, with their windows and prices where models.dev knows
11
+ // them) are kept in providers.json in the config directory, readable by the user alone, as the gateway's key is in
12
+ // gateway.json. (No import of config.js, which reads this module: the config directory is found here as there.)
13
+
14
+ import fs from 'node:fs';
15
+ import os from 'node:os';
16
+ import path from 'node:path';
17
+
18
+ export const GATEWAY_PROVIDER = '7bit';
19
+
20
+ // The built-in providers, in the order /connect lists them. All addresses answered 2026-11-19 (a wrong key: 401, 403,
21
+ // or 400 with "invalid key"). `modelsUrl`: an OpenAI-style list of models where the protocol's own has none (the
22
+ // Anthropic endpoints of DeepSeek, Kimi and GLM list nothing). `modelsDev`: the provider's id at models.dev, for the
23
+ // models' windows and prices.
24
+ export const PRESETS = [
25
+ { id: 'anthropic', name: 'Anthropic (Claude)', protocol: 'anthropic', baseUrl: 'https://api.anthropic.com', keyPage: 'https://console.anthropic.com/settings/keys', modelsDev: 'anthropic' },
26
+ { id: 'openai', name: 'OpenAI', protocol: 'openai', baseUrl: 'https://api.openai.com/v1', keyPage: 'https://platform.openai.com/api-keys', modelsDev: 'openai' },
27
+ { id: 'deepseek', name: 'DeepSeek', protocol: 'anthropic', baseUrl: 'https://api.deepseek.com/anthropic', modelsUrl: 'https://api.deepseek.com/models', keyPage: 'https://platform.deepseek.com/api_keys', modelsDev: 'deepseek' },
28
+ { id: 'kimi', name: 'Kimi (Moonshot)', protocol: 'anthropic', baseUrl: 'https://api.moonshot.cn/anthropic', modelsUrl: 'https://api.moonshot.cn/v1/models', keyPage: 'https://platform.moonshot.cn/console/api-keys', modelsDev: 'moonshotai-cn' },
29
+ { id: 'glm', name: 'GLM (Zhipu)', protocol: 'anthropic', baseUrl: 'https://open.bigmodel.cn/api/anthropic', modelsUrl: 'https://open.bigmodel.cn/api/paas/v4/models', keyPage: 'https://open.bigmodel.cn/usercenter/apikeys', modelsDev: 'zhipuai' },
30
+ { id: 'minimax', name: 'MiniMax', protocol: 'anthropic', baseUrl: 'https://api.minimaxi.com/anthropic', keyPage: 'https://platform.minimaxi.com', modelsDev: 'minimax-cn' },
31
+ { id: 'qwen', name: 'Qwen (Alibaba Bailian)', protocol: 'anthropic', baseUrl: 'https://dashscope.aliyuncs.com/apps/anthropic', modelsUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1/models', keyPage: 'https://bailian.console.aliyun.com', modelsDev: 'alibaba-cn' },
32
+ { id: 'openrouter', name: 'OpenRouter', protocol: 'openai', baseUrl: 'https://openrouter.ai/api/v1', keyPage: 'https://openrouter.ai/keys', modelsDev: 'openrouter' },
33
+ { id: 'siliconflow', name: 'SiliconFlow', protocol: 'openai', baseUrl: 'https://api.siliconflow.cn/v1', keyPage: 'https://cloud.siliconflow.cn/account/ak', modelsDev: 'siliconflow-cn' },
34
+ { id: 'volcengine', name: 'Volcengine Ark', protocol: 'openai', baseUrl: 'https://ark.cn-beijing.volces.com/api/v3', keyPage: 'https://console.volcengine.com/ark', modelsDev: 'volcengine' },
35
+ { id: 'gemini', name: 'Google Gemini', protocol: 'openai', baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai', keyPage: 'https://aistudio.google.com/apikey', modelsDev: 'google' },
36
+ { id: 'xai', name: 'xAI (Grok)', protocol: 'openai', baseUrl: 'https://api.x.ai/v1', keyPage: 'https://console.x.ai', modelsDev: 'xai' },
37
+ { id: 'ollama', name: 'Ollama (this computer)', protocol: 'openai', baseUrl: 'http://localhost:11434/v1', keyless: true },
38
+ ];
39
+ const PRESET_IDS = new Set(PRESETS.map((p) => p.id));
40
+
41
+ const configDir = () => process.env.CLAUDE_PRO_CONFIG_DIR || path.join(os.homedir(), '.claude-pro');
42
+ export const providersFile = () => path.join(configDir(), 'providers.json');
43
+
44
+ // The address requests are sent to: what users paste often ends in a path the client adds itself.
45
+ export function normalizeBaseUrl(url, protocol) {
46
+ const base = String(url || '').trim().replace(/\/+$/, '');
47
+ return protocol === 'openai' ? base.replace(/\/chat\/completions$/i, '') : base.replace(/\/v1(?:\/messages)?$/i, '').replace(/\/+$/, '');
48
+ }
49
+
50
+ export function validBaseUrl(url) {
51
+ try {
52
+ const u = new URL(url);
53
+ return (u.protocol === 'https:' || u.protocol === 'http:') && Boolean(u.host);
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+
59
+ // A name for a provider the user adds: what follows it in model names (myrelay/some-model), so letters, digits and -.
60
+ export const cleanProviderId = (name) => String(name || '').trim().toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 30);
61
+ export const reservedProviderId = (id) => id === GATEWAY_PROVIDER || PRESET_IDS.has(id);
62
+
63
+ // {id: connection}. A connection: {apiKey, authHeader, model?, models: [{id, name?, window?, maxOutput?, price?}],
64
+ // savedAt} (model: the one chosen at /connect), and for the user's own providers also {custom: true, name, protocol,
65
+ // baseUrl}. Read again at most once a second (the model is resolved at every frame of the footer), and at once after
66
+ // this process changed the file; another window's change is seen within the second. Not to be changed by callers.
67
+ const MEMO_MS = 1000;
68
+ let memo = null; // {at, data}
69
+ export function readConnections({ fresh = false } = {}) {
70
+ if (!fresh && memo && Date.now() - memo.at < MEMO_MS) return memo.data;
71
+ let data = {};
72
+ try {
73
+ const parsed = JSON.parse(fs.readFileSync(providersFile(), 'utf8').replace(/^\uFEFF/, ''));
74
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) data = parsed;
75
+ } catch { /* none yet, or unreadable */ }
76
+ memo = { at: Date.now(), data };
77
+ return data;
78
+ }
79
+
80
+ function writeConnections(all) {
81
+ const file = providersFile();
82
+ fs.mkdirSync(path.dirname(file), { recursive: true });
83
+ const tmp = `${file}.${process.pid}.tmp`;
84
+ memo = null;
85
+ fs.writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 0o600 });
86
+ fs.renameSync(tmp, file);
87
+ }
88
+
89
+ export function saveConnection(id, connection) {
90
+ const all = { ...readConnections({ fresh: true }) };
91
+ all[id] = { ...connection, savedAt: new Date().toISOString() };
92
+ writeConnections(all);
93
+ }
94
+
95
+ export function removeConnection(id) {
96
+ const all = { ...readConnections({ fresh: true }) };
97
+ if (!all[id]) return false;
98
+ delete all[id];
99
+ writeConnections(all);
100
+ return true;
101
+ }
102
+
103
+ // What is known of a provider: the built-in entry with its connection, or the user's own from its connection. null for
104
+ // neither.
105
+ export function providerInfo(id, connections = readConnections()) {
106
+ const connection = connections[id] || null;
107
+ const preset = PRESETS.find((p) => p.id === id);
108
+ if (preset) return { ...preset, connection };
109
+ if (connection?.custom && connection.baseUrl) {
110
+ return { id, name: connection.name || id, protocol: connection.protocol === 'openai' ? 'openai' : 'anthropic', baseUrl: connection.baseUrl, custom: true, connection };
111
+ }
112
+ return null;
113
+ }
114
+
115
+ // The providers that are connected now, in the order /connect lists them (the gateway is not among them: see
116
+ // gatewayLogin).
117
+ export function connectedProviders(connections = readConnections()) {
118
+ const rank = (id) => { const i = PRESETS.findIndex((p) => p.id === id); return i < 0 ? PRESETS.length : i; };
119
+ return Object.keys(connections).sort((a, b) => rank(a) - rank(b))
120
+ .map((id) => providerInfo(id, connections)).filter((p) => p?.connection && (p.connection.apiKey || p.keyless || p.custom));
121
+ }
122
+
123
+ // "deepseek/deepseek-v4-pro" -> {provider: 'deepseek', model: 'deepseek-v4-pro'}. The part before the first / is a
124
+ // provider only when it names one (built in, or added by the user): model names have slashes of their own
125
+ // (openrouter/anthropic/claude-sonnet-4.5; the gateway's deepseek-ai/DeepSeek-V3 is no provider's). Anything else is
126
+ // the gateway's: {provider: '7bit', model}.
127
+ export function splitModelRef(spec, connections = null) {
128
+ const name = String(spec || '').trim();
129
+ const slash = name.indexOf('/');
130
+ if (slash > 0) {
131
+ const prefix = name.slice(0, slash).toLowerCase();
132
+ const rest = name.slice(slash + 1);
133
+ if (rest && (prefix === GATEWAY_PROVIDER || PRESET_IDS.has(prefix) || (connections ?? readConnections())[prefix]?.custom)) return { provider: prefix, model: rest };
134
+ }
135
+ return { provider: GATEWAY_PROVIDER, model: name };
136
+ }
137
+
138
+ // What the provider listed for this model at /connect (its window, price), or null.
139
+ export function providerModel(providerId, modelId, connections = readConnections()) {
140
+ return connections[providerId]?.models?.find((m) => m.id === modelId) || null;
141
+ }
142
+
143
+ // Models whose provider's list gives no window or output limit (DeepSeek's GET /models has neither), by the id they go
144
+ // by at DeepSeek and at 7bit.fun alike: {window, maxOutput}, from DeepSeek's API documentation (as codex-gateway's
145
+ // deepseek-models.mjs has them, checked 2026-11-06: 1M in, at most 384K out). What a list gives wins over these.
146
+ const KNOWN_MODELS = new Map([
147
+ ...['deepseek-v4-pro', 'deepseek-flash', 'deepseek-v4-flash', 'deepseek-v4-flash-vision-exp', 'deepseek-v4.1-flash']
148
+ .map((id) => [id, { window: 1_000_000, maxOutput: 393_216 }]),
149
+ ]);
150
+ export const knownModel = (modelId) => KNOWN_MODELS.get(String(modelId || '').toLowerCase()) || null;
151
+
152
+ // Where a provider's requests go, for api.js: {provider, name, protocol, baseURL, key, bearer}. Throws when it is not
153
+ // connected.
154
+ export function providerEndpoint(id) {
155
+ const info = providerInfo(id);
156
+ if (!info) throw Object.assign(new Error(`There is no provider "${id}". /connect lists them.`), { status: 401, notConnected: true });
157
+ const c = info.connection;
158
+ if (!c || (!c.apiKey && !info.keyless)) throw Object.assign(new Error(`${info.name} is not connected. Run /connect ${id}.`), { status: 401, notConnected: true });
159
+ return {
160
+ provider: id,
161
+ name: info.name,
162
+ protocol: info.protocol,
163
+ baseURL: normalizeBaseUrl(c.baseUrl || info.baseUrl, info.protocol),
164
+ key: c.apiKey || 'none',
165
+ bearer: info.protocol === 'openai' || c.authHeader === 'bearer',
166
+ quirks: c.quirks && typeof c.quirks === 'object' ? c.quirks : {},
167
+ };
168
+ }
169
+
170
+ // ---------------------------------------------------------------- checking a key, listing models
171
+
172
+ const authHeaders = (key, kind) => (kind === 'bearer' ? { authorization: `Bearer ${key}` } : { 'x-api-key': key });
173
+ const limitSignal = (ms, signal) => (signal ? AbortSignal.any([AbortSignal.timeout(ms), signal]) : AbortSignal.timeout(ms));
174
+ // A refused key: 401 and 403, and the 400 Gemini and xAI answer a wrong key with.
175
+ const refusedKey = (status, text) => status === 401 || status === 403 || (status === 400 && /api[ _-]?key|token|auth/i.test(text));
176
+
177
+ async function errorText(res) {
178
+ const text = await res.text().catch(() => '');
179
+ try {
180
+ const body = JSON.parse(text);
181
+ const first = Array.isArray(body) ? body[0] : body;
182
+ return first?.error?.message || first?.message || (typeof first?.error === 'string' ? first.error : '') || text.slice(0, 300);
183
+ } catch {
184
+ return text.slice(0, 300);
185
+ }
186
+ }
187
+
188
+ const listOf = (body) => (Array.isArray(body?.data) ? body.data : Array.isArray(body?.models) ? body.models : [])
189
+ .map((m) => (typeof m === 'string' ? { id: m } : m))
190
+ .filter((m) => typeof m?.id === 'string' && m.id)
191
+ .map((m) => ({
192
+ id: m.id,
193
+ ...(typeof m.display_name === 'string' && m.display_name && m.display_name !== m.id ? { name: m.display_name } : {}),
194
+ ...(Number.isInteger(m.max_input_tokens) && m.max_input_tokens > 0 ? { window: m.max_input_tokens } : Number.isInteger(m.context_length) && m.context_length > 0 ? { window: m.context_length } : {}),
195
+ }));
196
+
197
+ // The models a provider lists, and the header its key goes in: {authHeader, models}. The protocol's own list first
198
+ // (GET /v1/models for anthropic, with x-api-key, then Bearer; GET /models for openai, with Bearer), then the
199
+ // provider's OpenAI-style list (modelsUrl). models is null when neither answers with one. Throws {status, refused} when
200
+ // the key is refused every way.
201
+ export async function listProviderModels({ protocol, baseUrl, modelsUrl, apiKey, keyless }, { fetchImpl = globalThis.fetch, timeoutMs = 15_000, signal, kinds } = {}) {
202
+ const key = apiKey || (keyless ? 'none' : '');
203
+ const base = normalizeBaseUrl(baseUrl, protocol);
204
+ const tries = protocol === 'openai'
205
+ ? [[`${base}/models`, 'bearer']]
206
+ : (kinds || ['x-api-key', 'bearer']).map((kind) => [`${base}/v1/models`, kind]);
207
+ if (modelsUrl) tries.push([modelsUrl, 'bearer']);
208
+ let refusal = null;
209
+ let authHeader = null;
210
+ for (const [url, kind] of tries) {
211
+ let res;
212
+ try {
213
+ res = await fetchImpl(url, { headers: { 'anthropic-version': '2023-06-01', ...authHeaders(key, kind) }, signal: limitSignal(timeoutMs, signal) });
214
+ } catch (e) {
215
+ if (signal?.aborted) throw e;
216
+ continue; // this list cannot be reached; another may be
217
+ }
218
+ if (res.ok) {
219
+ const body = await res.json().catch(() => null);
220
+ const models = body ? listOf(body) : [];
221
+ // (the modelsUrl list proves the key, not the header the Anthropic endpoint takes: that is left to testModel)
222
+ if (url !== modelsUrl) authHeader = kind;
223
+ if (models.length) return { authHeader, models };
224
+ continue;
225
+ }
226
+ const text = await errorText(res);
227
+ if (refusedKey(res.status, text)) refusal = { status: res.status, message: text };
228
+ }
229
+ if (refusal && !authHeader) throw Object.assign(new Error(`the key was refused (HTTP ${refusal.status})${refusal.message ? `: ${refusal.message}` : ''}`), { status: refusal.status, refused: true });
230
+ return { authHeader, models: null };
231
+ }
232
+
233
+ // One small request to `model`: that the provider speaks the protocol, takes the key and has the model (an endpoint
234
+ // that only lists models passes listProviderModels and fails here). Resolves with the header that worked and what the
235
+ // provider was found to want ({authHeader, quirks}: quirks.maxCompletionTokens, kept with the connection so that its
236
+ // requests do not learn it again from a refusal). Throws with the provider's own words.
237
+ export async function testProviderModel({ protocol, baseUrl, apiKey, keyless, authHeader = null, model }, { fetchImpl = globalThis.fetch, timeoutMs = 60_000, signal } = {}) {
238
+ const key = apiKey || (keyless ? 'none' : '');
239
+ const base = normalizeBaseUrl(baseUrl, protocol);
240
+ const openai = protocol === 'openai';
241
+ const kinds = openai ? ['bearer'] : authHeader ? [authHeader, ...['x-api-key', 'bearer'].filter((k) => k !== authHeader)] : ['x-api-key', 'bearer'];
242
+ let refusal = null;
243
+ for (const kind of kinds) {
244
+ for (const tokensField of openai ? ['max_tokens', 'max_completion_tokens'] : ['max_tokens']) {
245
+ const body = openai
246
+ ? { model, messages: [{ role: 'user', content: 'Reply with OK.' }], [tokensField]: 32 }
247
+ : { model, max_tokens: 32, messages: [{ role: 'user', content: 'Reply with OK.' }] };
248
+ const res = await fetchImpl(openai ? `${base}/chat/completions` : `${base}/v1/messages`, {
249
+ method: 'POST',
250
+ headers: { 'content-type': 'application/json', 'anthropic-version': '2023-06-01', ...authHeaders(key, kind) },
251
+ body: JSON.stringify(body),
252
+ signal: limitSignal(timeoutMs, signal),
253
+ });
254
+ if (res.ok) {
255
+ await res.body?.cancel?.().catch(() => {});
256
+ return { authHeader: kind, quirks: tokensField === 'max_completion_tokens' ? { maxCompletionTokens: true } : {} };
257
+ }
258
+ const text = await errorText(res);
259
+ // OpenAI's newer models take max_completion_tokens only: asked again with it
260
+ if (openai && res.status === 400 && /max_completion_tokens/i.test(text) && tokensField === 'max_tokens') continue;
261
+ if (refusedKey(res.status, text)) { refusal = { status: res.status, message: text }; break; }
262
+ const hint = res.status === 404 || res.status === 405 ? ` (the address has no ${openai ? 'POST /chat/completions' : 'POST /v1/messages'}: is it the right one, and the right protocol?)` : '';
263
+ throw Object.assign(new Error(`HTTP ${res.status}${text ? `: ${text}` : ''}${hint}`), { status: res.status });
264
+ }
265
+ }
266
+ throw Object.assign(new Error(`the key was refused (HTTP ${refusal.status})${refusal.message ? `: ${refusal.message}` : ''}`), { status: refusal.status, refused: true });
267
+ }
268
+
269
+ // ---------------------------------------------------------------- models.dev
270
+
271
+ // models.dev (anomalyco/models.dev, the catalogue OpenCode uses): each model's window, output limit and price, which
272
+ // providers' own lists mostly leave out. Fetched at /connect, kept a day in the config directory's cache (about 6 MB).
273
+ const MODELS_DEV_URL = 'https://models.dev/api.json';
274
+ const MODELS_DEV_MAX_AGE_MS = 24 * 3_600_000;
275
+ let modelsDevMemo = null;
276
+
277
+ export async function modelsDevCatalogue({ fetchImpl = globalThis.fetch, signal, timeoutMs = 20_000 } = {}) {
278
+ if (modelsDevMemo) return modelsDevMemo;
279
+ const file = path.join(configDir(), 'cache', 'models-dev.json');
280
+ try {
281
+ if (Date.now() - fs.statSync(file).mtimeMs < MODELS_DEV_MAX_AGE_MS) return (modelsDevMemo = JSON.parse(fs.readFileSync(file, 'utf8')));
282
+ } catch { /* not kept yet */ }
283
+ try {
284
+ const res = await fetchImpl(MODELS_DEV_URL, { signal: limitSignal(timeoutMs, signal) });
285
+ if (!res.ok) return null;
286
+ const data = await res.json();
287
+ try {
288
+ fs.mkdirSync(path.dirname(file), { recursive: true });
289
+ fs.writeFileSync(file, JSON.stringify(data));
290
+ } catch { /* kept in memory only */ }
291
+ return (modelsDevMemo = data);
292
+ } catch {
293
+ try { return (modelsDevMemo = JSON.parse(fs.readFileSync(file, 'utf8'))); } catch { return null; } // an older copy beats none
294
+ }
295
+ }
296
+
297
+ // models.dev's entry for a model as a connection keeps it: {id, name?, window?, maxOutput?, price?} (price per million
298
+ // tokens: input, output, cacheRead, cacheWrite).
299
+ function modelFromCatalogue(id, entry) {
300
+ const out = { id };
301
+ if (entry?.name && entry.name !== id) out.name = entry.name;
302
+ const window = Number(entry?.limit?.input || entry?.limit?.context);
303
+ if (Number.isInteger(window) && window > 0) out.window = window;
304
+ const maxOutput = Number(entry?.limit?.output);
305
+ if (Number.isInteger(maxOutput) && maxOutput > 0) out.maxOutput = maxOutput;
306
+ const cost = entry?.cost;
307
+ if (cost && Number.isFinite(Number(cost.input)) && Number.isFinite(Number(cost.output))) {
308
+ out.price = { input: Number(cost.input), output: Number(cost.output), cacheRead: Number(cost.cache_read ?? cost.input), cacheWrite: Number(cost.cache_write ?? cost.input) };
309
+ }
310
+ return out;
311
+ }
312
+
313
+ // The models to offer for a provider: those it listed, with what models.dev knows of them; when it listed none, the
314
+ // models.dev models of the provider that call tools (an agent needs them). [] when neither is known.
315
+ export function enrichModels(listed, catalogue, modelsDevId) {
316
+ const known = (modelsDevId && catalogue?.[modelsDevId]?.models) || {};
317
+ if (listed?.length) {
318
+ return listed.map((m) => {
319
+ const fromCatalogue = known[m.id] ? modelFromCatalogue(m.id, known[m.id]) : { id: m.id };
320
+ return { ...knownModel(m.id), ...fromCatalogue, ...Object.fromEntries(Object.entries(m).filter(([, v]) => v !== undefined)) };
321
+ });
322
+ }
323
+ return Object.entries(known).filter(([, e]) => e?.tool_call !== false).map(([id, e]) => modelFromCatalogue(id, e));
324
+ }
325
+
326
+ // USD for a request's usage at a provider model's price (per million tokens), or null without one.
327
+ export function priceCost(price, usage = {}) {
328
+ if (!price) return null;
329
+ const n = (v) => Math.max(0, Number(v) || 0);
330
+ return (n(usage.input_tokens) * price.input + n(usage.output_tokens) * price.output + n(usage.cache_read_input_tokens) * price.cacheRead + n(usage.cache_creation_input_tokens) * price.cacheWrite) / 1e6;
331
+ }
package/src/remote.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Publish a local interactive session to the gateway, so that the account's browser can watch it and steer it: send
2
2
  // it messages (as if typed in its input box: /commands, !shell, #memory, pasted images), answer its questions, stop
3
3
  // it, switch model and effort, complete input, browse directories for /cd and read a tool call's whole output. The
4
- // session never listens on the network: it connects out to the codex-gateway with the gateway API key from /login,
4
+ // session never listens on the network: it connects out to the codex-gateway with the gateway API key from /connect,
5
5
  // declares the commands it takes when it registers, and gets them on its command stream. With
6
6
  // CLAUDE_PRO_REMOTE_COMMANDS=0 it declares none and is read-only on the page.
7
7
  // The same connection carries the messages of the account's sessions on other computers (`@公司 ...`, see peers.js).
@@ -206,7 +206,11 @@ export class RemoteControl {
206
206
  // gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model}, seed() -> items, status() -> object,
207
207
  // peerMessage(message), changed() (online or viewers changed), refused(status) (the key was refused: closed), and
208
208
  // the page's commands: send, interrupt, answer (dialog), options, suggest, list, output (see COMMANDS).
209
- constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
209
+ // `rc`: remote control is on (/rc): the gateway's web page shows the conversation and may steer the session. Off,
210
+ // the session is online only for messages between sessions: no conversation is uploaded, and its status is only
211
+ // whether it works and its name (see setRc).
212
+ constructor({ gateway, id, handlers, rc = false, fetchImpl = globalThis.fetch }) {
213
+ this.rc = Boolean(rc);
210
214
  this.base = String(gateway.url).replace(/\/+$/, '');
211
215
  this.apiKey = gateway.apiKey;
212
216
  this.id = /^[\w-]{8,64}$/.test(id || '') ? id : newRemoteId();
@@ -234,9 +238,24 @@ export class RemoteControl {
234
238
  }
235
239
 
236
240
  // The commands this session takes, as declared to the gateway.
237
- get commands() { return Object.keys(COMMANDS).filter((type) => typeof this.handlers[COMMANDS[type]] === 'function'); }
238
-
239
- get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
241
+ get commands() { return this.rc ? Object.keys(COMMANDS).filter((type) => typeof this.handlers[COMMANDS[type]] === 'function') : []; }
242
+
243
+ // nobody watching, or remote control off: events are not uploaded (a snapshot follows when someone comes)
244
+ get viewing() { return this.rc && this.viewers !== 0; }
245
+
246
+ // Remote control on or off: the gateway is told at once (registering again), and a page that watched is closed by
247
+ // it. What happened while it was off is in the snapshot that goes out when it comes on: the conversation is kept
248
+ // here either way.
249
+ async setRc(on) {
250
+ on = Boolean(on);
251
+ if (this.rc === on) return;
252
+ this.rc = on;
253
+ this.events = [];
254
+ this.needSnapshot = true;
255
+ this.lastStatus = '';
256
+ if (this.registered) await this.register();
257
+ this.scheduleFlush(0);
258
+ }
240
259
 
241
260
  // `persistent`: keep trying when the gateway cannot be reached now (a restart); otherwise the first failure is thrown.
242
261
  async start({ persistent = false } = {}) {
@@ -276,7 +295,8 @@ export class RemoteControl {
276
295
  async register() {
277
296
  const info = this.handlers.info?.() || {};
278
297
  const commands = this.commands;
279
- const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...info, ...(commands.length ? { commands } : {}) });
298
+ const shown = this.rc ? info : { ...info, title: '', cwd: '' };
299
+ const data = await this.request('POST', '/v1/remote/sessions', { id: this.id, host: os.hostname(), version: info.version, ...shown, rc: this.rc, ...(commands.length ? { commands } : {}) });
280
300
  if (data.id) this.id = data.id;
281
301
  this.registered = true;
282
302
  this.needSnapshot = true;
@@ -290,7 +310,7 @@ export class RemoteControl {
290
310
  try {
291
311
  if (!this.registered) {
292
312
  await this.register();
293
- // closed while it registered (/logout, another account): the session that ended must not go online again,
313
+ // closed while it registered (/disconnect, another account): the session that ended must not go online again,
294
314
  // and the registration that just went through gets the bye that close() could not send yet
295
315
  if (this.closed) {
296
316
  this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/events`, { messages: [{ t: 'bye', restarting: false }] }, { timeout: 1500 }).catch(() => {});
@@ -386,6 +406,8 @@ export class RemoteControl {
386
406
  return;
387
407
  }
388
408
  if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
409
+ // 通讯录: someone asked this account to be a contact, or accepted its request
410
+ if (cmd.type === 'contact') { try { this.handlers.contactEvent?.(cmd); } catch { /* the App's problem */ } return; }
389
411
  if (!cmd.cid) return;
390
412
  if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
391
413
  // A command of the page, answered with POST …/results {cid, ok: true, …fields} or {cid, ok: false, error} (the
@@ -399,6 +421,7 @@ export class RemoteControl {
399
421
  };
400
422
  const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
401
423
  const handler = Object.hasOwn(COMMANDS, cmd.type) ? this.handlers[COMMANDS[cmd.type]] : null;
424
+ if (!this.rc) { failed(new Error('Remote control is off for this session: /rc in its terminal turns it on.')); return; }
402
425
  if (typeof handler !== 'function') {
403
426
  // an older gateway forwards every command, declared or not
404
427
  failed(new Error(this.commands.length ? `Unknown command: ${cmd.type}` : 'This session is read-only on the web page (CLAUDE_PRO_REMOTE_COMMANDS=0 on its computer).'));
@@ -428,21 +451,34 @@ export class RemoteControl {
428
451
  if (this.seenPeer.size > 500) this.seenPeer.delete(this.seenPeer.values().next().value);
429
452
  const f = cmd.from || {};
430
453
  const machine = f.machine || f.host || 'computer';
454
+ // a contact's session (another person's account): its 通讯号 and how this account takes its tasks
455
+ const account = typeof f.account === 'string' && f.account ? f.account : null;
431
456
  this.handlers.peerMessage?.({
432
457
  id: cmd.cid,
433
458
  kind: cmd.kind === 'reply' ? 'reply' : 'task',
434
459
  text: String(cmd.text ?? ''),
435
460
  inReplyTo: cmd.inReplyTo || null,
436
- from: { id: f.id, name: `${machine}/${f.name || 'session'}`, cwd: f.cwd || '', machine, remote: true },
461
+ from: {
462
+ id: f.id, name: `${account ? `${account}:` : ''}${machine}/${f.name || 'session'}`, cwd: account ? '' : (f.cwd || ''), machine, remote: true,
463
+ ...(account ? { account, trust: f.trust === 'auto' ? 'auto' : 'confirm' } : {}),
464
+ },
437
465
  });
438
466
  } catch { /* the App's problem: the message is acknowledged anyway, or it would come back forever */ }
439
467
  ack();
440
468
  }
441
469
 
442
- // The sessions of this gateway account, on every computer, as the gateway lists them (this one included).
470
+ // The sessions of this gateway account, on every computer, as the gateway lists them (this one included), and
471
+ // the online sessions of the account's contacts (each with `account`, the contact's 通讯号).
443
472
  async sessions() {
444
473
  const data = await this.request('GET', '/v1/remote/sessions');
445
- return Array.isArray(data?.data) ? data.data : [];
474
+ return { own: Array.isArray(data?.data) ? data.data : [], contacts: Array.isArray(data?.contacts) ? data.contacts : [] };
475
+ }
476
+
477
+ // 通讯录 at the gateway: no action lists them ({handle, contacts: [{handle, status, trust, online}]}); handle,
478
+ // add, accept, reject, remove, block, trust act ({handle[, trust]}) and answer with the list as it is then.
479
+ async contacts(action = '', body = {}) {
480
+ if (!action) return await this.request('GET', '/v1/remote/contacts');
481
+ return await this.request('POST', `/v1/remote/contacts/${action}`, body, { retry: false });
446
482
  }
447
483
 
448
484
  // A message to another session of the account: resolves with {id} (the message's id, which a reply names).
@@ -509,8 +545,13 @@ export class RemoteControl {
509
545
  this.progress.clear();
510
546
  }
511
547
 
548
+ // Remote control off: only what the account's other sessions see of it (whether it works, its name, its model).
512
549
  status() {
513
- try { return this.handlers.status?.() || {}; } catch (e) { return { error: e.message }; }
550
+ let status;
551
+ try { status = this.handlers.status?.() || {}; } catch (e) { status = { error: e.message }; }
552
+ if (this.rc) return status;
553
+ const { busy, name, model } = status;
554
+ return { busy: Boolean(busy), name, model };
514
555
  }
515
556
 
516
557
  // What decides whether the status is sent again: all of it while a page watches; while none does, only what
@@ -533,7 +574,7 @@ export class RemoteControl {
533
574
  if (this.closed || !this.registered || (!this.online && !this.closing)) return;
534
575
  this.takeProgress();
535
576
  const status = this.status();
536
- if (this.needSnapshot || this.sinceSnapshot > SNAPSHOT_EVERY) {
577
+ if (this.rc && (this.needSnapshot || this.sinceSnapshot > SNAPSHOT_EVERY)) {
537
578
  this.needSnapshot = false;
538
579
  this.events = [];
539
580
  this.sinceSnapshot = 0;
package/src/tools/bash.js CHANGED
@@ -60,7 +60,7 @@ export function makeBashTool(config) {
60
60
  const isCmd = shell.kind === 'cmd';
61
61
  return {
62
62
  name: 'Bash',
63
- description: `Executes a given ${isCmd ? 'cmd.exe' : 'bash'} command with an optional timeout. The working directory persists between commands; shell state (variables, functions) does not.
63
+ description: `Executes a given ${isCmd ? 'cmd.exe' : 'bash'} command with an optional timeout. Every command starts in the session's working directory: a \`cd\` lasts for that command only, and shell state (variables, functions) does not persist either.
64
64
 
65
65
  This tool is for terminal operations like git, npm, docker, running builds and tests. For file work use the dedicated tools instead of shell commands: Read, not cat/head/tail; Edit, not sed/awk; Write, not echo or heredoc redirection; Glob and Grep, not find and grep. An edit made with Edit, MultiEdit or Write can be undone with /rewind and is shown to the user as a diff; one made by a command (a script that rewrites the file, sed -i) is neither. To edit and then build or test in one step, put the edit calls and the Bash call in the same response: they run in that order. A script is fine for a mechanical change across many files, once you know git can bring them back.
66
66
 
@@ -92,7 +92,6 @@ When you commit (the system prompt says when): run git status, git diff and git
92
92
  const command = String(input.command || '').trim();
93
93
  if (!command) return { isError: true, content: 'Empty command' };
94
94
  const stdinText = typeof input.stdin === 'string' ? input.stdin : undefined;
95
- const cwdFile = path.join(os.tmpdir(), `claude-pro-cwd-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
96
95
  let cwd = ctx.cwd;
97
96
  if (!fs.existsSync(cwd)) cwd = ctx.projectRoot;
98
97
 
@@ -122,7 +121,7 @@ When you commit (the system prompt says when): run git status, git diff and git
122
121
  let timedOut = false;
123
122
  let child;
124
123
  try {
125
- child = spawnShell(shell, command, { cwd, env: childEnv(), cwdFile, stdin: stdinText });
124
+ child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
126
125
  } catch (e) {
127
126
  resolve({ isError: true, content: `Failed to start shell: ${e.message}` });
128
127
  return;
@@ -133,11 +132,6 @@ When you commit (the system prompt says when): run git status, git diff and git
133
132
  const finish = (code, err) => {
134
133
  clearTimeout(timer);
135
134
  ctx.signal?.removeEventListener('abort', onAbort);
136
- try {
137
- const newCwd = fs.readFileSync(cwdFile, 'utf8').trim();
138
- if (newCwd && fs.existsSync(newCwd)) ctx.setCwd(path.resolve(newCwd));
139
- } catch { /* command may have exited early */ }
140
- fs.rm(cwdFile, { force: true }, () => {});
141
135
  if (ctx.signal?.aborted) {
142
136
  reject(Object.assign(new Error('aborted'), { name: 'AbortError', partialOutput: output }));
143
137
  return;
@@ -5,31 +5,32 @@ const unavailable = { isError: true, content: 'Talking to other sessions is only
5
5
 
6
6
  export const ListPeersTool = {
7
7
  name: 'ListPeers',
8
- description: 'List the other claude-pro sessions (each is an agent with its own conversation, working in its own directory): those running on this machine, and those on the user\'s other computers that are online at the gateway, with the name to send them a message with MessagePeer.',
8
+ description: 'List the other claude-pro sessions (each is an agent with its own conversation, working in its own directory): those running on this machine, those on the user\'s other computers that are online at the gateway, and those of the user\'s contacts (other people), with the name to send them a message with MessagePeer.',
9
9
  input_schema: { type: 'object', properties: {} },
10
10
  summarize() { return ''; },
11
11
  async call(input, ctx) {
12
12
  if (!ctx.io?.listAllPeers) return unavailable;
13
- const { me, local, remote, online } = await ctx.io.listAllPeers();
13
+ const { me, local, remote, contacts = [], online } = await ctx.io.listAllPeers();
14
14
  const head = `You are "${me.name}" (${me.cwd})${online ? `; sessions on other computers know you as "${me.label}"` : ''}.`;
15
- const count = local.length + remote.length;
15
+ const count = local.length + remote.length + contacts.length;
16
16
  if (!count) return { content: `${head}\nNo other session is running${online ? '' : ' on this machine (this session is not online at the gateway, so sessions on other computers are not listed)'}.`, display: { summary: 'No other session' } };
17
17
  const lines = [head];
18
18
  if (local.length) lines.push('On this machine:', ...local.map((p) => `- ${p.name}: working in ${p.cwd}`));
19
19
  if (remote.length) lines.push('On the user\'s other computers (through the gateway):', ...remote.map((p) => `- ${p.label}: working in ${p.cwd} on the computer "${p.machine}"${p.busy ? ' (busy now)' : ''}`));
20
+ if (contacts.length) lines.push('Of the user\'s contacts, other people (message them only when the user asks you to):', ...contacts.map((p) => `- ${p.label}: a session of ${p.account}${p.busy ? ' (busy now)' : ''}`));
20
21
  return { content: lines.join('\n'), display: { summary: `${count} other session${count === 1 ? '' : 's'}` } };
21
22
  },
22
23
  };
23
24
 
24
25
  export const MessagePeerTool = {
25
26
  name: 'MessagePeer',
26
- description: `Send a task or a question to another claude-pro session, on this machine or on one of the user's other computers (ListPeers lists them). The other session's agent works on it in its own conversation and directory, and the final text of its answer comes back to you later as a <peer-message kind="reply"> message: you do not wait for it here. Use it to delegate work that belongs to another session's project or context, or to ask it something only it knows. Write the message so that it stands on its own: the other agent has not seen your conversation.
27
+ description: `Send a task or a question to another claude-pro session, on this machine, on one of the user's other computers, or of one of the user's contacts (ListPeers lists them). A contact's session belongs to another person: message it only when the user asks you to, and send it nothing private. The other session's agent works on it in its own conversation and directory, and the final text of its answer comes back to you later as a <peer-message kind="reply"> message: you do not wait for it here. Use it to delegate work that belongs to another session's project or context, or to ask it something only it knows. Write the message so that it stands on its own: the other agent has not seen your conversation.
27
28
 
28
29
  Send it once and wait for the answer: do not send reminders or "please report" follow-ups while the other session works. Messages that arrive while it is busy are handled together after what it is doing, so they only add to its work; the answer comes by itself when it is done.`,
29
30
  input_schema: {
30
31
  type: 'object',
31
32
  properties: {
32
- to: { type: 'string', description: 'The name of the session as ListPeers shows it (computer/name for one on another computer)' },
33
+ to: { type: 'string', description: 'The name of the session as ListPeers shows it (computer/name for one on another computer, contact:computer/name for a contact\'s)' },
33
34
  message: { type: 'string', description: 'The task or question to send, written so it stands on its own' },
34
35
  },
35
36
  required: ['to', 'message'],
package/src/ui/dialogs.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Modal dialogs rendered in the live region: selection menus (questions, the model and session pickers, /rewind),
2
- // with a typed answer of their own when they offer "Other".
2
+ // with a typed answer of their own when they offer "Other", and a text field (/connect asks for a key or an address).
3
3
 
4
4
  import { c, glyphs, padEnd, stringWidth, truncate, wordWrap } from './ansi.js';
5
5
  import { Editor } from './editor.js';
@@ -131,3 +131,79 @@ export class SelectDialog {
131
131
  return { lines: out, cursor };
132
132
  }
133
133
  }
134
+
135
+ // One line of text to type or paste (Ctrl+V, or the terminal's paste: the App gives a dialog's `editor` the pasted
136
+ // text). Resolves with the text, trimmed, or null (Esc). `secret`: what is typed shows as stars and its length only
137
+ // (a key on the screen of a recorded or shared terminal is given away), and spaces and line breaks are taken out
138
+ // (a key has none; a paste may bring one along). `allowEmpty`: Enter on an empty field answers '' (to keep what
139
+ // was saved); without it Enter waits for text. `validate(text)`: a message to show under the field instead of
140
+ // answering, or null. The remote page sees the dialog but cannot answer it (it has no options): the text is typed here.
141
+ export class TextInputDialog {
142
+ constructor({ title, body = [], question, placeholder = '', secret = false, initial = '', allowEmpty = false, error = null, validate = null, color = c.permission }) {
143
+ this.title = title;
144
+ this.body = body;
145
+ this.question = question;
146
+ this.placeholder = placeholder;
147
+ this.secret = secret;
148
+ this.allowEmpty = allowEmpty;
149
+ this.error = error;
150
+ this.validate = validate;
151
+ this.color = color;
152
+ this.cancelValue = null;
153
+ this.editor = new Editor();
154
+ if (initial) this.editor.set(initial);
155
+ }
156
+
157
+ resolve(value) {
158
+ const cb = this.onResolve;
159
+ this.onResolve = null;
160
+ cb?.(value);
161
+ }
162
+
163
+ value() {
164
+ const text = this.editor.expanded();
165
+ return this.secret ? text.replace(/\s+/g, '') : text.replace(/[\r\n]+/g, ' ').trim();
166
+ }
167
+
168
+ handleKey(str, key = {}) {
169
+ if (key.name === 'escape') { this.resolve(null); return true; }
170
+ if (key.name === 'return' && !key.meta) {
171
+ const text = this.value();
172
+ if (!text && !this.allowEmpty) return true;
173
+ const problem = text ? this.validate?.(text) : null;
174
+ if (problem) { this.error = problem; return true; }
175
+ this.resolve(text);
176
+ return true;
177
+ }
178
+ this.error = null;
179
+ this.editor.handleKey(str, key);
180
+ return true; // modal: everything else stays here
181
+ }
182
+
183
+ render(width) {
184
+ const lines = [];
185
+ if (this.title) lines.push(c.bold(this.color(this.title)), '');
186
+ lines.push(...this.body);
187
+ if (this.body.length) lines.push('');
188
+ if (this.question) lines.push(this.question);
189
+ const inner = Math.max(20, width - 1) - 4;
190
+ let cursor = null;
191
+ if (this.secret) {
192
+ const n = this.value().length;
193
+ const room = Math.max(4, inner - 20);
194
+ const stars = n ? `${'*'.repeat(Math.min(n, room))}${n > room ? '...' : ''}` : '';
195
+ const row = boxRows(lines, width) + 1; // the row it takes once box() has wrapped the long ones, and the top border
196
+ lines.push(`> ${stars}${n ? c.dim(` (${n} characters)`) : c.dim(this.placeholder)}`);
197
+ cursor = { row, col: 2 + 2 + stringWidth(stars) };
198
+ } else {
199
+ const r = this.editor.render(width - 4, { placeholder: this.placeholder });
200
+ const top = boxRows(lines, width) + 1;
201
+ lines.push(...r.lines.map((l) => truncate(l, inner)));
202
+ if (r.cursor) cursor = { row: top + r.cursor.row, col: 2 + r.cursor.col };
203
+ }
204
+ if (this.error) lines.push('', c.red(this.error));
205
+ const out = box(lines, width, this.color);
206
+ out.push(c.dim(` Enter to confirm · Esc to cancel${this.secret ? ' · Ctrl+V pastes' : ''}`));
207
+ return { lines: out, cursor };
208
+ }
209
+ }