@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/ui/repl.js CHANGED
@@ -18,7 +18,7 @@ import { createRuntime } from '../runtime.js';
18
18
  import { SessionStore, firstUserText, moveSession } from '../session.js';
19
19
  import { defaultEffort, effortSupported, effortToSend, quickQuery } from '../api.js';
20
20
  import { CONFIG_DIR, VERSION, APP_NAME, INSTALL_DIR } from '../config.js';
21
- import { readGatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
21
+ import { gatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
22
22
  import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
23
23
  import { buildCommands, modelChoices, effortChoices } from '../commands.js';
24
24
  import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
@@ -29,8 +29,6 @@ import { shutdownBackgroundShells, listBackgroundShells } from '../tools/bash.js
29
29
  import { estimateTokens } from '../agent.js';
30
30
  import { readClipboardImage, imageFromFile, watchClipboard, writeClipboard, readClipboardText } from '../utils/clipboard.js';
31
31
  import { fitImagesIn, imageSize } from '../utils/images.js';
32
- import { downloadsDir, filesToSend, formatBytes } from '../utils/downloads.js';
33
- import { copyUnique } from '../transfer.js';
34
32
  import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer, CHECK_EVERY_MS } from '../updater.js';
35
33
  import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
36
34
  import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
@@ -227,8 +225,6 @@ export class App {
227
225
  this.remotePeersAt = 0;
228
226
  this.remotePeersLoading = null;
229
227
  this.remotePeersTimer = null;
230
- this.transfers = new Map(); // files on their way to or from other sessions, for the footer
231
- this.transferSeq = 0;
232
228
  this.cost = 0; // what this conversation's requests have cost so far (USD at list prices): the footer and /cost
233
229
  this.fileIndex = new FileIndex(cwd, () => this.runtime?.config);
234
230
  this.store = new SessionStore(cwd);
@@ -248,7 +244,6 @@ export class App {
248
244
  onSubmit: (value, raw, images) => { try { this.onSubmit(value, raw, images); } catch (e) { this.logError(e); } },
249
245
  onDoubleEscape: () => this.openRewind(),
250
246
  imageFromPath: (p) => {
251
- if (/^\s*\/(sendfile|sf)\b/i.test(this.editor?.text || '')) return null; // a file to send, not to show the model
252
247
  const r = imageFromFile(resolvePath(p, this.cwd));
253
248
  if (r.error && !/not found|Not a file/.test(r.error)) this.flash(r.error, 'warn');
254
249
  if (r.image) this.flashMessage = null;
@@ -269,10 +264,8 @@ export class App {
269
264
  const stdin = this.stdin;
270
265
  stdin.setRawMode(true);
271
266
  // Where the cursor is, before anything is drawn: the input box is kept on the last rows of the window from
272
- // there (see screen.js). CLAUDE_PRO_PIN_INPUT=0 (here or in the settings) leaves it right below the output.
273
- const pinOff = (v) => /^(0|false|no|off)$/i.test(v || '');
274
- if (pinOff(process.env.CLAUDE_PRO_PIN_INPUT)) this.screen.pin = false;
275
- else if (stdin.isTTY && this.stdout.isTTY && !this.headless) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
267
+ // there (see screen.js).
268
+ if (stdin.isTTY && this.stdout.isTTY && !this.headless) this.screen.pinFrom(await queryCursorRow(stdin, this.stdout));
276
269
  stdin.setEncoding('utf8');
277
270
  this.stdout.write(ESC.bracketedPasteOn);
278
271
  this.watchCopies();
@@ -292,7 +285,6 @@ export class App {
292
285
  this.screen.schedule();
293
286
  };
294
287
  this.commands = buildCommands(this);
295
- if (pinOff(this.config.env.CLAUDE_PRO_PIN_INPUT)) { this.screen.pin = false; this.screen.pinned = null; }
296
288
  // What the session showed before a restart: scrolled back to in fullscreen, repainted after a resize otherwise.
297
289
  if (Array.isArray(this.flags.restart?.screenHistory)) this.screen.history = this.flags.restart.screenHistory.filter((l) => typeof l === 'string');
298
290
  if (this.fullscreenWanted()) this.screen.setFull(true);
@@ -328,9 +320,9 @@ export class App {
328
320
  }, 120);
329
321
  if (restart) this.continueAfterRestart(restart);
330
322
  else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
331
- // Nothing configured yet: the gateway is the default, and its login comes first, as in Claude Code. (Not in a
323
+ // Nothing configured yet: the gateway is the default, and its browser login starts first. (Not in a
332
324
  // background session: nobody sits at this computer to log in in its browser.)
333
- else if (this.config.usesGateway && !readGatewayLogin(this.config.gatewayUrl) && !this.headless) {
325
+ else if (this.config.usesGateway && !gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY) && !this.headless) {
334
326
  Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
335
327
  }
336
328
  this.fileIndex.refresh();
@@ -468,7 +460,7 @@ export class App {
468
460
  id: this.flags.restart?.peerId,
469
461
  onMessage: (msg) => this.onPeerMessage(msg),
470
462
  getStatus: () => ({ busy: this.working() }),
471
- info: () => ({ kind: this.headless ? 'background' : 'terminal', remoteId: this.remote?.id || this.flags.remoteId || this.flags.restart?.remote?.id || null, conversationId: this.store.id }),
463
+ info: () => ({ kind: this.headless ? 'background' : 'terminal', remoteId: this.remote?.id || this.flags.remoteId || this.flags.restart?.remote?.id || null, conversationId: this.store.id, attached: this.vterm ? this.vterm.clients.size : 0 }),
472
464
  onControl: (body) => this.onControl(body),
473
465
  onAttach: this.headless ? (socket, size) => this.attachClient(socket, size) : null,
474
466
  }).start();
@@ -500,13 +492,24 @@ export class App {
500
492
  }
501
493
 
502
494
  // `claude-pro attach` (see attach.js) on this background session: the screen, drawn whole for it, and its keys.
503
- // From the client: one JSON object a line, {keys: base64} or {resize: [columns, rows]}.
495
+ // From the client: one JSON object a line, {keys: base64} or {resize: [columns, rows]}. A turn that runs goes on:
496
+ // the client gets the conversation as it is (scrolled back with the wheel, PgUp), the live part and what follows.
497
+ // The registry says how many are attached (the web page shows it, see background.js); one that goes away
498
+ // (detached, its window closed, its process killed) changes nothing else.
504
499
  attachClient(socket, { cols, rows } = {}) {
505
500
  const client = { write: (d) => { if (!socket.destroyed) socket.write(d); }, close: () => socket.end() };
506
501
  socket.on('error', () => { /* its close follows */ });
507
- socket.on('close', () => this.vterm.detach(client));
502
+ // An HTTP server's sockets stay half open when the other side closes (allowHalfOpen): without this, a client that
503
+ // went away (its window closed, its process killed) would count as attached until a write failed, a minute later.
504
+ socket.on('end', () => socket.destroy());
505
+ socket.on('close', () => {
506
+ this.vterm.detach(client);
507
+ this.peers?.update();
508
+ });
508
509
  this.vterm.attach(client, { cols, rows });
510
+ this.peers?.update();
509
511
  client.write(`${ATTACH_MODES}${ESC.bracketedPasteOn}`);
512
+ this.screen.title = ''; // its window gets the title too (sent again with the next draw)
510
513
  if (this.screen.full) this.screen.repaint();
511
514
  let buf = '';
512
515
  // (no setEncoding: an HTTP server's socket refuses it; the lines are ASCII anyway, JSON with base64)
@@ -544,13 +547,7 @@ export class App {
544
547
  // `target`: a peer entry, or what names one (see resolvePeer): a session on this computer, or one on another
545
548
  // computer, reached through the gateway. `byModel`: the MessagePeer tool sent it, so the answer goes to the
546
549
  // model; otherwise the user typed `@name ...` and the answer is only shown (and noted for the model).
547
- // `files`: paths of files on this computer to send along (see utils/downloads.js); the other session saves
548
- // them in its Downloads folder.
549
- //
550
- // `background`: with files, return as soon as they are checked and the session is found, and send in the
551
- // background (progress in the footer; a finished or failed sending is reported in the transcript).
552
- async sendToPeer(target, text, { byModel = false, files: paths = [], background = false } = {}) {
553
- const files = paths.length ? filesToSend(paths) : [];
550
+ async sendToPeer(target, text, { byModel = false } = {}) {
554
551
  let peer = target && typeof target === 'object' ? target : null;
555
552
  if (!peer) {
556
553
  const local = this.peers?.peers() || [];
@@ -564,80 +561,11 @@ export class App {
564
561
  }
565
562
  if (peer.remote && !this.remote) throw new Error(`&${peer.label} is on another computer, and this session is not online at the gateway (/status says why).`);
566
563
  if (!peer.remote && !this.peers) throw new Error('Talking to other sessions on this computer is off (CLAUDE_PRO_PEERS=0).');
567
- const send = async () => {
568
- let r;
569
- if (peer.remote) {
570
- const uploaded = [];
571
- if (files.length) {
572
- const job = this.startTransfer('up', files, peer);
573
- try {
574
- for (const f of files) uploaded.push(await this.remote.uploadFile(f, { signal: job.signal, onProgress: (p) => job.progress(f, p) }));
575
- } finally {
576
- job.end();
577
- }
578
- }
579
- r = { ...(await this.remote.sendPeer(peer.id, { text, files: uploaded })), peer };
580
- } else {
581
- r = await this.peers.send(peer, { text, files });
582
- }
583
- r.files = files;
584
- if (!byModel) this.userSentToPeers.add(`${r.peer.id}:${r.id}`);
585
- return r;
586
- };
587
- if (!background || !files.length) return await send();
588
- const label = peer.label || peer.name;
589
- const what = `${files.length} file${files.length === 1 ? '' : 's'} (${formatBytes(files.reduce((n, f) => n + f.size, 0))})`;
590
- send().then(
591
- () => this.screen.log(c.dim(` ⎿ Sent ${what} to &${label}; it saves them in its Downloads folder and confirms`), ''),
592
- (e) => {
593
- const why = e.name === 'AbortError'
594
- ? `Stopped sending ${what} to &${label}. Send the same files again to continue where it stopped.`
595
- : `Could not send ${what} to &${label}: ${e.message}${peer.remote ? ' (sending the same files again continues where it stopped)' : ''}`;
596
- this.notice(why, 'warn');
597
- if (byModel) this.agent.addReminder(`The files you sent with MessagePeer did not go out: ${why}`);
598
- },
599
- );
600
- return { peer, files, background: true };
601
- }
602
-
603
- // A sending or receiving of files, shown in the footer while it runs: {signal, progress(file, p), end()}.
604
- startTransfer(direction, files, peer) {
605
- const id = ++this.transferSeq;
606
- const controller = new AbortController();
607
- const total = files.reduce((n, f) => n + (Number(f.size) || 0), 0);
608
- const t = { direction, label: peer.label || peer.name, names: files.map((f) => f.name), total, done: new Map(), phase: 'starting', retryIn: 0, at: Date.now(), controller, shown: 0 };
609
- this.transfers.set(id, t);
610
- this.screen.schedule();
611
- return {
612
- signal: controller.signal,
613
- progress: (file, p) => {
614
- t.done.set(file, p.phase === 'hashing' || p.phase === 'checking' ? 0 : p.done);
615
- t.phase = p.phase;
616
- t.file = file.name;
617
- t.retryIn = p.phase === 'waiting' ? Date.now() + (p.retryIn || 0) : 0;
618
- if (p.phase === 'hashing' || p.phase === 'checking') t.hashed = p.total ? p.done / p.total : 0;
619
- if (Date.now() - t.shown > 250) { t.shown = Date.now(); this.screen.schedule(); }
620
- },
621
- end: () => { this.transfers.delete(id); this.screen.schedule(); },
622
- };
623
- }
624
-
625
- // The footer's word on the files on their way.
626
- transferStatus() {
627
- const all = [...this.transfers.values()];
628
- if (!all.length) return '';
629
- const t = all[0];
630
- const done = [...t.done.values()].reduce((n, v) => n + v, 0);
631
- const pct = t.total ? Math.floor((done / t.total) * 100) : 0;
632
- const arrow = t.direction === 'up' ? '⇡' : '⇣';
633
- const name = truncate(t.names.length === 1 ? t.names[0] : `${t.names.length} files`, 24);
634
- const where = t.direction === 'up' ? `→ &${t.label}` : `← &${t.label}`;
635
- let state;
636
- if (t.phase === 'waiting') state = c.yellow(`${pct}% · network down, retrying…`);
637
- else if (t.phase === 'hashing') state = c.dim(`preparing ${Math.floor((t.hashed || 0) * 100)}%`);
638
- else if (t.phase === 'checking') state = c.dim('checking');
639
- else state = c.dim(`${pct}% · ${formatBytes(done)}/${formatBytes(t.total)}`);
640
- return `${c.blue(`${arrow} ${name}`)} ${c.dim(where)} ${state}${all.length > 1 ? c.dim(` +${all.length - 1}`) : ''}`;
564
+ const r = peer.remote
565
+ ? { ...(await this.remote.sendPeer(peer.id, { text })), peer }
566
+ : await this.peers.send(peer, { text });
567
+ if (!byModel) this.userSentToPeers.add(`${r.peer.id}:${r.id}`);
568
+ return r;
641
569
  }
642
570
 
643
571
  // The account's sessions on other computers that are online now, from the gateway (what was known stays when
@@ -678,7 +606,6 @@ export class App {
678
606
 
679
607
  onPeerMessage(msg) {
680
608
  if (this.exiting) return;
681
- if (msg.files?.length && !msg.received) return this.receiveFiles(msg).catch((e) => this.logError(e)); // the gateway keeps the message until this is done
682
609
  const from = c.bold(`&${msg.from.name}`);
683
610
  const width = this.width - 1;
684
611
  if (msg.kind === 'reply' && this.userSentToPeers.delete(`${msg.from.id}:${msg.inReplyTo}`)) {
@@ -693,56 +620,6 @@ export class App {
693
620
  this.startTurn(item.text, { display, peers: item.peer ? [item.peer] : [] });
694
621
  }
695
622
 
696
- // Files another session sent: saved in the Downloads folder (never over a file that is there) at once, whatever
697
- // this session is doing. Files alone are answered right away with where they are, without a turn of the model;
698
- // with a task, the task runs as usual and is told where they are.
699
- async receiveFiles(msg) {
700
- msg.received = true;
701
- let dir;
702
- try { dir = await downloadsDir(this.config.env); } catch { dir = path.join(os.homedir(), 'Downloads'); }
703
- const saved = [];
704
- const failed = [];
705
- const remote = this.remote;
706
- const job = msg.from.remote ? this.startTransfer('down', msg.files, msg.from) : null;
707
- try {
708
- for (const f of msg.files) {
709
- try {
710
- let file;
711
- if (msg.from.remote) {
712
- if (!remote) throw new Error('this session is not online at the gateway');
713
- file = await remote.downloadFile(f, dir, { signal: job.signal, onProgress: (p) => job.progress(f, p) });
714
- remote.deleteFile(f.id);
715
- } else {
716
- file = await copyUnique(f.path, dir, f.name);
717
- }
718
- saved.push({ path: file, size: fs.statSync(file).size });
719
- } catch (e) {
720
- failed.push(`${f.name}: ${e.message}`);
721
- }
722
- }
723
- } finally {
724
- job?.end();
725
- }
726
- this.screen.log(
727
- `${c.blue('✉')} ${c.bold(`&${msg.from.name}`)} ${c.dim(`sent ${msg.files.length} file${msg.files.length === 1 ? '' : 's'}${saved.length ? `, saved in ${dir}:` : ':'}`)}`,
728
- ...saved.map((s) => ` ${path.basename(s.path)} ${c.dim(formatBytes(s.size))}`),
729
- ...failed.map((f) => c.red(` ✗ ${f}`)),
730
- '',
731
- );
732
- const where = `the Downloads folder of ${machineName(this.config.env)} (${dir})`;
733
- const report = [
734
- saved.length ? `Saved ${saved.length} file${saved.length === 1 ? '' : 's'} in ${where}:\n${saved.map((s) => `- ${s.path}`).join('\n')}` : '',
735
- failed.length ? `Could not save:\n${failed.map((f) => `- ${f}`).join('\n')}` : '',
736
- ].filter(Boolean).join('\n\n');
737
- if (msg.kind === 'task' && !msg.text.trim()) {
738
- this.agent.addReminder(`Another claude-pro session, ${msg.from.name}, sent files to this computer. ${report}`);
739
- this.replyToPeer(msg, report);
740
- return;
741
- }
742
- msg.text = `${msg.text}\n\n[Files that came with this message. ${report}]`;
743
- this.onPeerMessage(msg);
744
- }
745
-
746
623
  // Send `text` as the answer to `msg`, a message of another session: here, or through the gateway.
747
624
  replyToPeer(msg, text) {
748
625
  const done = () => this.screen.log(c.dim(` ⎿ Answer sent to &${msg.from.name}`));
@@ -760,48 +637,6 @@ export class App {
760
637
  this.peers.send(peer, { text, kind: 'reply', inReplyTo: msg.id }).then(done, failed);
761
638
  }
762
639
 
763
- // /sendfile &session file...: files on this computer to another session (here or on another computer), which
764
- // saves them in its Downloads folder and confirms. Paths may be quoted, @-mentions, or have spaces unquoted.
765
- async sendFiles(args) {
766
- if (/^\s*(stop|cancel)\s*$/i.test(args)) {
767
- const ups = [...this.transfers.values()].filter((t) => t.direction === 'up');
768
- for (const t of ups) t.controller.abort();
769
- this.screen.log(c.dim(ups.length ? ` ⎿ Stopping ${ups.length} sending${ups.length === 1 ? '' : 's'}` : ' ⎿ Nothing is being sent'));
770
- return;
771
- }
772
- const tokens = [...String(args).matchAll(/@?"([^"]+)"|@?'([^']+)'|(\S+)/g)].map((m) => ({ text: m[1] ?? m[2] ?? m[3], quoted: m[3] === undefined }));
773
- const targets = tokens.filter((t) => !t.quoted && /^[&&]./u.test(t.text));
774
- if (targets.length !== 1) {
775
- this.notice(targets.length ? 'Send to one session at a time.' : 'Usage: /sendfile &session file... (type & for the list of sessions)', 'warn');
776
- return;
777
- }
778
- const exists = (p) => { try { return fs.statSync(p).isFile(); } catch { return false; } };
779
- const rest = tokens.filter((t) => t !== targets[0]);
780
- const paths = [];
781
- for (let i = 0; i < rest.length;) {
782
- if (rest[i].quoted) { paths.push(resolvePath(rest[i].text, this.cwd)); i++; continue; }
783
- // the longest run of words that is a file: a path with spaces that was not quoted
784
- let j = i + 1;
785
- for (let k = rest.length; k > i + 1; k--) {
786
- if (rest.slice(i, k).some((t) => t.quoted)) continue;
787
- if (exists(resolvePath(rest.slice(i, k).map((t) => t.text).join(' ').replace(/^@/, ''), this.cwd))) { j = k; break; }
788
- }
789
- paths.push(resolvePath(rest.slice(i, j).map((t) => t.text).join(' ').replace(/^@/, ''), this.cwd));
790
- i = j;
791
- }
792
- let files;
793
- try { files = filesToSend(paths); } catch (e) { this.notice(e.message, 'warn'); return; }
794
- const total = files.reduce((n, f) => n + f.size, 0);
795
- const what = `${files.length} file${files.length === 1 ? '' : 's'} (${formatBytes(total)})`;
796
- try {
797
- const r = await this.sendToPeer(targets[0].text, '', { files: paths, background: true });
798
- const label = r.peer.label || r.peer.name;
799
- this.screen.log(c.dim(` ⎿ Sending ${what} to &${label} in the background (progress below; /sendfile stop stops it${r.peer.remote ? ', and sending the same files again later continues where it stopped' : ''})`));
800
- } catch (e) {
801
- this.notice(`Could not send the files: ${e.message}`, 'warn');
802
- }
803
- }
804
-
805
640
  // The turn that handled tasks of other sessions ended: send each its answer.
806
641
  answerPeers(result, error) {
807
642
  const tasks = this.turnPeers.splice(0);
@@ -837,7 +672,7 @@ export class App {
837
672
  const env = this.config.env;
838
673
  if (!onlineEnabled(env)) return false;
839
674
  if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
840
- return Boolean(readGatewayLogin(this.config.gatewayUrl));
675
+ return Boolean(gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY));
841
676
  }
842
677
 
843
678
  // Online at the gateway from the start, without holding the start up: when this computer is logged in to it; with
@@ -854,9 +689,9 @@ export class App {
854
689
  }
855
690
 
856
691
  // Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
857
- // computers reach it from then on. Needs the gateway login of /login (the provider of the model requests can be
858
- // another one); throws {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried
859
- // again in the background; one that refuses the key throws, and that key is not tried again (see syncRemote).
692
+ // computers reach it from then on. Needs the gateway login from /login or CLAUDE_PRO_GATEWAY_API_KEY; throws
693
+ // {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried again in the background;
694
+ // one that refuses the key throws, and that key is not tried again (see syncRemote).
860
695
  startRemote({ id } = {}) {
861
696
  if (this.remote) return Promise.resolve(this.remote);
862
697
  this.remoteStarting ??= this.connectRemote({ id }).finally(() => { this.remoteStarting = null; });
@@ -868,7 +703,7 @@ export class App {
868
703
  syncRemote() {
869
704
  if (this.exiting) return Promise.resolve(null);
870
705
  if (this.remoteStarting) return this.remoteStarting.catch(() => null);
871
- const login = readGatewayLogin(this.config.gatewayUrl);
706
+ const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
872
707
  const r = this.remote;
873
708
  // logged out, or another account: not this account's session any more
874
709
  if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
@@ -886,7 +721,7 @@ export class App {
886
721
  ensureHost({ login = false } = {}) {
887
722
  const env = this.config.env;
888
723
  if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
889
- if (!onlineEnabled(env) || !hostEnabled(env) || !readGatewayLogin(this.config.gatewayUrl)) return;
724
+ if (!onlineEnabled(env) || !hostEnabled(env) || !gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY)) return;
890
725
  try { startHostIfNeeded(); } catch { /* the next session tries again */ }
891
726
  try {
892
727
  const auto = ensureAutostart({ force: login, env });
@@ -895,7 +730,7 @@ export class App {
895
730
  }
896
731
 
897
732
  async connectRemote({ id }) {
898
- const login = readGatewayLogin(this.config.gatewayUrl);
733
+ const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
899
734
  if (!login) throw Object.assign(new Error(`this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login logs in)`), { code: 'NO_GATEWAY_LOGIN' });
900
735
  const remote = new RemoteControl({
901
736
  gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
@@ -959,7 +794,7 @@ export class App {
959
794
  return { text };
960
795
  }
961
796
  if (this.remoteStarting) return { text: 'connecting…' };
962
- const login = readGatewayLogin(this.config.gatewayUrl);
797
+ const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
963
798
  if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`) };
964
799
  if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)') };
965
800
  if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)') };
@@ -975,7 +810,7 @@ export class App {
975
810
  if (w) {
976
811
  const label = w.label.charAt(0).toUpperCase() + w.label.slice(1);
977
812
  rateWait = {
978
- text: w.waitingForLogin ? 'Waiting for the Claude Code login to be renewed' : `${w.overloaded ? label : `${label} reached`}${w.polling ? ' · checking again' : ` · resumes at ${formatClock(w.resumeAt)}`}`,
813
+ text: `${w.overloaded ? label : `${label} reached`}${w.polling ? ' · checking again' : ` · resumes at ${formatClock(w.resumeAt)}`}`,
979
814
  resumeIn: w.resumeAt - Date.now(),
980
815
  };
981
816
  }
@@ -1161,14 +996,13 @@ export class App {
1161
996
 
1162
997
  // What a restart would kill: agents and shells that are still running in the background.
1163
998
  // Something is going on that an update must not cut into: a turn, a question waiting for an answer, messages
1164
- // waiting to be sent, background agents and shells, files on their way.
999
+ // waiting to be sent, background agents and shells.
1165
1000
  working() {
1166
1001
  return Boolean(this.busy || this.dialogs.length || this.queue.length || this.restartBlockers().length);
1167
1002
  }
1168
1003
 
1169
1004
  restartBlockers() {
1170
1005
  const found = [];
1171
- for (const t of this.transfers.values()) found.push(`files on their way ${t.direction === 'up' ? 'to' : 'from'} &${t.label}`);
1172
1006
  for (const t of this.runtime.tasks.running()) found.push(`background agent ${t.id} "${t.description}"`);
1173
1007
  for (const s of listBackgroundShells()) if (s.status === 'running') found.push(`background shell ${s.id} (${String(s.command).slice(0, 40)})`);
1174
1008
  return found;
@@ -1417,7 +1251,7 @@ export class App {
1417
1251
  const model = cfg.mainModel;
1418
1252
  const lines = [
1419
1253
  c.claude('╭' + '─'.repeat(w - 2) + '╮'),
1420
- row(`${c.claude('✻')} Welcome to ${c.bold(APP_NAME)}! ${c.dim(`v${VERSION} · a Claude Code style agent`)}`),
1254
+ row(`${c.claude('✻')} Welcome to ${c.bold(APP_NAME)}! ${c.dim(`v${VERSION} · a command line coding agent`)}`),
1421
1255
  row(''),
1422
1256
  row(c.dim(' /help for help, /status for your current setup')),
1423
1257
  row(''),
@@ -1427,11 +1261,7 @@ export class App {
1427
1261
  c.claude('╰' + '─'.repeat(w - 2) + '╯'),
1428
1262
  ];
1429
1263
  lines.push('', c.dim(' Full access: every tool runs immediately, nothing is ever asked. File edits are checkpointed;'), c.dim(' /rewind puts files and/or the conversation back (shell-command changes are not tracked).'));
1430
- if (cfg.usesGateway && !readGatewayLogin(cfg.gatewayUrl)) {
1431
- lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
1432
- } else if (cfg.provider === 'api' && !cfg.authToken && !cfg.apiKey) {
1433
- lines.push('', c.yellow(' ⚠ No API credentials found. Set ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY in .env, ~/.claude-pro/settings.json or the environment.'));
1434
- }
1264
+ if (!gatewayLogin(cfg.gatewayUrl, cfg.env.CLAUDE_PRO_GATEWAY_API_KEY)) lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
1435
1265
  const mcp = this.runtime.mcp.status();
1436
1266
  if (mcp.length) {
1437
1267
  const ok = mcp.filter((m) => m.status === 'connected').length;
@@ -1465,13 +1295,13 @@ export class App {
1465
1295
  return mode === 'fullscreen' && this.stdout.isTTY !== false;
1466
1296
  }
1467
1297
 
1468
- // Fullscreen: the wheel scrolls the conversation (CLAUDE_PRO_SCROLL_SPEED rows a notch, 3 by default); a drag,
1298
+ // Fullscreen: the wheel scrolls the conversation (3 rows a notch); a drag,
1469
1299
  // a double or a triple click selects, and what is selected goes to the clipboard (see Screen.mouse).
1470
1300
  onMouse(m) {
1471
1301
  if (!this.screen.full || this.exiting) return;
1472
1302
  if (m.button & 64) {
1473
1303
  if (m.button & 128) return;
1474
- const speed = Math.max(1, Math.min(20, Number(this.config.env.CLAUDE_PRO_SCROLL_SPEED) || 3));
1304
+ const speed = 3;
1475
1305
  this.screen.scrollBy(m.button & 1 ? -speed : speed);
1476
1306
  return;
1477
1307
  }
@@ -1612,7 +1442,7 @@ export class App {
1612
1442
  return { items: files.map((f) => ({ value: value(f), label: f, noSpace: f.endsWith('/') })), from: cursor - q.length - (quoted ? 2 : 1), to: cursor };
1613
1443
  }
1614
1444
  // `&name`: the other sessions, on this computer and (through the gateway) on the account's others. At the start
1615
- // it sends them the message; elsewhere it names them (/sendfile, or for the model).
1445
+ // it sends them the message; elsewhere it names them or identifies them for the model.
1616
1446
  const amp = /(^|\s)[&&]([^\s&&]*)$/u.exec(before);
1617
1447
  if (amp) return this.peerSuggestions(amp[2], cursor, amp.index === 0 && !amp[1], { quiet });
1618
1448
  return null;
@@ -1897,7 +1727,7 @@ export class App {
1897
1727
  else if (found.ambiguous) notes.push(found.error);
1898
1728
  }
1899
1729
  if (!notes.length) return [];
1900
- return [{ type: 'text', text: `<system-reminder>The user refers to other sessions: ${notes.join('; ')}. MessagePeer (to: the name in quotes) sends a session a task; its files parameter sends files of this computer along, which the session saves in its computer's Downloads folder (files without a message are only saved and confirmed).</system-reminder>` }];
1730
+ return [{ type: 'text', text: `<system-reminder>The user refers to other sessions: ${notes.join('; ')}. MessagePeer (to: the name in quotes) sends a session a task.</system-reminder>` }];
1901
1731
  }
1902
1732
 
1903
1733
  // alt+v (ctrl+v where the terminal passes it through): attach an image from the clipboard.
@@ -2252,7 +2082,7 @@ export class App {
2252
2082
  }
2253
2083
  // Say it once; later waits of the same pause only move the countdown (unless the reset moved a lot).
2254
2084
  const prev = this.rateWait;
2255
- this.rateWait = { resumeAt: ev.resumeAt, label: ev.label, polling: ev.polling, waitingForLogin: Boolean(ev.waitingForLogin), overloaded: Boolean(ev.overloaded) };
2085
+ this.rateWait = { resumeAt: ev.resumeAt, label: ev.label, polling: ev.polling, overloaded: Boolean(ev.overloaded) };
2256
2086
  if (shouldAnnounce(prev, ev)) this.notice(`${describePause(ev)} Esc cancels.`, 'warn');
2257
2087
  this.screen.schedule();
2258
2088
  }
@@ -2350,7 +2180,7 @@ export class App {
2350
2180
  const rateLimit = (ev) => {
2351
2181
  if (ev.type === 'rate_limit_wait') {
2352
2182
  if (shouldAnnounce(paused, ev)) app.notice(`[${def.name}] ${describePause(ev)}`, 'warn');
2353
- paused = { resumeAt: ev.resumeAt, waitingForLogin: Boolean(ev.waitingForLogin) };
2183
+ paused = { resumeAt: ev.resumeAt };
2354
2184
  }
2355
2185
  if (ev.type === 'rate_limit_resume') {
2356
2186
  paused = null;
@@ -2445,7 +2275,6 @@ export class App {
2445
2275
  const w = this.rateWait;
2446
2276
  const left = humanDuration(w.resumeAt - Date.now()); // the same wording as the notice above it
2447
2277
  const esc = c.dim(`(${this.controller?.signal.aborted ? 'cancelling…' : 'esc to cancel'})`);
2448
- if (w.waitingForLogin) return c.yellow(`${frame} Waiting for the Claude Code login to be renewed · checking again in ${left}`) + ' ' + esc;
2449
2278
  const label = w.label.charAt(0).toUpperCase() + w.label.slice(1);
2450
2279
  const when = w.polling ? `checking again in ${left}` : `resumes at ${formatClock(w.resumeAt)} (in ${left})`;
2451
2280
  return c.yellow(`${frame} ${w.overloaded ? label : `${label} reached`} · ${when}`) + ' ' + esc;
@@ -2566,7 +2395,6 @@ export class App {
2566
2395
  if (this.remote?.online && this.remote.viewers && !flash && !(this.exitArmed && Date.now() - this.exitArmed < 1500)) {
2567
2396
  left += c.dim(' · ') + c.green(`⇄ ${this.remote.viewers} watching`);
2568
2397
  }
2569
- if (this.transfers.size && !flash) left += c.dim(' · ') + this.transferStatus();
2570
2398
  if (!flash) {
2571
2399
  if (this.updating) left += c.dim(' · ') + c.blue(`⇣ updating ${APP_NAME} to ${this.updating}…`);
2572
2400
  else if (this.updateRestart && this.sourceChanged && !this.restartRequest) left += c.dim(' · ') + c.blue(`↻ ${this.updateRestart} installed: restarts ${this.working() ? 'when the work is done' : 'now'}`);
@@ -1,60 +0,0 @@
1
- // Read an existing Claude Code subscription login. There is no login flow here and no subprocess: signing
2
- // in is the official application's. Renewing the access token with the refresh token stored beside it is
3
- // done by oauth.js, which is the only code that writes the credentials file; this reads it.
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import crypto from 'node:crypto';
7
-
8
- export const CLAUDE_CODE_API_URL = 'https://api.anthropic.com';
9
- export const CLAUDE_CODE_SYSTEM = "You are Claude Code, Anthropic's official CLI for Claude.";
10
- export const CLAUDE_CODE_BETAS = 'claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14';
11
- const sessionIds = new WeakMap();
12
- let installedVersion;
13
-
14
- function readJson(file, label) {
15
- let text;
16
- try { text = fs.readFileSync(file, 'utf8'); }
17
- catch { throw new Error(`Could not read existing Claude Code ${label}: ${file}. Select the existing login with CLAUDE_PRO_CLAUDE_CONFIG_FILE / CLAUDE_PRO_CLAUDE_CREDENTIALS_FILE.`); }
18
- // JSON.parse errors can contain an excerpt of the token. Never echo them.
19
- try { return JSON.parse(text.replace(/^\uFEFF/, '')); }
20
- catch { throw new Error(`Invalid JSON in Claude Code ${label}: ${file}.`); }
21
- }
22
-
23
- function clientVersion(config, metadata) {
24
- if (config.env.CLAUDE_PRO_CLAUDE_CODE_VERSION) return config.env.CLAUDE_PRO_CLAUDE_CODE_VERSION;
25
- if (installedVersion) return installedVersion;
26
- for (const dir of (process.env.PATH || process.env.Path || '').split(path.delimiter).filter(Boolean)) {
27
- try {
28
- const pkg = JSON.parse(fs.readFileSync(path.join(dir.replace(/^"|"$/g, ''), 'node_modules', '@anthropic-ai', 'claude-code', 'package.json'), 'utf8'));
29
- if (/^\d+\.\d+\.\d+$/.test(pkg.version)) return (installedVersion = pkg.version);
30
- } catch { /* native installs do not have an npm package */ }
31
- }
32
- return /^\d+\.\d+\.\d+$/.test(metadata.lastOnboardingVersion || '') ? metadata.lastOnboardingVersion : '2.1.289';
33
- }
34
-
35
- export function readClaudeCodeLogin(config) {
36
- const metadata = readJson(config.claudeCodeConfigFile, 'account configuration');
37
- const credentials = readJson(config.claudeCodeCredentialsFile, 'credentials');
38
- const oauth = credentials?.claudeAiOauth;
39
- if (!oauth || typeof oauth.accessToken !== 'string' || !oauth.accessToken.trim()) {
40
- throw new Error(`No existing Claude Code subscription access token in ${config.claudeCodeCredentialsFile}. The .claude.json file contains account metadata; the token is in .claude/.credentials.json.`);
41
- }
42
- if (oauth.expiresAt && Number(oauth.expiresAt) <= Date.now()) {
43
- throw new Error('The existing Claude Code access token has expired and cannot be renewed from here (the credentials file has no refresh token, or CLAUDE_PRO_DISABLE_TOKEN_REFRESH is set). Run `claude` and use /login to sign in again; this project will read the updated file automatically.');
44
- }
45
- if (!sessionIds.has(config)) sessionIds.set(config, crypto.randomUUID());
46
- return {
47
- accessToken: oauth.accessToken,
48
- expiresAt: Number(oauth.expiresAt) || null, // ms since epoch; the token lives 8 hours
49
- userId: JSON.stringify({ device_id: metadata.userID || '', account_uuid: metadata.oauthAccount?.accountUuid || '', session_id: sessionIds.get(config) }),
50
- version: clientVersion(config, metadata),
51
- };
52
- }
53
-
54
- export function claudeCodeHeaders(login) {
55
- return {
56
- 'anthropic-beta': CLAUDE_CODE_BETAS,
57
- 'user-agent': `claude-cli/${login.version} (external, cli)`,
58
- 'x-app': 'cli',
59
- };
60
- }