@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.
- package/README.md +69 -21
- package/package.json +5 -2
- package/src/agent.js +12 -3
- package/src/api.js +85 -43
- package/src/browser/session.js +11 -1
- package/src/commands.js +390 -84
- package/src/config.js +139 -17
- package/src/gateway.js +27 -71
- package/src/main.js +10 -10
- package/src/openai-chat.js +379 -0
- package/src/peers.js +23 -6
- package/src/providers.js +331 -0
- package/src/remote.js +53 -12
- package/src/tools/bash.js +2 -8
- package/src/tools/peers.js +6 -5
- package/src/ui/dialogs.js +77 -1
- package/src/ui/repl.js +122 -38
- package/src/utils/shell.js +4 -5
package/src/commands.js
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { c, glyphs, padEnd, truncate } from './ui/ansi.js';
|
|
6
|
-
import { SelectDialog } from './ui/dialogs.js';
|
|
6
|
+
import { SelectDialog, TextInputDialog } from './ui/dialogs.js';
|
|
7
7
|
import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
|
|
8
8
|
import { loadConfig, settingsFiles, configEntries, writeConfigSetting, unsetConfigSetting, rememberChoice, applyRememberedChoices, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
|
|
9
|
-
import {
|
|
9
|
+
import { loginWithKey, gatewayLogin, gatewayKeyPage, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, loadGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
|
|
10
|
+
import { GATEWAY_PROVIDER, PRESETS, providerInfo, connectedProviders, readConnections, saveConnection, removeConnection, normalizeBaseUrl, validBaseUrl, cleanProviderId, reservedProviderId, listProviderModels, testProviderModel, modelsDevCatalogue, enrichModels } from './providers.js';
|
|
10
11
|
import { SessionStore } from './session.js';
|
|
11
12
|
import { memoryFiles, listAutoMemories } from './context.js';
|
|
12
13
|
import { INIT_PROMPT } from './prompts.js';
|
|
@@ -29,23 +30,53 @@ const effortLevels = (modelId, modelInfo = null) => {
|
|
|
29
30
|
return remote.length ? remote : EFFORTS;
|
|
30
31
|
};
|
|
31
32
|
|
|
33
|
+
// The models of the providers connected with /connect, for /model: each provider's list asked for anew (4 seconds at
|
|
34
|
+
// most), with what was kept at /connect about them (windows, prices); without an answer, the list kept then.
|
|
35
|
+
async function providerModelChoices() {
|
|
36
|
+
const groups = await Promise.all(connectedProviders().map(async (info) => {
|
|
37
|
+
let listed = null;
|
|
38
|
+
try {
|
|
39
|
+
listed = (await listProviderModels({ ...info, ...info.connection, baseUrl: info.connection.baseUrl || info.baseUrl }, { timeoutMs: 4000, kinds: [info.connection.authHeader || 'x-api-key'] })).models;
|
|
40
|
+
} catch { /* the kept list */ }
|
|
41
|
+
const kept = info.connection.models || [];
|
|
42
|
+
const models = listed?.length ? listed.map((m) => ({ ...kept.find((k) => k.id === m.id), ...m })) : kept;
|
|
43
|
+
return models.map((m) => ({
|
|
44
|
+
value: `${info.id}/${m.id}`,
|
|
45
|
+
label: `${info.id}/${m.id}`,
|
|
46
|
+
description: [info.name, m.name && m.name !== m.id ? m.name : '', m.window ? `${formatTokens(m.window)} context` : ''].filter(Boolean).join(' · '),
|
|
47
|
+
}));
|
|
48
|
+
}));
|
|
49
|
+
return groups.flat();
|
|
50
|
+
}
|
|
51
|
+
|
|
32
52
|
// What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
|
|
33
|
-
// default first. `value` is what /model <value> takes.
|
|
34
|
-
// seconds at most
|
|
35
|
-
// last, else gpt-6.1-sol for its GPT models
|
|
53
|
+
// default first. `value` is what /model <value> takes. Every connected provider's models, provider/model, 7bit.fun's
|
|
54
|
+
// among them (asked for anew each time, 4 seconds at most, so that a model just added is there without a restart;
|
|
55
|
+
// without an answer the list given last, else gpt-6.1-sol for its GPT models); the Claude aliases where a provider of
|
|
56
|
+
// Claude is connected. A provider that is not connected offers nothing.
|
|
36
57
|
export async function modelChoices(cfg) {
|
|
37
58
|
const configured = cfg.configuredModelSpec;
|
|
38
|
-
const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).
|
|
39
|
-
|
|
40
|
-
|
|
59
|
+
const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).label}` }];
|
|
60
|
+
const tag = (m) => `${m.provider}/${m.id}`;
|
|
61
|
+
const aliased = new Set();
|
|
62
|
+
if (cfg.claudeProvider()) {
|
|
63
|
+
for (const a of ['opus', 'sonnet', 'haiku']) {
|
|
64
|
+
const target = cfg.resolveModel(cfg.aliasTarget(a));
|
|
65
|
+
aliased.add(tag(target));
|
|
66
|
+
opts.push({ value: a, label: a, description: `→ ${target.label}` });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const others = providerModelChoices();
|
|
41
70
|
const login = gatewayLogin(cfg.gatewayUrl);
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
71
|
+
if (login) {
|
|
72
|
+
let served = null;
|
|
73
|
+
try { served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: true }); } catch { /* offline: the fallback below */ }
|
|
74
|
+
for (const m of served?.length ? served : [{ id: 'gpt-6.1-sol' }]) {
|
|
75
|
+
if (aliased.has(`${GATEWAY_PROVIDER}/${m.id}`)) continue;
|
|
76
|
+
opts.push({ value: `${GATEWAY_PROVIDER}/${m.id}`, label: `${GATEWAY_PROVIDER}/${m.id}`, description: ['7bit.fun', isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || ''].filter(Boolean).join(' · ') });
|
|
77
|
+
}
|
|
48
78
|
}
|
|
79
|
+
opts.push(...(await others).filter((o) => !aliased.has(o.value)));
|
|
49
80
|
return opts;
|
|
50
81
|
}
|
|
51
82
|
|
|
@@ -54,7 +85,7 @@ export async function modelChoices(cfg) {
|
|
|
54
85
|
export async function effortChoices(cfg) {
|
|
55
86
|
const id = cfg.model.id;
|
|
56
87
|
let info = null;
|
|
57
|
-
if (isGpt(id)) {
|
|
88
|
+
if (isGpt(id) && cfg.model.provider === GATEWAY_PROVIDER) {
|
|
58
89
|
const login = gatewayLogin(cfg.gatewayUrl);
|
|
59
90
|
try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000), fresh: true })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
|
|
60
91
|
}
|
|
@@ -77,7 +108,8 @@ export function buildCommands(app) {
|
|
|
77
108
|
const log = (...lines) => app.screen.log(...lines);
|
|
78
109
|
const out = (lines) => log(resultLines(Array.isArray(lines) ? lines : [lines]), '');
|
|
79
110
|
|
|
80
|
-
// /model and /effort choices are kept for later sessions (rememberChoice); say so, or why
|
|
111
|
+
// /model and /effort choices are kept for later sessions (rememberChoice), for the provider in use; say so, or why
|
|
112
|
+
// they are not.
|
|
81
113
|
const keep = (cfg, patch, forgotten) => {
|
|
82
114
|
try {
|
|
83
115
|
rememberChoice(patch);
|
|
@@ -286,10 +318,12 @@ export function buildCommands(app) {
|
|
|
286
318
|
if (!choice) return;
|
|
287
319
|
}
|
|
288
320
|
const forget = choice === '__default__' || choice === 'default';
|
|
289
|
-
const
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
321
|
+
const target = cfg.resolveModel(forget ? cfg.configuredModelSpec : choice);
|
|
322
|
+
const sameProvider = target.provider === cfg.model.provider;
|
|
323
|
+
const changed = target.id !== cfg.model.id || !sameProvider;
|
|
324
|
+
// (Not asked at a pause for a rate limit: the cache runs out while waiting for the limit as well. Another
|
|
325
|
+
// provider's model of the same name has no cache of this one.)
|
|
326
|
+
if (changed && !app.agent.pausedForLimit && !(await confirmCacheLoss('Switching the model', { model: sameProvider ? target.id : target.label }))) { out(c.dim('The model was not changed.')); return; }
|
|
293
327
|
cfg.modelOverride = forget ? null : choice;
|
|
294
328
|
if (changed) app.runtime.invalidateSystemPrompt(); // the prompt names the model; the new model starts a cache of its own anyway
|
|
295
329
|
const kept = keep(cfg, { model: cfg.modelOverride }, forget);
|
|
@@ -306,7 +340,7 @@ export function buildCommands(app) {
|
|
|
306
340
|
get argHint() {
|
|
307
341
|
const cfg = app.runtime.config;
|
|
308
342
|
const login = gatewayLogin(cfg.gatewayUrl);
|
|
309
|
-
return `[${effortLevels(cfg.model.id, cachedGatewayModel(login, cfg.model.id)).join('|')}|auto|default]`;
|
|
343
|
+
return `[${effortLevels(cfg.model.id, cfg.model.provider === GATEWAY_PROVIDER ? cachedGatewayModel(login, cfg.model.id) : null).join('|')}|auto|default]`;
|
|
310
344
|
},
|
|
311
345
|
description: 'Set reasoning effort (output_config.effort; kept for later sessions)',
|
|
312
346
|
async run(args) {
|
|
@@ -338,7 +372,7 @@ export function buildCommands(app) {
|
|
|
338
372
|
},
|
|
339
373
|
});
|
|
340
374
|
|
|
341
|
-
// After
|
|
375
|
+
// After the gateway was connected: the configuration read again, with the remembered /model and /effort.
|
|
342
376
|
const afterLogin = () => {
|
|
343
377
|
const cfg = app.runtime.config;
|
|
344
378
|
const model = cfg.model.id;
|
|
@@ -350,75 +384,282 @@ export function buildCommands(app) {
|
|
|
350
384
|
if (cfg.model.id !== model) app.runtime.invalidateSystemPrompt();
|
|
351
385
|
};
|
|
352
386
|
const accountLine = (account) => `${account.name || ''}${account.email ? ` <${account.email}>` : ''} · balance ${c.bold(formatUsd(account.available_usd ?? account.balance_usd))}`;
|
|
353
|
-
|
|
354
|
-
//
|
|
355
|
-
|
|
356
|
-
|
|
387
|
+
const hostOf = (url) => { try { return new URL(url).host; } catch { return url; } };
|
|
388
|
+
// A check that goes over the network (a key, a model): the footer says so meanwhile, and Esc cancels it, as /doctor's.
|
|
389
|
+
const checking = async (status, fn) => {
|
|
390
|
+
app.busy = true;
|
|
391
|
+
app.status = status;
|
|
392
|
+
app.turnStart = Date.now();
|
|
393
|
+
app.controller = new AbortController();
|
|
394
|
+
try {
|
|
395
|
+
return await fn(app.controller.signal);
|
|
396
|
+
} finally {
|
|
397
|
+
app.busy = false;
|
|
398
|
+
app.status = null;
|
|
399
|
+
app.controller = null;
|
|
400
|
+
app.screen.schedule();
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
// The gateway connected: this session goes online there at once, for messages between sessions; its web page shows
|
|
404
|
+
// it (and can steer it, unless CLAUDE_PRO_REMOTE_COMMANDS=0) only with remote control on (/rc).
|
|
357
405
|
const goOnline = async () => {
|
|
358
406
|
const remote = await app.syncRemote();
|
|
359
407
|
if (!remote) return;
|
|
360
|
-
const page = remote.
|
|
361
|
-
? '
|
|
362
|
-
:
|
|
408
|
+
const page = !remote.rc
|
|
409
|
+
? 'sessions on your other computers and your contacts can send it tasks; /rc lets the web page (远程控制) show and steer it'
|
|
410
|
+
: remote.commands?.length
|
|
411
|
+
? 'its web page shows it and can send it messages and commands (CLAUDE_PRO_REMOTE_COMMANDS=0 makes the page read-only)'
|
|
412
|
+
: 'the read-only web page shows it';
|
|
363
413
|
out(remote.registered
|
|
364
414
|
? `${c.green('⇄')} This session is online at the gateway: ${page}.`
|
|
365
415
|
: c.dim(`⇄ This session goes online at the gateway as soon as ${remote.base} can be reached.`));
|
|
366
416
|
};
|
|
367
417
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
const controller = new AbortController();
|
|
393
|
-
pendingLogin = controller;
|
|
418
|
+
// Connecting the gateway (7bit.fun in /connect): a key of the user's account, made on the gateway's page and pasted
|
|
419
|
+
// here (/login did this until 2026-11-19, and before that sent the browser to the gateway). As with the other
|
|
420
|
+
// providers, a saved key is kept with Enter or replaced by pasting another; a refused one is asked for again, with
|
|
421
|
+
// what the gateway said, three times at most.
|
|
422
|
+
async function connectGateway() {
|
|
423
|
+
const cfg = app.runtime.config;
|
|
424
|
+
const url = cfg.gatewayUrl;
|
|
425
|
+
const page = gatewayKeyPage(url);
|
|
426
|
+
let saved = gatewayLogin(url);
|
|
427
|
+
let error = null;
|
|
428
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
429
|
+
const typed = await app.showDialog(new TextInputDialog({
|
|
430
|
+
title: `Connect ${hostOf(url)}`,
|
|
431
|
+
body: [
|
|
432
|
+
`Make an API key on ${c.blue(page)} (创建新密钥) and paste it here.`,
|
|
433
|
+
c.dim('The key is checked with the gateway, then kept in ~/.claude-pro/gateway.json, readable by you alone.'),
|
|
434
|
+
],
|
|
435
|
+
question: 'API key:',
|
|
436
|
+
placeholder: saved ? 'Enter: keep the saved key · or paste another (Ctrl+V)' : 'paste the key (Ctrl+V)',
|
|
437
|
+
secret: true,
|
|
438
|
+
allowEmpty: Boolean(saved),
|
|
439
|
+
error,
|
|
440
|
+
}));
|
|
441
|
+
if (typed === null) { out(c.dim(saved ? `${hostOf(url)}: the saved key is kept.` : `${hostOf(url)} was not connected. /connect connects it.`)); return; }
|
|
394
442
|
try {
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
onUrl: (page) => out([`Opening the gateway login in your browser. If it does not open, visit:`, c.blue(page), c.dim('Waiting for the browser (10 minutes at most)…')]),
|
|
399
|
-
});
|
|
443
|
+
let account;
|
|
444
|
+
if (typed) account = (await checking('Checking the key', (signal) => loginWithKey({ url, apiKey: typed, signal }))).balance;
|
|
445
|
+
else account = await checking('Checking the saved key', (signal) => fetchGatewayAccount(saved, { signal }));
|
|
400
446
|
afterLogin();
|
|
401
|
-
out([
|
|
447
|
+
out([`${c.green('✔')} Connected the gateway ${c.bold(url)}: ${cfg.model.label}`, accountLine(account), c.dim(`Top up and usage: ${page}`)]);
|
|
402
448
|
await goOnline();
|
|
449
|
+
return;
|
|
403
450
|
} catch (e) {
|
|
404
|
-
if (e.name
|
|
405
|
-
|
|
406
|
-
if (
|
|
451
|
+
if (e.name === 'AbortError') return;
|
|
452
|
+
if (e.status !== 401 && e.status !== 403) { out(c.red(`Cannot reach the gateway ${url}: ${e.message}`)); return; }
|
|
453
|
+
if (!typed) { clearGatewayLogin(); saved = null; }
|
|
454
|
+
error = `The gateway refused ${typed ? 'that' : 'the saved'} key (${e.status}${e.message ? `: ${e.message}` : ''}). ${typed ? `Check it on ${page}.` : 'Paste another.'}`;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
out(c.red(`${hostOf(url)} was not connected: the gateway refused the key three times. Check it on ${page}, then /connect again.`));
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// After a provider was disconnected: the model in use, when its provider is not connected any more, gives way to the
|
|
461
|
+
// default (which follows the providers still connected, see Config.defaultModelSpec). Returns what to say, or ''.
|
|
462
|
+
function fallBack() {
|
|
463
|
+
const cfg = app.runtime.config;
|
|
464
|
+
if (cfg.providerConnected(cfg.model.provider)) return '';
|
|
465
|
+
cfg.modelOverride = null;
|
|
466
|
+
try { rememberChoice({ model: null }); } catch { /* the settings file cannot be written: for this session */ }
|
|
467
|
+
app.runtime.invalidateSystemPrompt();
|
|
468
|
+
const now = cfg.model;
|
|
469
|
+
return cfg.providerConnected(now.provider)
|
|
470
|
+
? ` The model is ${c.bold(now.label)} now (the default).`
|
|
471
|
+
: ` No connected provider serves a model now: /connect connects one.`;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Forgetting the gateway's key (7bit.fun in /disconnect; /logout until 2026-11-19): this session goes offline there,
|
|
475
|
+
// and the other sessions of this computer follow within seconds (see App.syncRemote).
|
|
476
|
+
function disconnectGateway() {
|
|
477
|
+
const cfg = app.runtime.config;
|
|
478
|
+
const had = clearGatewayLogin();
|
|
479
|
+
const wasOnline = Boolean(app.remote);
|
|
480
|
+
app.stopRemote();
|
|
481
|
+
out(had
|
|
482
|
+
? `Disconnected 7bit.fun: its key is forgotten.${wasOnline ? ' This session is offline there now.' : ''}${fallBack()}`
|
|
483
|
+
: c.dim(`7bit.fun (${cfg.gatewayUrl}) was not connected.`));
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// ---------------------------------------------------------------- /connect: the providers of models
|
|
487
|
+
|
|
488
|
+
// A provider's key, checked by asking for its models with it (the header the key goes in is found on the way); asked
|
|
489
|
+
// again when refused, three times at most. Resolves with {apiKey, authHeader, listed}, or null (cancelled, refused,
|
|
490
|
+
// unreachable: said).
|
|
491
|
+
async function askProviderKey(info, existing) {
|
|
492
|
+
const base = normalizeBaseUrl(info.baseUrl, info.protocol);
|
|
493
|
+
let error = null;
|
|
494
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
495
|
+
const keep = Boolean(existing?.apiKey);
|
|
496
|
+
const typed = await app.showDialog(new TextInputDialog({
|
|
497
|
+
title: `Connect ${info.name}`,
|
|
498
|
+
body: [
|
|
499
|
+
info.keyPage ? `Make an API key on ${c.blue(info.keyPage)} and paste it here.` : `The API key for ${base}${info.keyless ? ' (none needed: Enter)' : ''}.`,
|
|
500
|
+
c.dim(`${info.protocol === 'openai' ? 'OpenAI Chat Completions' : 'Anthropic Messages API'} · ${base} · kept in ~/.claude-pro/providers.json, readable by you alone.`),
|
|
501
|
+
],
|
|
502
|
+
question: 'API key:',
|
|
503
|
+
placeholder: keep ? 'Enter: keep the saved key · or paste another (Ctrl+V)' : info.keyless ? 'Enter: no key' : 'paste the key (Ctrl+V)',
|
|
504
|
+
secret: true,
|
|
505
|
+
allowEmpty: keep || Boolean(info.keyless),
|
|
506
|
+
error,
|
|
507
|
+
}));
|
|
508
|
+
if (typed === null) { out(c.dim(`${info.name} was not connected.`)); return null; }
|
|
509
|
+
const apiKey = typed || existing?.apiKey || '';
|
|
510
|
+
try {
|
|
511
|
+
const r = await checking(`Checking the key with ${info.name}`, (signal) => listProviderModels({ ...info, apiKey }, { signal }));
|
|
512
|
+
return { apiKey, authHeader: r.authHeader, listed: r.models };
|
|
513
|
+
} catch (e) {
|
|
514
|
+
if (e.name === 'AbortError') return null;
|
|
515
|
+
if (!e.refused) { out(c.red(`Cannot reach ${info.name}: ${e.message}`)); return null; }
|
|
516
|
+
error = `${info.name} refused that key: ${e.message}`;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
out(c.red(`${info.name} was not connected: it refused the key three times.`));
|
|
520
|
+
return null;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// Connect a provider: its key, the model to use now (or none), one request to that model (the protocol, the key, the
|
|
524
|
+
// model: nothing is saved before it answers), then the connection is saved and /model switches to the model.
|
|
525
|
+
async function connectProvider(info) {
|
|
526
|
+
const existing = readConnections()[info.id];
|
|
527
|
+
const key = await askProviderKey(info, existing);
|
|
528
|
+
if (!key) return;
|
|
529
|
+
const catalogue = info.modelsDev ? await checking('Reading models.dev', (signal) => modelsDevCatalogue({ signal })).catch(() => null) : null;
|
|
530
|
+
const models = enrichModels(key.listed, catalogue, info.modelsDev);
|
|
531
|
+
const cfg = app.runtime.config;
|
|
532
|
+
const KEEP = '__keep__';
|
|
533
|
+
// ("keep" only where the model in use can be used: with nothing else connected, one of this provider's is the model)
|
|
534
|
+
const canKeep = cfg.providerConnected(cfg.model.provider) && cfg.model.provider !== info.id;
|
|
535
|
+
const choice = models.length
|
|
536
|
+
? await app.showDialog(new SelectDialog({
|
|
537
|
+
title: `Connect ${info.name} · model`,
|
|
538
|
+
question: `${canKeep ? 'Use one of its models now?' : 'Which of its models?'} (/model switches any time; its models are ${info.id}/<model>)`,
|
|
539
|
+
options: [
|
|
540
|
+
...(canKeep ? [{ label: `Keep using ${cfg.model.label}`, value: KEEP }] : []),
|
|
541
|
+
...models.map((m) => ({ label: m.id, value: m.id, description: [m.name, m.window ? `${formatTokens(m.window)} context` : '', m.price ? `$${m.price.input} / $${m.price.output} per M tokens` : ''].filter(Boolean).join(' · ') })),
|
|
542
|
+
],
|
|
543
|
+
otherOption: true,
|
|
544
|
+
}))
|
|
545
|
+
: await app.showDialog(new TextInputDialog({
|
|
546
|
+
title: `Connect ${info.name} · model`,
|
|
547
|
+
body: [`${info.name} lists no models here: name the one to use, as ${info.name} documents it.`],
|
|
548
|
+
question: 'Model:',
|
|
549
|
+
}));
|
|
550
|
+
if (choice === null || choice === undefined) { out(c.dim(`${info.name} was not connected.`)); return; }
|
|
551
|
+
// One request: to the model chosen; with "keep", to the first one listed when the endpoint is the user's own (its
|
|
552
|
+
// protocol is not known to work) or the key's header is not known yet (an Anthropic endpoint without a list).
|
|
553
|
+
let authHeader = key.authHeader;
|
|
554
|
+
let quirks = {};
|
|
555
|
+
const tryModel = choice !== KEEP ? choice : (info.custom || !authHeader) ? models[0]?.id : null;
|
|
556
|
+
if (tryModel) {
|
|
557
|
+
try {
|
|
558
|
+
({ authHeader, quirks } = await checking(`Trying ${tryModel}`, (signal) => testProviderModel({ ...info, apiKey: key.apiKey, authHeader, model: tryModel }, { signal })));
|
|
559
|
+
} catch (e) {
|
|
560
|
+
if (e.name === 'AbortError') return;
|
|
561
|
+
out(c.red(`${info.name} was not connected: ${tryModel} answered ${e.message}`));
|
|
562
|
+
return;
|
|
407
563
|
}
|
|
564
|
+
}
|
|
565
|
+
const kept = models.length ? models : choice !== KEEP ? [{ id: choice }] : [];
|
|
566
|
+
saveConnection(info.id, {
|
|
567
|
+
...(info.custom ? { custom: true, name: info.name, protocol: info.protocol, baseUrl: info.baseUrl } : {}),
|
|
568
|
+
apiKey: key.apiKey,
|
|
569
|
+
authHeader: info.protocol === 'openai' ? 'bearer' : authHeader || 'x-api-key',
|
|
570
|
+
...(Object.keys(quirks).length ? { quirks } : {}),
|
|
571
|
+
// the model chosen: the default when this provider is the first connected (see Config.defaultModelSpec)
|
|
572
|
+
...(choice !== KEEP ? { model: choice } : existing?.model ? { model: existing.model } : {}),
|
|
573
|
+
models: kept,
|
|
574
|
+
});
|
|
575
|
+
out([`${c.green('✔')} Connected ${c.bold(info.name)}${kept.length ? c.dim(` · ${kept.length} model${kept.length === 1 ? '' : 's'}`) : ''}`, c.dim(`Its models are ${info.id}/<model> in /model · /disconnect ${info.id} forgets the key.`)]);
|
|
576
|
+
if (choice !== KEEP) await commands.get('model').run(`${info.id}/${choice}`);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// A provider of the user's own: a name (what its models are named after), the address, then as a built-in one.
|
|
580
|
+
async function connectCustom(protocol) {
|
|
581
|
+
const kind = protocol === 'openai' ? 'OpenAI-compatible' : 'Anthropic-compatible';
|
|
582
|
+
const name = await app.showDialog(new TextInputDialog({
|
|
583
|
+
title: `Your own provider (${kind})`,
|
|
584
|
+
body: ['A name for it: its models are named <name>/<model> in /model (letters, digits and -).'],
|
|
585
|
+
question: 'Name:',
|
|
586
|
+
validate: (text) => {
|
|
587
|
+
const id = cleanProviderId(text);
|
|
588
|
+
if (!id) return 'Letters, digits and - only.';
|
|
589
|
+
return reservedProviderId(id) ? `"${id}" is a built-in provider: pick it from the /connect list, or give another name.` : null;
|
|
590
|
+
},
|
|
591
|
+
}));
|
|
592
|
+
if (!name) return;
|
|
593
|
+
const id = cleanProviderId(name);
|
|
594
|
+
const existing = readConnections()[id];
|
|
595
|
+
const examples = protocol === 'openai' ? ['https://api.example.com/v1', 'http://localhost:1234/v1 (LM Studio)', 'http://localhost:8000/v1 (vLLM)'] : ['https://api.example.com/anthropic'];
|
|
596
|
+
const typed = await app.showDialog(new TextInputDialog({
|
|
597
|
+
title: `${name} (${kind})`,
|
|
598
|
+
body: [`The address it takes requests at (${protocol === 'openai' ? 'POST <address>/chat/completions' : 'POST <address>/v1/messages'}), for example:`, ...examples.map((e) => c.dim(` ${e}`))],
|
|
599
|
+
question: 'Base URL:',
|
|
600
|
+
initial: existing?.baseUrl || '',
|
|
601
|
+
placeholder: 'https://…',
|
|
602
|
+
validate: (text) => (validBaseUrl(normalizeBaseUrl(text, protocol)) ? null : 'An http(s) address.'),
|
|
603
|
+
}));
|
|
604
|
+
if (!typed) return;
|
|
605
|
+
await connectProvider({ id, name: name.trim(), protocol, baseUrl: normalizeBaseUrl(typed, protocol), custom: true, keyless: true });
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
add({
|
|
609
|
+
name: 'connect',
|
|
610
|
+
argHint: '[provider]',
|
|
611
|
+
description: 'Connect a model provider with its API key: 7bit.fun, Anthropic, OpenAI, DeepSeek, Kimi, GLM, Qwen, your own…',
|
|
612
|
+
async run(args) {
|
|
613
|
+
const connections = readConnections();
|
|
614
|
+
const gatewayIn = Boolean(gatewayLogin(app.runtime.config.gatewayUrl));
|
|
615
|
+
let choice = args.trim().toLowerCase();
|
|
616
|
+
if (!choice) {
|
|
617
|
+
const mark = (on) => (on ? c.green('✔ ') : ' ');
|
|
618
|
+
const protocolName = (p) => (p === 'openai' ? 'OpenAI' : 'Anthropic');
|
|
619
|
+
choice = await app.showDialog(new SelectDialog({
|
|
620
|
+
title: 'Connect a provider',
|
|
621
|
+
question: 'Several can be connected at once (✔): their models are all in /model. Picking a connected one again replaces its key.',
|
|
622
|
+
options: [
|
|
623
|
+
{ label: `${mark(gatewayIn)}7bit.fun`, value: GATEWAY_PROVIDER, description: 'the gateway: Claude and GPT models, balance, the web page, your other computers' },
|
|
624
|
+
...PRESETS.map((p) => ({ label: `${mark(Boolean(connections[p.id]))}${p.name}`, value: p.id, description: `${protocolName(p.protocol)} protocol · ${hostOf(p.baseUrl)}` })),
|
|
625
|
+
...Object.entries(connections).filter(([, conn]) => conn?.custom).map(([id, conn]) => ({ label: `${mark(true)}${conn.name || id}`, value: id, description: `your own · ${protocolName(conn.protocol)} protocol · ${hostOf(conn.baseUrl)}` })),
|
|
626
|
+
{ label: ' Your own (Anthropic-compatible)', value: '__custom_anthropic__', description: 'any endpoint with POST /v1/messages' },
|
|
627
|
+
{ label: ' Your own (OpenAI-compatible)', value: '__custom_openai__', description: 'any endpoint with POST /chat/completions: relays, LM Studio, vLLM…' },
|
|
628
|
+
],
|
|
629
|
+
}));
|
|
630
|
+
if (!choice) return;
|
|
631
|
+
}
|
|
632
|
+
if (choice === GATEWAY_PROVIDER || choice === 'gateway' || choice === '7bit.fun') return connectGateway();
|
|
633
|
+
if (choice === '__custom_anthropic__') return connectCustom('anthropic');
|
|
634
|
+
if (choice === '__custom_openai__') return connectCustom('openai');
|
|
635
|
+
const info = providerInfo(choice, connections);
|
|
636
|
+
if (!info) { out(c.red(`There is no provider "${choice}". /connect lists them.`)); return; }
|
|
637
|
+
await connectProvider(info.custom ? { ...info, keyless: true } : info);
|
|
408
638
|
},
|
|
409
639
|
});
|
|
410
640
|
|
|
411
641
|
add({
|
|
412
|
-
name: '
|
|
413
|
-
|
|
414
|
-
|
|
642
|
+
name: 'disconnect',
|
|
643
|
+
argHint: '[provider]',
|
|
644
|
+
description: 'Forget a provider\'s key (7bit.fun\'s too: this computer\'s sessions go offline there)',
|
|
645
|
+
async run(args) {
|
|
415
646
|
const cfg = app.runtime.config;
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
647
|
+
let id = args.trim().toLowerCase();
|
|
648
|
+
if (!id) {
|
|
649
|
+
const options = connectedProviders().map((p) => ({ label: p.name, value: p.id, description: `${p.id}/<model>` }));
|
|
650
|
+
if (gatewayLogin(cfg.gatewayUrl)) options.unshift({ label: '7bit.fun', value: GATEWAY_PROVIDER, description: 'the gateway: its models, and this computer\'s sessions online there' });
|
|
651
|
+
if (!options.length) { out(c.dim('No provider is connected. /connect connects one.')); return; }
|
|
652
|
+
id = await app.showDialog(new SelectDialog({
|
|
653
|
+
title: 'Disconnect a provider',
|
|
654
|
+
question: 'Its key is forgotten, and its models cannot be used until it is connected again.',
|
|
655
|
+
options,
|
|
656
|
+
}));
|
|
657
|
+
if (!id) return;
|
|
658
|
+
}
|
|
659
|
+
if (id === GATEWAY_PROVIDER || id === 'gateway' || id === '7bit.fun') { disconnectGateway(); return; }
|
|
660
|
+
const info = providerInfo(id);
|
|
661
|
+
if (!removeConnection(id)) { out(c.dim(`${info?.name || id} is not connected.`)); return; }
|
|
662
|
+
out(`Disconnected ${info?.name || id}: its key is forgotten.${fallBack()}`);
|
|
422
663
|
},
|
|
423
664
|
});
|
|
424
665
|
|
|
@@ -435,14 +676,14 @@ export function buildCommands(app) {
|
|
|
435
676
|
row('Version', VERSION),
|
|
436
677
|
row('Session ID', app.store.id),
|
|
437
678
|
row('cwd', app.cwd),
|
|
438
|
-
row('Provider', '
|
|
679
|
+
row('Provider', `${cfg.providerName(cfg.model.provider)} ${c.dim(`(${cfg.model.provider}/…)`)}${cfg.providerConnected(cfg.model.provider) ? '' : c.red(' not connected (/connect)')}`),
|
|
439
680
|
row('Endpoint', cfg.endpointLabel),
|
|
440
|
-
row('
|
|
681
|
+
row('Connected', [...(gatewayLogin(cfg.gatewayUrl) ? [`7bit.fun ${c.dim(`(${gatewayLogin(cfg.gatewayUrl).account?.email || 'key of this machine'}; /cost shows the balance)`)}`] : []), ...connectedProviders().map((p) => p.name)].join(', ') || c.red('no provider (/connect)')),
|
|
441
682
|
row('Model', `${cfg.model.label} ${c.dim(`(sent as "${cfg.model.id}", ${formatTokens(cfg.model.contextWindow)} context)`)}`),
|
|
442
683
|
row('Effort', cfg.effort || 'auto'),
|
|
443
684
|
row('System prompt', app.flags.systemPrompt !== undefined ? 'command line override' : 'built-in default'),
|
|
444
685
|
row('Max output', formatTokens(cfg.maxOutputTokens)),
|
|
445
|
-
row('Prompt cache', cfg.promptCachingDisabled() ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.model
|
|
686
|
+
row('Prompt cache', cfg.promptCachingDisabled() ? 'off (DISABLE_PROMPT_CACHING)' : `on · TTL ${cfg.cacheTtl('main')} for the conversation, ${cfg.cacheTtl('other')} for sub-agents and compaction${cacheRefusals(cfg, cfg.model).length ? c.yellow(` · the endpoint refused: ${cacheRefusals(cfg, cfg.model).join(', ')}`) : ''}${app.runtime.systemPromptStale ? c.dim(' · memory/config changes reach the system prompt at /clear or /compact') : ''}`),
|
|
446
687
|
row('Auto-compact', `at ${formatTokens(cfg.compactWindow())} tokens (the window, less room for the summary)`),
|
|
447
688
|
row('Access', 'full (no permission prompts)'),
|
|
448
689
|
row('Checkpoints', `${app.runtime.checkpoints.list().length} (/rewind)`),
|
|
@@ -456,14 +697,14 @@ export function buildCommands(app) {
|
|
|
456
697
|
},
|
|
457
698
|
});
|
|
458
699
|
|
|
459
|
-
// /status about
|
|
460
|
-
// other computers.
|
|
700
|
+
// /status about this session's name for the other sessions, and, where 7bit.fun is connected, whether it is online
|
|
701
|
+
// there (its web page) and its name on the other computers.
|
|
461
702
|
function remoteLines(row) {
|
|
462
703
|
const cfg = app.runtime.config;
|
|
463
|
-
const remote = app.remoteState();
|
|
464
704
|
const me = app.peerLabel();
|
|
705
|
+
if (!gatewayLogin(cfg.gatewayUrl)) return [row('Name', `@${me} ${c.dim('(for the other sessions of this computer; /rename changes it)')}`)];
|
|
465
706
|
return [
|
|
466
|
-
row('Remote session',
|
|
707
|
+
row('Remote session', app.remoteState().text),
|
|
467
708
|
row('Name', `@${me} ${c.dim(`(on your other computers: @${machineName(cfg.env)}/${me}; /rename changes it)`)}`),
|
|
468
709
|
];
|
|
469
710
|
}
|
|
@@ -636,15 +877,78 @@ export function buildCommands(app) {
|
|
|
636
877
|
async run(args) {
|
|
637
878
|
const [action, ...rest] = args.split(/\s+/).filter(Boolean);
|
|
638
879
|
if (action === 'name' && rest.length) { out(`This session is now ${c.bold('@' + app.renameSession(rest.join('-')))}`); return; }
|
|
639
|
-
const { me, local, remote, online } = await app.listAllPeers();
|
|
880
|
+
const { me, local, remote, contacts = [], online } = await app.listAllPeers();
|
|
640
881
|
out([
|
|
641
882
|
`This session: ${c.bold('@' + me.name)} ${c.dim(displayPath(me.cwd, app.cwd))}${online ? c.dim(` · from other computers: @${me.label}`) : ''}`,
|
|
642
883
|
...local.map((p) => `${c.bold('@' + p.name)} ${c.dim(`${p.cwd} · pid ${p.pid}`)}`),
|
|
643
884
|
...(remote.length ? [c.dim('On your other computers, through the gateway:'), ...remote.map((p) => `${c.bold('@' + p.label)} ${c.dim(`${p.cwd}${p.busy ? ' · busy' : ''}`)}`)] : []),
|
|
644
|
-
...(
|
|
885
|
+
...(contacts.length ? [c.dim('Of your contacts (other people, /contacts):'), ...contacts.map((p) => `${c.bold('@' + p.label)}${p.busy ? c.dim(' · busy') : ''}`)] : []),
|
|
886
|
+
...(local.length || remote.length || contacts.length ? [] : [c.dim('No other session is running.')]),
|
|
645
887
|
c.dim(online
|
|
646
888
|
? 'Type "@" for the combined file/session list, "@name task" to send a task; its answer is shown here. On another computer: "@computer/name task", or "@computer task" when it runs one session. /rename names this session. The agent can use ListPeers / MessagePeer too.'
|
|
647
|
-
: 'Type "@" for the combined file/session list, "@name task" to send a task; its answer is shown here. Sessions on your other computers show up here once this one is online at the gateway (/
|
|
889
|
+
: 'Type "@" for the combined file/session list, "@name task" to send a task; its answer is shown here. Sessions on your other computers show up here once this one is online at the gateway (/connect 7bit.fun; /status says why it is not).'),
|
|
890
|
+
]);
|
|
891
|
+
},
|
|
892
|
+
});
|
|
893
|
+
|
|
894
|
+
add({
|
|
895
|
+
name: 'rc',
|
|
896
|
+
aliases: ['remote-control'],
|
|
897
|
+
argHint: '[off]',
|
|
898
|
+
description: 'Remote control: the gateway\'s web page (远程控制) shows this session and can steer it; /rc off stops that',
|
|
899
|
+
async run(args) {
|
|
900
|
+
const off = /^(off|stop|0|false|no)$/i.test(args.trim());
|
|
901
|
+
if (!off && app.remoteControl && app.remote?.rc) { out(`Remote control is on already: ${c.dim('/rc off turns it off.')}`); return; }
|
|
902
|
+
const said = await app.setRemoteControl(!off);
|
|
903
|
+
out(off ? c.dim(said) : said);
|
|
904
|
+
},
|
|
905
|
+
});
|
|
906
|
+
|
|
907
|
+
// 通讯录 at the gateway: other people's accounts whose claude-pro sessions and this account's may send each other
|
|
908
|
+
// tasks, once both sides agreed. Each account has a public 通讯号 (handle) that the others add it by.
|
|
909
|
+
const CONTACT_LABELS = { incoming: c.yellow('asks to be your contact'), outgoing: c.dim('waiting for them to accept'), accepted: c.green('contact'), blocked: c.red('blocked') };
|
|
910
|
+
add({
|
|
911
|
+
name: 'contacts',
|
|
912
|
+
argHint: '[add|accept|reject|remove|block|trust|handle] [通讯号] [auto|confirm]',
|
|
913
|
+
description: 'Your contacts at the gateway: other people whose claude-pro sessions and yours may send each other tasks once both agree',
|
|
914
|
+
async run(args) {
|
|
915
|
+
const [action = '', handle = '', extra = ''] = args.trim().split(/\s+/).filter(Boolean).map((s, i) => (i === 0 ? s.toLowerCase() : s));
|
|
916
|
+
const remote = await app.syncRemote();
|
|
917
|
+
if (!remote?.registered) { out(c.red(`Contacts live at the gateway, and this session is not online there: ${app.remoteState().text}`)); return; }
|
|
918
|
+
const actions = ['add', 'accept', 'reject', 'remove', 'block', 'trust', 'handle'];
|
|
919
|
+
if (action && !actions.includes(action)) { out(c.red(`Unknown action "${action}". /contacts ${actions.join('|')} 通讯号`)); return; }
|
|
920
|
+
if (action && !handle) { out(c.red(`/contacts ${action} needs a 通讯号${action === 'handle' ? ' (your new one)' : ''}.`)); return; }
|
|
921
|
+
const trust = extra.toLowerCase() || 'auto';
|
|
922
|
+
if (action === 'trust' && !['auto', 'confirm'].includes(trust)) { out(c.red('/contacts trust 通讯号 auto (their tasks run without asking) or confirm (each one is asked).')); return; }
|
|
923
|
+
let data;
|
|
924
|
+
try {
|
|
925
|
+
data = await remote.contacts(action, action === 'trust' ? { handle, trust } : action ? { handle } : undefined);
|
|
926
|
+
} catch (e) {
|
|
927
|
+
out(c.red(e.status === 404 && !action ? `The gateway ${remote.base} has no contacts yet (${e.message}).` : e.message));
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
const done = {
|
|
931
|
+
add: `Asked ${handle}: once they accept, your sessions can send each other tasks.`,
|
|
932
|
+
accept: `${handle} is your contact now.`,
|
|
933
|
+
reject: `Declined ${handle}.`,
|
|
934
|
+
remove: `${handle} is no longer in your contacts.`,
|
|
935
|
+
block: `Blocked ${handle}: they cannot ask you nor send your sessions tasks.`,
|
|
936
|
+
trust: trust === 'auto' ? `Tasks from ${handle} run without asking now.` : `Each task from ${handle} is asked about now.`,
|
|
937
|
+
handle: `Your 通讯号 is ${data.handle} now.`,
|
|
938
|
+
}[action];
|
|
939
|
+
const added = action === 'add' && data.contacts?.find((x) => x.handle === handle.toLowerCase().replace(/^@/, ''))?.status === 'accepted';
|
|
940
|
+
if (done) out(c.green('✔ ') + (added ? `${handle} had asked you already: you are contacts now.` : done));
|
|
941
|
+
if (action === 'accept' || action === 'remove' || action === 'block' || added) app.refreshRemotePeers();
|
|
942
|
+
if (action && action !== 'handle') return;
|
|
943
|
+
const rows = Array.isArray(data.contacts) ? data.contacts : [];
|
|
944
|
+
out([
|
|
945
|
+
`Your 通讯号: ${c.bold(data.handle)} ${c.dim('(the name others add you by; /contacts handle NEW changes it)')}`,
|
|
946
|
+
...rows.map((x) => {
|
|
947
|
+
const online = x.status === 'accepted' ? c.dim(` · ${x.online ? `${x.online} session${x.online === 1 ? '' : 's'} online` : 'no session online'} · tasks: ${x.trust === 'auto' ? 'run without asking' : 'asked about each time'}`) : '';
|
|
948
|
+
return ` ${c.bold(x.handle)} ${CONTACT_LABELS[x.status] || x.status}${online}`;
|
|
949
|
+
}),
|
|
950
|
+
...(rows.length ? [] : [c.dim(' No contacts yet.')]),
|
|
951
|
+
c.dim('/contacts add 通讯号 asks someone; accept / reject / remove / block 通讯号; trust 通讯号 auto|confirm. A contact sees only the name, computer and state of your online sessions; their tasks are asked about here before they run, unless you set trust to auto. In /peers their sessions show as @通讯号:computer/name.'),
|
|
648
952
|
]);
|
|
649
953
|
},
|
|
650
954
|
});
|
|
@@ -867,7 +1171,9 @@ export function buildCommands(app) {
|
|
|
867
1171
|
`${c.green('✔')} Node ${process.versions.node}`,
|
|
868
1172
|
`${app.runtime.shell.kind === 'bash' ? c.green('✔') : c.yellow('!')} Shell: ${app.runtime.shell.name} (${app.runtime.shell.path})`,
|
|
869
1173
|
`${rg ? c.green('✔') : c.yellow('!')} ripgrep ${rg ? 'found' : 'not found (Grep uses the built-in JS scanner, which is slower; set CLAUDE_PRO_RIPGREP_PATH to use an rg.exe)'}`,
|
|
870
|
-
|
|
1174
|
+
...(gatewayLogin(cfg.gatewayUrl) ? [`${c.green('✔')} 7bit.fun connected ${c.dim(`(7bit/…, ${cfg.gatewayUrl})`)}`] : []),
|
|
1175
|
+
...connectedProviders().map((p) => `${c.green('✔')} ${p.name} connected ${c.dim(`(${p.id}/…, ${normalizeBaseUrl(p.connection.baseUrl || p.baseUrl, p.protocol)})`)}`),
|
|
1176
|
+
...(cfg.providerConnected(cfg.model.provider) ? [] : [`${c.red('✘')} ${cfg.model.label} is a model of ${cfg.providerName(cfg.model.provider)}, which is not connected (/connect)`]),
|
|
871
1177
|
];
|
|
872
1178
|
out(lines);
|
|
873
1179
|
app.busy = true;
|