@yanzc/claude-pro 0.7.1 → 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/src/background.js CHANGED
@@ -8,8 +8,11 @@
8
8
  // - otherwise it crashed: opened again with --resume (the same conversation, the same id at the gateway), at most
9
9
  // MAX_CRASHES times in CRASH_WINDOW_MS, then failed (with the end of its log as the error);
10
10
  // - CONFIG_DIR/host-sessions.json keeps the sessions to open again when the service starts (after a reboot, or a
11
- // new version of the service): one still running (the same boot, its supervisor alive) is taken over, the others
12
- // are opened again with --resume. A task that was running is not continued: the conversation is.
11
+ // new version of the service): one still running is taken over, the others are opened again with --resume. A task
12
+ // that was running is not continued: the conversation is.
13
+ // - Whether a session runs is told by the processes themselves (liveSessionProcesses: those started with --headless
14
+ // --remote-id <id>), not by a pid kept from before: a session is never opened while a process of it runs, and
15
+ // copies that should not be there (two supervisors of one id) are ended, the one the service knew kept.
13
16
  //
14
17
  // Each session's output (its log: what it printed, as plain text, and the errors of its processes) goes to
15
18
  // CONFIG_DIR/logs/sessions/<id>.log, cut down to LOG_BYTES (copied to .log.1 first) once a minute.
@@ -19,7 +22,6 @@
19
22
  // (POST /control: exit, restart).
20
23
 
21
24
  import fs from 'node:fs';
22
- import os from 'node:os';
23
25
  import path from 'node:path';
24
26
  import { spawn, spawnSync } from 'node:child_process';
25
27
  import { listPeers, controlPeer } from './peers.js';
@@ -39,8 +41,50 @@ export function pidAlive(pid) {
39
41
  try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
40
42
  }
41
43
 
42
- // When this computer started (ms, to the minute): a pid saved before a reboot means nothing after it.
43
- export const bootTime = () => Math.round((Date.now() - os.uptime() * 1000) / 60_000) * 60_000;
44
+ // The processes of background sessions running now, by their id at the gateway: Map id -> {supervisors, sessions}
45
+ // ([{pid, ppid}] each): the processes started with --headless --remote-id <id> (bin/claude-pro.js runs the
46
+ // supervisor, which runs the session with the same arguments). A supervisor is one whose parent is not one of them;
47
+ // a session without its supervisor (killed) is in `sessions` alone. Read from the system's list of processes.
48
+ export function liveSessionProcesses() {
49
+ let rows = [];
50
+ try {
51
+ if (process.platform === 'win32') {
52
+ const script = [
53
+ '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
54
+ // a tab between the fields: "`t" in a string of double quotes
55
+ "Get-CimInstance Win32_Process -Filter \"CommandLine LIKE '%--headless%'\" | ForEach-Object { \"{0}`t{1}`t{2}\" -f $_.ProcessId, $_.ParentProcessId, $_.CommandLine }",
56
+ ].join('\n');
57
+ const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { windowsHide: true, encoding: 'utf8', timeout: 30_000 });
58
+ rows = String(r.stdout || '').split(/\r?\n/).filter(Boolean).map((l) => { const [pid, ppid, ...rest] = l.split('\t'); return { pid: Number(pid), ppid: Number(ppid), args: rest.join('\t') }; });
59
+ } else if (process.platform === 'linux') {
60
+ for (const d of fs.readdirSync('/proc')) {
61
+ if (!/^\d+$/.test(d)) continue;
62
+ try {
63
+ const args = fs.readFileSync(`/proc/${d}/cmdline`, 'utf8').split('\0').join(' ');
64
+ if (!args.includes('--headless')) continue;
65
+ const stat = fs.readFileSync(`/proc/${d}/stat`, 'utf8');
66
+ rows.push({ pid: Number(d), ppid: Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]), args });
67
+ } catch { /* gone meanwhile */ }
68
+ }
69
+ } else {
70
+ const r = spawnSync('ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8', timeout: 30_000 });
71
+ rows = String(r.stdout || '').split('\n').map((l) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(l)).filter(Boolean).map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), args: m[3] }));
72
+ }
73
+ } catch { /* nothing known: nothing taken for running */ }
74
+ const byId = new Map();
75
+ for (const row of rows) {
76
+ const id = /--remote-id\s+"?([A-Za-z0-9_-]{8,64})/.exec(row.args)?.[1];
77
+ if (!id || !/--headless/.test(row.args) || row.pid === process.pid) continue;
78
+ if (!byId.has(id)) byId.set(id, []);
79
+ byId.get(id).push({ pid: row.pid, ppid: row.ppid });
80
+ }
81
+ const out = new Map();
82
+ for (const [id, list] of byId) {
83
+ const pids = new Set(list.map((p) => p.pid));
84
+ out.set(id, { supervisors: list.filter((p) => !pids.has(p.ppid)), sessions: list.filter((p) => pids.has(p.ppid)) });
85
+ }
86
+ return out;
87
+ }
44
88
 
45
89
  // Where a background session says it ended for good (see App.exit): the service reads and removes it.
46
90
  export const endedMarker = (dir, id) => path.join(dir, 'background-ended', id);
@@ -95,6 +139,7 @@ export class BackgroundSessions {
95
139
  // The sessions saved by the service before: taken over when they still run, opened again when not.
96
140
  start() {
97
141
  let saved = [];
142
+ let live = null; // the processes of the sessions running now, read once
98
143
  try { saved = JSON.parse(fs.readFileSync(this.file, 'utf8')); } catch { /* none */ }
99
144
  for (const s of Array.isArray(saved) ? saved : []) {
100
145
  if (!s || !ID.test(String(s.sessionId || '')) || typeof s.cwd !== 'string') continue;
@@ -102,11 +147,9 @@ export class BackgroundSessions {
102
147
  this.sessions.set(rec.sessionId, rec);
103
148
  if (s.state === 'failed') { rec.state = 'failed'; rec.error = s.error || null; continue; }
104
149
  if (s.suspended) { rec.suspended = true; rec.state = 'exited'; continue; }
105
- if (s.boot === bootTime() && pidAlive(s.pid)) {
106
- rec.pid = s.pid;
107
- rec.state = 'running';
150
+ live ??= liveSessionProcesses();
151
+ if (this.adopt(rec, live.get(rec.sessionId), s.pid)) {
108
152
  rec.startedAt = s.startedAt || null;
109
- this.log(`took over the background session ${rec.sessionId} (pid ${rec.pid}) in ${rec.cwd}`);
110
153
  } else {
111
154
  this.log(`opening the background session ${rec.sessionId} again in ${rec.cwd}`);
112
155
  this.launch(rec, { resume: true });
@@ -144,10 +187,10 @@ export class BackgroundSessions {
144
187
  error: null,
145
188
  restarts: 0,
146
189
  crashes: [],
147
- boot: null,
148
190
  stopping: false,
149
191
  restartFrom: null,
150
192
  suspended: false,
193
+ attached: 0, // terminals attached to it (claude-pro attach, a window the page opened)
151
194
  };
152
195
  }
153
196
 
@@ -163,7 +206,35 @@ export class BackgroundSessions {
163
206
  return { pid: rec.pid };
164
207
  }
165
208
 
209
+ // Take over the session `rec` when processes of it run (`found`: an entry of liveSessionProcesses): its supervisor,
210
+ // the one with pid `prefer` when there are several (the others, copies that should not be there, are ended);
211
+ // without one, the session process itself (its supervisor was killed: it ends one day, and is then opened again).
212
+ // Returns whether there was one to take over.
213
+ adopt(rec, found, prefer = null) {
214
+ const heads = found?.supervisors?.length ? found.supervisors : found?.sessions || [];
215
+ if (!heads.length) return false;
216
+ const keep = heads.find((p) => p.pid === prefer) || heads.find((p) => p.pid === rec.pid) || heads[heads.length - 1];
217
+ for (const p of heads) {
218
+ if (p === keep) continue;
219
+ this.log(`the background session ${rec.sessionId} ran twice: ended the copy with pid ${p.pid}, kept ${keep.pid}`);
220
+ killTree(p.pid);
221
+ }
222
+ rec.pid = keep.pid;
223
+ rec.child = null;
224
+ rec.state = 'running';
225
+ rec.suspended = false;
226
+ this.log(`took over the background session ${rec.sessionId} (pid ${rec.pid}) in ${rec.cwd}`);
227
+ return true;
228
+ }
229
+
230
+ // Start the session's processes; with `resume` (opened again: after a crash, a restart of the service, a login)
231
+ // only when none of them runs (see adopt): opening it again then would make two copies of one session.
166
232
  launch(rec, { resume = false, first = false } = {}) {
233
+ if (resume && this.adopt(rec, liveSessionProcesses().get(rec.sessionId))) {
234
+ this.persist();
235
+ this.onChange();
236
+ return;
237
+ }
167
238
  const args = [this.entry, '--headless', '--remote-id', rec.sessionId];
168
239
  if (resume && rec.conversationId) args.push('--resume', rec.conversationId);
169
240
  if (first && rec.name) args.push('--name', rec.name);
@@ -184,7 +255,6 @@ export class BackgroundSessions {
184
255
  rec.endedAt = null;
185
256
  rec.exitCode = null;
186
257
  rec.error = null;
187
- rec.boot = bootTime();
188
258
  rec.stopping = false;
189
259
  rec.suspended = false;
190
260
  child.on('error', (e) => {
@@ -273,6 +343,9 @@ export class BackgroundSessions {
273
343
  rec.state = 'running';
274
344
  changed = true;
275
345
  }
346
+ // the terminals attached to it (none while it is not in the registry: starting, restarting)
347
+ const attached = Number(p?.attached) || 0;
348
+ if (rec.attached !== attached) { rec.attached = attached; changed = true; }
276
349
  // one taken over from an earlier service has no child process here: its pid tells
277
350
  if (!rec.child && rec.state !== 'restarting' && !pidAlive(rec.pid)) this.gone(rec, null);
278
351
  }
@@ -366,6 +439,22 @@ export class BackgroundSessions {
366
439
  this.onChange();
367
440
  }
368
441
 
442
+ // The conversation `conversationId` deleted: the sessions that are not running and had it (failed, suspended,
443
+ // ended) are forgotten, so that it is not opened again. Returns their logs (they hold its text), to delete too.
444
+ forgetConversation(conversationId) {
445
+ const logs = [];
446
+ for (const rec of [...this.sessions.values()]) {
447
+ if (rec.conversationId !== conversationId || this.alive(rec)) continue;
448
+ this.sessions.delete(rec.sessionId);
449
+ logs.push(this.logFile(rec.sessionId));
450
+ }
451
+ for (const e of this.ended.filter((x) => x.conversationId === conversationId)) logs.push(this.logFile(e.sessionId));
452
+ this.ended = this.ended.filter((x) => x.conversationId !== conversationId);
453
+ this.persist();
454
+ this.onChange();
455
+ return logs.flatMap((f) => [f, `${f}.1`]);
456
+ }
457
+
369
458
  // The conversation `conversationId` already open in a session of this computer (a background one, or a terminal):
370
459
  // its entry in the registry.
371
460
  openConversation(conversationId) {
@@ -398,6 +487,7 @@ export class BackgroundSessions {
398
487
  exitCode: rec.exitCode,
399
488
  error: rec.error,
400
489
  restarts: rec.restarts,
490
+ attached: rec.attached || 0,
401
491
  };
402
492
  }
403
493
 
@@ -409,7 +499,7 @@ export class BackgroundSessions {
409
499
  persist() {
410
500
  const list = [...this.sessions.values()].map((r) => ({
411
501
  sessionId: r.sessionId, cwd: r.cwd, name: r.name, conversationId: r.conversationId, model: r.model,
412
- pid: r.pid, boot: r.boot, startedAt: r.startedAt, state: r.state === 'failed' ? 'failed' : undefined, error: r.state === 'failed' ? r.error : undefined,
502
+ pid: r.pid, startedAt: r.startedAt, state: r.state === 'failed' ? 'failed' : undefined, error: r.state === 'failed' ? r.error : undefined,
413
503
  suspended: r.suspended || undefined,
414
504
  }));
415
505
  try {
@@ -15,7 +15,8 @@ export class CheckpointStore {
15
15
  // dir: where snapshot files are kept (created lazily).
16
16
  constructor(dir) {
17
17
  this.dir = dir;
18
- // {id, label, time, messageIndex, conversationValid, orphaned, files: [{path, existed, snap, skipped}]}
18
+ // {id, label, time, messageIndex, conversation, conversationValid, orphaned, files: [{path, existed, snap, skipped}]}
19
+ // (conversation: the id of the conversation it belongs to, so that deleting the conversation finds it)
19
20
  this.entries = [];
20
21
  this.counter = 0;
21
22
  this.current = null;
@@ -23,12 +24,13 @@ export class CheckpointStore {
23
24
 
24
25
  // Start a checkpoint for a new user prompt. messageIndex is where its message will sit in
25
26
  // the conversation, so rewinding the conversation can cut it off there.
26
- beginTurn({ label, messageIndex }) {
27
+ beginTurn({ label, messageIndex, conversation = null }) {
27
28
  const entry = {
28
29
  id: ++this.counter,
29
30
  label: String(label || '').replace(/\s+/g, ' ').trim().slice(0, 200),
30
31
  time: Date.now(),
31
32
  messageIndex,
33
+ conversation,
32
34
  conversationValid: true,
33
35
  orphaned: false,
34
36
  files: [],
package/src/commands.js CHANGED
@@ -6,9 +6,7 @@ import { c, padEnd, truncate } from './ui/ansi.js';
6
6
  import { SelectDialog } from './ui/dialogs.js';
7
7
  import { renderTodos, resultLines, formatTokens, formatDuration } from './ui/render.js';
8
8
  import { loadConfig, settingsFiles, updateSettingsFile, rememberChoice, applyRememberedChoices, KNOWN_KEYS, VERSION, APP_NAME, CONFIG_DIR } from './config.js';
9
- import { loginWithBrowser, readGatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
10
- import { codexLoginSummary, codexModels, codexEfforts } from './codex/client.js';
11
- import { readClaudeCodeLogin } from './claude-code.js';
9
+ import { loginWithBrowser, readGatewayLogin, gatewayLogin, clearGatewayLogin, fetchGatewayAccount, fetchGatewayModels, cachedGatewayModel, gatewayEfforts, formatUsd } from './gateway.js';
12
10
  import { SessionStore } from './session.js';
13
11
  import { memoryFiles, listAutoMemories } from './context.js';
14
12
  import { INIT_PROMPT } from './prompts.js';
@@ -25,13 +23,11 @@ import { describeHost, normalizeDir } from './host.js';
25
23
 
26
24
  const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
27
25
  const isGpt = (modelId) => /^gpt-/i.test(modelId);
28
- // The levels /effort offers for a model: Claude's own (as in Claude Code); for a GPT model the gateway's metadata,
29
- // else the local Codex cache; EFFORTS for other models (an Anthropic-compatible API may take any of them).
26
+ // The levels /effort offers for a gateway model: use its advertised levels when available.
30
27
  const effortLevels = (modelId, modelInfo = null) => {
31
28
  if (/^claude-/i.test(modelId)) return CLAUDE_EFFORTS;
32
29
  const remote = gatewayEfforts(modelInfo);
33
- if (remote.length) return remote;
34
- return isGpt(modelId) && codexEfforts(modelId).length ? codexEfforts(modelId) : EFFORTS;
30
+ return remote.length ? remote : EFFORTS;
35
31
  };
36
32
 
37
33
  // What /model offers (and the remote page, see App.remoteOptions): [{value, label, description}] in plain text, the
@@ -40,15 +36,10 @@ const effortLevels = (modelId, modelInfo = null) => {
40
36
  export async function modelChoices(cfg) {
41
37
  const configured = cfg.configuredModelSpec;
42
38
  const opts = [{ value: 'default', label: 'Default', description: `${configured} → ${cfg.resolveModel(configured).id}` }];
43
- if (cfg.usesCodex) {
44
- // The models the local Codex install lists.
45
- for (const m of codexModels({ ...process.env, ...cfg.env }).models.filter((x) => !x.hidden)) opts.push({ value: m.slug, label: m.slug, description: m.contextWindow ? `${formatTokens(m.contextWindow)} context` : '' });
46
- } else {
47
- opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
48
- }
39
+ opts.push(...['opus', 'sonnet', 'haiku'].map((a) => ({ value: a, label: a, description: `→ ${cfg.resolveModel(cfg.aliasTarget(a)).label}` })));
49
40
  if (cfg.usesGateway) {
50
41
  // The other models the gateway serves (Fable, the GPT models, …); without an answer, gpt-6.1-sol.
51
- const login = readGatewayLogin(cfg.gatewayUrl);
42
+ const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
52
43
  let served = null;
53
44
  try { if (login) served = await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) }); } catch { /* offline: the fallback below */ }
54
45
  const aliased = new Set(['opus', 'sonnet', 'haiku'].map((a) => cfg.resolveModel(cfg.aliasTarget(a)).id));
@@ -57,7 +48,6 @@ export async function modelChoices(cfg) {
57
48
  opts.push({ value: m.id, label: m.id, description: isGpt(m.id) ? 'OpenAI, through the gateway\'s Codex login' : m.display_name || '' });
58
49
  }
59
50
  }
60
- if (cfg.provider === 'api' && cfg.env.CLAUDE_CODE_SUBAGENT_MODEL) opts.push({ value: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, label: cfg.env.CLAUDE_CODE_SUBAGENT_MODEL, description: 'sub-agent model' });
61
51
  return opts;
62
52
  }
63
53
 
@@ -67,7 +57,7 @@ export async function effortChoices(cfg) {
67
57
  const id = cfg.mainModel.id;
68
58
  let info = null;
69
59
  if (cfg.usesGateway && isGpt(id)) {
70
- const login = readGatewayLogin(cfg.gatewayUrl);
60
+ const login = gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
71
61
  try { if (login) info = (await fetchGatewayModels(login, { signal: AbortSignal.timeout(4000) })).find((m) => m.id === id) || null; } catch { /* use local cache or generic levels */ }
72
62
  }
73
63
  const levels = effortLevels(id, info);
@@ -106,7 +96,6 @@ export function buildCommands(app) {
106
96
  cfg.env = fresh.env;
107
97
  cfg.sources = fresh.sources;
108
98
  cfg.settings = fresh.settings;
109
- cfg.ignoredFromDotEnv = fresh.ignoredFromDotEnv;
110
99
  // What the system prompt is built from may have changed (memory switched off, say). It is not rebuilt in the
111
100
  // middle of a conversation, which would lose its prompt cache; it is, at the next /clear or compaction. A
112
101
  // different model is the exception: the prompt names it, and the new model has a cache of its own anyway.
@@ -135,7 +124,7 @@ export function buildCommands(app) {
135
124
  description: 'Show help and available commands',
136
125
  run() {
137
126
  const lines = [
138
- c.bold(`${APP_NAME} v${VERSION}`) + c.dim(' — a Claude Code style coding agent'),
127
+ c.bold(`${APP_NAME} v${VERSION}`) + c.dim(' — a command line coding agent'),
139
128
  '',
140
129
  'Always review the agent\'s changes before committing them.',
141
130
  '',
@@ -278,7 +267,6 @@ export function buildCommands(app) {
278
267
  if (v === undefined) continue;
279
268
  lines.push(`${padEnd(k, 34)} ${c.bold(v)} ${c.dim(cfg.sources[k] || '')}`);
280
269
  }
281
- if (cfg.ignoredFromDotEnv.length) lines.push('', c.dim(`Not applied from .env with the claude-code provider (it is the API provider's setup; Claude Code's defaults are used instead): ${cfg.ignoredFromDotEnv.join(', ')}. Set them with /config set or /effort to apply them here.`));
282
270
  lines.push('', c.dim('Other keys: ' + Object.keys(KNOWN_KEYS).filter((k) => cfg.env[k] === undefined).join(', ')));
283
271
  lines.push('', `${c.dim('Change with')} /config set KEY VALUE [--project|--local] ${c.dim('or edit')} ${settingsFiles(app.cwd).user}`);
284
272
  log(lines, '');
@@ -312,7 +300,7 @@ export function buildCommands(app) {
312
300
  name: 'effort',
313
301
  get argHint() {
314
302
  const cfg = app.runtime.config;
315
- const login = cfg.usesGateway ? readGatewayLogin(cfg.gatewayUrl) : null;
303
+ const login = cfg.usesGateway ? gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) : null;
316
304
  return `[${effortLevels(cfg.mainModel.id, cachedGatewayModel(login, cfg.mainModel.id)).join('|')}|auto|default]`;
317
305
  },
318
306
  description: 'Set reasoning effort (output_config.effort; kept for later sessions)',
@@ -345,7 +333,7 @@ export function buildCommands(app) {
345
333
  },
346
334
  });
347
335
 
348
- // Switch the provider (kept in the user settings) and take up its own remembered /model and /effort.
336
+ // Keep the gateway selection in the user settings and apply its remembered /model and /effort.
349
337
  const switchProvider = (provider) => {
350
338
  const cfg = app.runtime.config;
351
339
  const files = settingsFiles(app.cwd);
@@ -381,50 +369,13 @@ export function buildCommands(app) {
381
369
 
382
370
  add({
383
371
  name: 'login',
384
- argHint: '[claude|gateway|codex]',
385
- description: 'Choose where model requests go: the Claude subscription, the codex-gateway account (browser login), or the Codex subscription',
372
+ argHint: '[gateway]',
373
+ description: 'Log in to the codex-gateway account in your browser',
386
374
  async run(args) {
387
375
  const cfg = app.runtime.config;
388
- let choice = args.trim().toLowerCase();
389
- if (choice === 'claude') choice = 'claude-code';
390
- if (!choice) {
391
- const saved = readGatewayLogin(cfg.gatewayUrl);
392
- const codex = codexLoginSummary({ ...process.env, ...cfg.env });
393
- choice = await app.showDialog(new SelectDialog({
394
- title: 'Log in',
395
- question: `Now: ${c.bold(cfg.provider)} (${cfg.endpointLabel})`,
396
- options: [
397
- { label: `Gateway ${cfg.gatewayUrl} ${c.dim(saved ? `(logged in as ${saved.account?.email || 'this machine'}; paid from the account balance)` : '(log in in the browser; paid from the account balance)')}`, value: 'gateway' },
398
- { label: `Claude subscription ${c.dim('(the local Claude Code login)')}`, value: 'claude-code' },
399
- { label: `Codex subscription ${c.dim(codex.ok ? `(the local Codex login${codex.plan ? `, ${codex.plan}` : ''})` : '(run `codex login` first)')}`, value: 'codex' },
400
- ],
401
- }));
402
- if (!choice) return;
403
- }
404
- if (!['claude-code', 'gateway', 'codex'].includes(choice)) { out(c.red(`Unknown choice "${choice}". Use claude, gateway or codex.`)); return; }
405
- if (choice !== cfg.provider && !(await confirmCacheLoss('Switching the provider'))) { out(c.dim('Nothing was changed.')); return; }
406
-
407
- if (choice === 'claude-code') {
408
- try { readClaudeCodeLogin(cfg); } catch (e) {
409
- // An expired token is renewed at the first request; a missing login is not.
410
- if (!/expired/i.test(e.message)) {
411
- out(c.red(`The Claude subscription login cannot be used: ${e.message}. Log in with the official \`claude\` once, then run /login again.`));
412
- return;
413
- }
414
- }
415
- const note = switchProvider('claude-code');
416
- out(`Using the ${c.bold('Claude subscription')}: ${cfg.mainModel.label}${note}`);
417
- return;
418
- }
419
- if (choice === 'codex') {
420
- const codex = codexLoginSummary({ ...process.env, ...cfg.env });
421
- if (!codex.ok) { out(c.red(`The Codex login cannot be used: ${codex.error}`)); return; }
422
- const note = switchProvider('codex');
423
- out(`Using the ${c.bold('Codex subscription')}${codex.email ? ` (${codex.email}${codex.plan ? `, ${codex.plan}` : ''})` : ''}: ${cfg.mainModel.label}${note}`);
424
- return;
425
- }
376
+ const choice = args.trim().toLowerCase();
377
+ if (choice && choice !== 'gateway') { out(c.red(`Unknown login method "${choice}". Only gateway login is supported.`)); return; }
426
378
 
427
- // The gateway: a saved key that still works is used as it is; otherwise log in through the browser.
428
379
  const url = cfg.gatewayUrl;
429
380
  const saved = readGatewayLogin(url);
430
381
  if (saved) {
@@ -436,7 +387,7 @@ export function buildCommands(app) {
436
387
  return;
437
388
  } catch (e) {
438
389
  if (e.status !== 401 && e.status !== 403) { out(c.red(`Cannot reach the gateway ${url}: ${e.message}`)); return; }
439
- clearGatewayLogin(); // the key was revoked: log in again
390
+ clearGatewayLogin();
440
391
  }
441
392
  }
442
393
  pendingLogin?.abort();
@@ -468,8 +419,8 @@ export function buildCommands(app) {
468
419
  const wasOnline = Boolean(app.remote);
469
420
  app.stopRemote(); // the other sessions of this computer and its computer service follow within seconds
470
421
  out(had
471
- ? `Logged out of the gateway ${cfg.gatewayUrl}.${wasOnline ? ' This session is offline there now.' : ''}${cfg.usesGateway ? ' Run /login to log in again or choose another provider.' : ''}`
472
- : c.dim('There was no gateway login. (The Claude and Codex subscription logins belong to their own CLIs.)'));
422
+ ? `Logged out of the gateway ${cfg.gatewayUrl}.${wasOnline ? ' This session is offline there now.' : ''} Run /login to log in again.`
423
+ : c.dim('There was no gateway login. Run /login to log in.'));
473
424
  },
474
425
  });
475
426
 
@@ -488,10 +439,7 @@ export function buildCommands(app) {
488
439
  row('cwd', app.cwd),
489
440
  row('Provider', cfg.provider),
490
441
  row('Endpoint', cfg.endpointLabel),
491
- row('Auth', cfg.usesClaudeCode ? `existing Claude Code OAuth (${cfg.claudeCodeCredentialsFile})`
492
- : cfg.usesGateway ? (readGatewayLogin(cfg.gatewayUrl) ? `gateway key of ${readGatewayLogin(cfg.gatewayUrl).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)'))
493
- : cfg.usesCodex ? (() => { const s = codexLoginSummary({ ...process.env, ...cfg.env }); return s.ok ? `Codex login${s.email ? ` of ${s.email}` : ''}${s.plan ? ` (${s.plan})` : ''} ${c.dim(s.file)}` : c.red(s.error); })()
494
- : cfg.authToken ? `ANTHROPIC_AUTH_TOKEN (${cfg.display('ANTHROPIC_AUTH_TOKEN')})` : cfg.apiKey ? `ANTHROPIC_API_KEY (${cfg.display('ANTHROPIC_API_KEY')})` : c.red('none')),
442
+ row('Auth', gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? `gateway key of ${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY).account?.email || 'this machine'} ${c.dim('(/cost shows the balance)')}` : c.red('not logged in (/login)')),
495
443
  row('Model', `${cfg.mainModel.label} ${c.dim(`(sent as "${cfg.mainModel.id}", ${formatTokens(cfg.mainModel.contextWindow)} context)`)}`),
496
444
  row('Sub-agent model', cfg.subagentModelChosen ? `chosen per task by difficulty ${c.dim(`(haiku, sonnet or opus; not chosen: ${cfg.subagentModel.label})`)}` : cfg.subagentModel.label),
497
445
  row('Small model', cfg.smallModel.label),
@@ -544,7 +492,7 @@ export function buildCommands(app) {
544
492
  `Session time: ${formatDuration(Date.now() - app.sessionStart)}`,
545
493
  ]);
546
494
  const cfg = app.runtime.config;
547
- const saved = cfg.usesGateway && readGatewayLogin(cfg.gatewayUrl);
495
+ const saved = cfg.usesGateway && gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY);
548
496
  if (!saved) return;
549
497
  try {
550
498
  const account = await fetchGatewayAccount(saved);
@@ -665,21 +613,12 @@ export function buildCommands(app) {
665
613
  ...(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' : ''}`)}`)] : []),
666
614
  ...(local.length || remote.length ? [] : [c.dim('No other session is running.')]),
667
615
  c.dim(online
668
- ? 'Type "&" for the 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. /sendfile &name file... sends files (saved in its Downloads folder). /rename names this session. The agent can use ListPeers / MessagePeer too.'
616
+ ? 'Type "&" for the 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.'
669
617
  : 'Type "&" for the 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 (/login; /status says why it is not).'),
670
618
  ]);
671
619
  },
672
620
  });
673
621
 
674
- add({
675
- name: 'sendfile',
676
- aliases: ['sf'],
677
- argHint: '&session <file...>',
678
- argRequired: true,
679
- description: 'Send files to another session, on this computer or on another one: it saves them in its Downloads folder',
680
- async run(args) { await app.sendFiles(args); },
681
- });
682
-
683
622
  add({
684
623
  name: 'tui',
685
624
  argHint: '[fullscreen | default]',
@@ -916,11 +855,7 @@ export function buildCommands(app) {
916
855
  `${c.green('✔')} Node ${process.versions.node}`,
917
856
  `${app.runtime.shell.kind === 'bash' ? c.green('✔') : c.yellow('!')} Shell: ${app.runtime.shell.name} (${app.runtime.shell.path})`,
918
857
  `${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)'}`,
919
- cfg.usesClaudeCode
920
- ? `${c.yellow('!')} Existing Claude Code OAuth: ${cfg.claudeCodeCredentialsFile} (checked by the request below)`
921
- : cfg.usesGateway ? `${readGatewayLogin(cfg.gatewayUrl) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${readGatewayLogin(cfg.gatewayUrl) ? '' : ' missing (/login)'}`
922
- : cfg.usesCodex ? (() => { const s = codexLoginSummary({ ...process.env, ...cfg.env }); return `${s.ok ? c.green('✔') : c.red('✘')} Codex login ${s.ok ? s.file : s.error}`; })()
923
- : `${cfg.authToken || cfg.apiKey ? c.green('✔') : c.red('✘')} Credentials ${cfg.authToken ? 'ANTHROPIC_AUTH_TOKEN' : cfg.apiKey ? 'ANTHROPIC_API_KEY' : 'missing'}`,
858
+ `${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? c.green('✔') : c.red('✘')} Gateway login for ${cfg.gatewayUrl}${gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY) ? '' : ' missing (/login)'}`,
924
859
  ];
925
860
  out(lines);
926
861
  app.busy = true;