@yanzc/claude-pro 0.7.2 → 0.7.4

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;
@@ -325,9 +320,9 @@ export class App {
325
320
  }, 120);
326
321
  if (restart) this.continueAfterRestart(restart);
327
322
  else if (initialPrompt?.trim()) this.onSubmit(initialPrompt, initialPrompt);
328
- // 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
329
324
  // background session: nobody sits at this computer to log in in its browser.)
330
- 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) {
331
326
  Promise.resolve(this.commands.get('login').run('')).catch((e) => this.logError(e)).finally(() => this.screen.schedule());
332
327
  }
333
328
  this.fileIndex.refresh();
@@ -552,13 +547,7 @@ export class App {
552
547
  // `target`: a peer entry, or what names one (see resolvePeer): a session on this computer, or one on another
553
548
  // computer, reached through the gateway. `byModel`: the MessagePeer tool sent it, so the answer goes to the
554
549
  // model; otherwise the user typed `@name ...` and the answer is only shown (and noted for the model).
555
- // `files`: paths of files on this computer to send along (see utils/downloads.js); the other session saves
556
- // them in its Downloads folder.
557
- //
558
- // `background`: with files, return as soon as they are checked and the session is found, and send in the
559
- // background (progress in the footer; a finished or failed sending is reported in the transcript).
560
- async sendToPeer(target, text, { byModel = false, files: paths = [], background = false } = {}) {
561
- const files = paths.length ? filesToSend(paths) : [];
550
+ async sendToPeer(target, text, { byModel = false } = {}) {
562
551
  let peer = target && typeof target === 'object' ? target : null;
563
552
  if (!peer) {
564
553
  const local = this.peers?.peers() || [];
@@ -572,80 +561,11 @@ export class App {
572
561
  }
573
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).`);
574
563
  if (!peer.remote && !this.peers) throw new Error('Talking to other sessions on this computer is off (CLAUDE_PRO_PEERS=0).');
575
- const send = async () => {
576
- let r;
577
- if (peer.remote) {
578
- const uploaded = [];
579
- if (files.length) {
580
- const job = this.startTransfer('up', files, peer);
581
- try {
582
- for (const f of files) uploaded.push(await this.remote.uploadFile(f, { signal: job.signal, onProgress: (p) => job.progress(f, p) }));
583
- } finally {
584
- job.end();
585
- }
586
- }
587
- r = { ...(await this.remote.sendPeer(peer.id, { text, files: uploaded })), peer };
588
- } else {
589
- r = await this.peers.send(peer, { text, files });
590
- }
591
- r.files = files;
592
- if (!byModel) this.userSentToPeers.add(`${r.peer.id}:${r.id}`);
593
- return r;
594
- };
595
- if (!background || !files.length) return await send();
596
- const label = peer.label || peer.name;
597
- const what = `${files.length} file${files.length === 1 ? '' : 's'} (${formatBytes(files.reduce((n, f) => n + f.size, 0))})`;
598
- send().then(
599
- () => this.screen.log(c.dim(` ⎿ Sent ${what} to &${label}; it saves them in its Downloads folder and confirms`), ''),
600
- (e) => {
601
- const why = e.name === 'AbortError'
602
- ? `Stopped sending ${what} to &${label}. Send the same files again to continue where it stopped.`
603
- : `Could not send ${what} to &${label}: ${e.message}${peer.remote ? ' (sending the same files again continues where it stopped)' : ''}`;
604
- this.notice(why, 'warn');
605
- if (byModel) this.agent.addReminder(`The files you sent with MessagePeer did not go out: ${why}`);
606
- },
607
- );
608
- return { peer, files, background: true };
609
- }
610
-
611
- // A sending or receiving of files, shown in the footer while it runs: {signal, progress(file, p), end()}.
612
- startTransfer(direction, files, peer) {
613
- const id = ++this.transferSeq;
614
- const controller = new AbortController();
615
- const total = files.reduce((n, f) => n + (Number(f.size) || 0), 0);
616
- 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 };
617
- this.transfers.set(id, t);
618
- this.screen.schedule();
619
- return {
620
- signal: controller.signal,
621
- progress: (file, p) => {
622
- t.done.set(file, p.phase === 'hashing' || p.phase === 'checking' ? 0 : p.done);
623
- t.phase = p.phase;
624
- t.file = file.name;
625
- t.retryIn = p.phase === 'waiting' ? Date.now() + (p.retryIn || 0) : 0;
626
- if (p.phase === 'hashing' || p.phase === 'checking') t.hashed = p.total ? p.done / p.total : 0;
627
- if (Date.now() - t.shown > 250) { t.shown = Date.now(); this.screen.schedule(); }
628
- },
629
- end: () => { this.transfers.delete(id); this.screen.schedule(); },
630
- };
631
- }
632
-
633
- // The footer's word on the files on their way.
634
- transferStatus() {
635
- const all = [...this.transfers.values()];
636
- if (!all.length) return '';
637
- const t = all[0];
638
- const done = [...t.done.values()].reduce((n, v) => n + v, 0);
639
- const pct = t.total ? Math.floor((done / t.total) * 100) : 0;
640
- const arrow = t.direction === 'up' ? '⇡' : '⇣';
641
- const name = truncate(t.names.length === 1 ? t.names[0] : `${t.names.length} files`, 24);
642
- const where = t.direction === 'up' ? `→ &${t.label}` : `← &${t.label}`;
643
- let state;
644
- if (t.phase === 'waiting') state = c.yellow(`${pct}% · network down, retrying…`);
645
- else if (t.phase === 'hashing') state = c.dim(`preparing ${Math.floor((t.hashed || 0) * 100)}%`);
646
- else if (t.phase === 'checking') state = c.dim('checking');
647
- else state = c.dim(`${pct}% · ${formatBytes(done)}/${formatBytes(t.total)}`);
648
- 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;
649
569
  }
650
570
 
651
571
  // The account's sessions on other computers that are online now, from the gateway (what was known stays when
@@ -686,7 +606,6 @@ export class App {
686
606
 
687
607
  onPeerMessage(msg) {
688
608
  if (this.exiting) return;
689
- if (msg.files?.length && !msg.received) return this.receiveFiles(msg).catch((e) => this.logError(e)); // the gateway keeps the message until this is done
690
609
  const from = c.bold(`&${msg.from.name}`);
691
610
  const width = this.width - 1;
692
611
  if (msg.kind === 'reply' && this.userSentToPeers.delete(`${msg.from.id}:${msg.inReplyTo}`)) {
@@ -701,56 +620,6 @@ export class App {
701
620
  this.startTurn(item.text, { display, peers: item.peer ? [item.peer] : [] });
702
621
  }
703
622
 
704
- // Files another session sent: saved in the Downloads folder (never over a file that is there) at once, whatever
705
- // this session is doing. Files alone are answered right away with where they are, without a turn of the model;
706
- // with a task, the task runs as usual and is told where they are.
707
- async receiveFiles(msg) {
708
- msg.received = true;
709
- let dir;
710
- try { dir = await downloadsDir(this.config.env); } catch { dir = path.join(os.homedir(), 'Downloads'); }
711
- const saved = [];
712
- const failed = [];
713
- const remote = this.remote;
714
- const job = msg.from.remote ? this.startTransfer('down', msg.files, msg.from) : null;
715
- try {
716
- for (const f of msg.files) {
717
- try {
718
- let file;
719
- if (msg.from.remote) {
720
- if (!remote) throw new Error('this session is not online at the gateway');
721
- file = await remote.downloadFile(f, dir, { signal: job.signal, onProgress: (p) => job.progress(f, p) });
722
- remote.deleteFile(f.id);
723
- } else {
724
- file = await copyUnique(f.path, dir, f.name);
725
- }
726
- saved.push({ path: file, size: fs.statSync(file).size });
727
- } catch (e) {
728
- failed.push(`${f.name}: ${e.message}`);
729
- }
730
- }
731
- } finally {
732
- job?.end();
733
- }
734
- this.screen.log(
735
- `${c.blue('✉')} ${c.bold(`&${msg.from.name}`)} ${c.dim(`sent ${msg.files.length} file${msg.files.length === 1 ? '' : 's'}${saved.length ? `, saved in ${dir}:` : ':'}`)}`,
736
- ...saved.map((s) => ` ${path.basename(s.path)} ${c.dim(formatBytes(s.size))}`),
737
- ...failed.map((f) => c.red(` ✗ ${f}`)),
738
- '',
739
- );
740
- const where = `the Downloads folder of ${machineName(this.config.env)} (${dir})`;
741
- const report = [
742
- saved.length ? `Saved ${saved.length} file${saved.length === 1 ? '' : 's'} in ${where}:\n${saved.map((s) => `- ${s.path}`).join('\n')}` : '',
743
- failed.length ? `Could not save:\n${failed.map((f) => `- ${f}`).join('\n')}` : '',
744
- ].filter(Boolean).join('\n\n');
745
- if (msg.kind === 'task' && !msg.text.trim()) {
746
- this.agent.addReminder(`Another claude-pro session, ${msg.from.name}, sent files to this computer. ${report}`);
747
- this.replyToPeer(msg, report);
748
- return;
749
- }
750
- msg.text = `${msg.text}\n\n[Files that came with this message. ${report}]`;
751
- this.onPeerMessage(msg);
752
- }
753
-
754
623
  // Send `text` as the answer to `msg`, a message of another session: here, or through the gateway.
755
624
  replyToPeer(msg, text) {
756
625
  const done = () => this.screen.log(c.dim(` ⎿ Answer sent to &${msg.from.name}`));
@@ -768,48 +637,6 @@ export class App {
768
637
  this.peers.send(peer, { text, kind: 'reply', inReplyTo: msg.id }).then(done, failed);
769
638
  }
770
639
 
771
- // /sendfile &session file...: files on this computer to another session (here or on another computer), which
772
- // saves them in its Downloads folder and confirms. Paths may be quoted, @-mentions, or have spaces unquoted.
773
- async sendFiles(args) {
774
- if (/^\s*(stop|cancel)\s*$/i.test(args)) {
775
- const ups = [...this.transfers.values()].filter((t) => t.direction === 'up');
776
- for (const t of ups) t.controller.abort();
777
- this.screen.log(c.dim(ups.length ? ` ⎿ Stopping ${ups.length} sending${ups.length === 1 ? '' : 's'}` : ' ⎿ Nothing is being sent'));
778
- return;
779
- }
780
- const tokens = [...String(args).matchAll(/@?"([^"]+)"|@?'([^']+)'|(\S+)/g)].map((m) => ({ text: m[1] ?? m[2] ?? m[3], quoted: m[3] === undefined }));
781
- const targets = tokens.filter((t) => !t.quoted && /^[&&]./u.test(t.text));
782
- if (targets.length !== 1) {
783
- this.notice(targets.length ? 'Send to one session at a time.' : 'Usage: /sendfile &session file... (type & for the list of sessions)', 'warn');
784
- return;
785
- }
786
- const exists = (p) => { try { return fs.statSync(p).isFile(); } catch { return false; } };
787
- const rest = tokens.filter((t) => t !== targets[0]);
788
- const paths = [];
789
- for (let i = 0; i < rest.length;) {
790
- if (rest[i].quoted) { paths.push(resolvePath(rest[i].text, this.cwd)); i++; continue; }
791
- // the longest run of words that is a file: a path with spaces that was not quoted
792
- let j = i + 1;
793
- for (let k = rest.length; k > i + 1; k--) {
794
- if (rest.slice(i, k).some((t) => t.quoted)) continue;
795
- if (exists(resolvePath(rest.slice(i, k).map((t) => t.text).join(' ').replace(/^@/, ''), this.cwd))) { j = k; break; }
796
- }
797
- paths.push(resolvePath(rest.slice(i, j).map((t) => t.text).join(' ').replace(/^@/, ''), this.cwd));
798
- i = j;
799
- }
800
- let files;
801
- try { files = filesToSend(paths); } catch (e) { this.notice(e.message, 'warn'); return; }
802
- const total = files.reduce((n, f) => n + f.size, 0);
803
- const what = `${files.length} file${files.length === 1 ? '' : 's'} (${formatBytes(total)})`;
804
- try {
805
- const r = await this.sendToPeer(targets[0].text, '', { files: paths, background: true });
806
- const label = r.peer.label || r.peer.name;
807
- 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' : ''})`));
808
- } catch (e) {
809
- this.notice(`Could not send the files: ${e.message}`, 'warn');
810
- }
811
- }
812
-
813
640
  // The turn that handled tasks of other sessions ended: send each its answer.
814
641
  answerPeers(result, error) {
815
642
  const tasks = this.turnPeers.splice(0);
@@ -845,7 +672,7 @@ export class App {
845
672
  const env = this.config.env;
846
673
  if (!onlineEnabled(env)) return false;
847
674
  if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
848
- return Boolean(readGatewayLogin(this.config.gatewayUrl));
675
+ return Boolean(gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY));
849
676
  }
850
677
 
851
678
  // Online at the gateway from the start, without holding the start up: when this computer is logged in to it; with
@@ -862,9 +689,9 @@ export class App {
862
689
  }
863
690
 
864
691
  // Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
865
- // computers reach it from then on. Needs the gateway login of /login (the provider of the model requests can be
866
- // another one); throws {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried
867
- // 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).
868
695
  startRemote({ id } = {}) {
869
696
  if (this.remote) return Promise.resolve(this.remote);
870
697
  this.remoteStarting ??= this.connectRemote({ id }).finally(() => { this.remoteStarting = null; });
@@ -876,7 +703,7 @@ export class App {
876
703
  syncRemote() {
877
704
  if (this.exiting) return Promise.resolve(null);
878
705
  if (this.remoteStarting) return this.remoteStarting.catch(() => null);
879
- const login = readGatewayLogin(this.config.gatewayUrl);
706
+ const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
880
707
  const r = this.remote;
881
708
  // logged out, or another account: not this account's session any more
882
709
  if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
@@ -894,7 +721,7 @@ export class App {
894
721
  ensureHost({ login = false } = {}) {
895
722
  const env = this.config.env;
896
723
  if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
897
- 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;
898
725
  try { startHostIfNeeded(); } catch { /* the next session tries again */ }
899
726
  try {
900
727
  const auto = ensureAutostart({ force: login, env });
@@ -903,7 +730,7 @@ export class App {
903
730
  }
904
731
 
905
732
  async connectRemote({ id }) {
906
- const login = readGatewayLogin(this.config.gatewayUrl);
733
+ const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
907
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' });
908
735
  const remote = new RemoteControl({
909
736
  gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
@@ -967,7 +794,7 @@ export class App {
967
794
  return { text };
968
795
  }
969
796
  if (this.remoteStarting) return { text: 'connecting…' };
970
- const login = readGatewayLogin(this.config.gatewayUrl);
797
+ const login = gatewayLogin(this.config.gatewayUrl, this.config.env.CLAUDE_PRO_GATEWAY_API_KEY);
971
798
  if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`) };
972
799
  if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)') };
973
800
  if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)') };
@@ -983,7 +810,7 @@ export class App {
983
810
  if (w) {
984
811
  const label = w.label.charAt(0).toUpperCase() + w.label.slice(1);
985
812
  rateWait = {
986
- text: w.waitingForLogin ? 'Waiting for the Claude subscription 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)}`}`,
987
814
  resumeIn: w.resumeAt - Date.now(),
988
815
  };
989
816
  }
@@ -1169,14 +996,13 @@ export class App {
1169
996
 
1170
997
  // What a restart would kill: agents and shells that are still running in the background.
1171
998
  // Something is going on that an update must not cut into: a turn, a question waiting for an answer, messages
1172
- // waiting to be sent, background agents and shells, files on their way.
999
+ // waiting to be sent, background agents and shells.
1173
1000
  working() {
1174
1001
  return Boolean(this.busy || this.dialogs.length || this.queue.length || this.restartBlockers().length);
1175
1002
  }
1176
1003
 
1177
1004
  restartBlockers() {
1178
1005
  const found = [];
1179
- for (const t of this.transfers.values()) found.push(`files on their way ${t.direction === 'up' ? 'to' : 'from'} &${t.label}`);
1180
1006
  for (const t of this.runtime.tasks.running()) found.push(`background agent ${t.id} "${t.description}"`);
1181
1007
  for (const s of listBackgroundShells()) if (s.status === 'running') found.push(`background shell ${s.id} (${String(s.command).slice(0, 40)})`);
1182
1008
  return found;
@@ -1435,11 +1261,7 @@ export class App {
1435
1261
  c.claude('╰' + '─'.repeat(w - 2) + '╯'),
1436
1262
  ];
1437
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).'));
1438
- if (cfg.usesGateway && !readGatewayLogin(cfg.gatewayUrl)) {
1439
- lines.push('', c.yellow(` ⚠ Not logged in to the gateway ${cfg.gatewayUrl}. Run /login.`));
1440
- } else if (cfg.provider === 'api' && !cfg.authToken && !cfg.apiKey) {
1441
- 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.'));
1442
- }
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.`));
1443
1265
  const mcp = this.runtime.mcp.status();
1444
1266
  if (mcp.length) {
1445
1267
  const ok = mcp.filter((m) => m.status === 'connected').length;
@@ -1620,7 +1442,7 @@ export class App {
1620
1442
  return { items: files.map((f) => ({ value: value(f), label: f, noSpace: f.endsWith('/') })), from: cursor - q.length - (quoted ? 2 : 1), to: cursor };
1621
1443
  }
1622
1444
  // `&name`: the other sessions, on this computer and (through the gateway) on the account's others. At the start
1623
- // 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.
1624
1446
  const amp = /(^|\s)[&&]([^\s&&]*)$/u.exec(before);
1625
1447
  if (amp) return this.peerSuggestions(amp[2], cursor, amp.index === 0 && !amp[1], { quiet });
1626
1448
  return null;
@@ -1905,7 +1727,7 @@ export class App {
1905
1727
  else if (found.ambiguous) notes.push(found.error);
1906
1728
  }
1907
1729
  if (!notes.length) return [];
1908
- 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>` }];
1909
1731
  }
1910
1732
 
1911
1733
  // alt+v (ctrl+v where the terminal passes it through): attach an image from the clipboard.
@@ -2260,7 +2082,7 @@ export class App {
2260
2082
  }
2261
2083
  // Say it once; later waits of the same pause only move the countdown (unless the reset moved a lot).
2262
2084
  const prev = this.rateWait;
2263
- 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) };
2264
2086
  if (shouldAnnounce(prev, ev)) this.notice(`${describePause(ev)} Esc cancels.`, 'warn');
2265
2087
  this.screen.schedule();
2266
2088
  }
@@ -2358,7 +2180,7 @@ export class App {
2358
2180
  const rateLimit = (ev) => {
2359
2181
  if (ev.type === 'rate_limit_wait') {
2360
2182
  if (shouldAnnounce(paused, ev)) app.notice(`[${def.name}] ${describePause(ev)}`, 'warn');
2361
- paused = { resumeAt: ev.resumeAt, waitingForLogin: Boolean(ev.waitingForLogin) };
2183
+ paused = { resumeAt: ev.resumeAt };
2362
2184
  }
2363
2185
  if (ev.type === 'rate_limit_resume') {
2364
2186
  paused = null;
@@ -2453,7 +2275,6 @@ export class App {
2453
2275
  const w = this.rateWait;
2454
2276
  const left = humanDuration(w.resumeAt - Date.now()); // the same wording as the notice above it
2455
2277
  const esc = c.dim(`(${this.controller?.signal.aborted ? 'cancelling…' : 'esc to cancel'})`);
2456
- if (w.waitingForLogin) return c.yellow(`${frame} Waiting for the Claude subscription login to be renewed · checking again in ${left}`) + ' ' + esc;
2457
2278
  const label = w.label.charAt(0).toUpperCase() + w.label.slice(1);
2458
2279
  const when = w.polling ? `checking again in ${left}` : `resumes at ${formatClock(w.resumeAt)} (in ${left})`;
2459
2280
  return c.yellow(`${frame} ${w.overloaded ? label : `${label} reached`} · ${when}`) + ' ' + esc;
@@ -2574,7 +2395,6 @@ export class App {
2574
2395
  if (this.remote?.online && this.remote.viewers && !flash && !(this.exitArmed && Date.now() - this.exitArmed < 1500)) {
2575
2396
  left += c.dim(' · ') + c.green(`⇄ ${this.remote.viewers} watching`);
2576
2397
  }
2577
- if (this.transfers.size && !flash) left += c.dim(' · ') + this.transferStatus();
2578
2398
  if (!flash) {
2579
2399
  if (this.updating) left += c.dim(' · ') + c.blue(`⇣ updating ${APP_NAME} to ${this.updating}…`);
2580
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'}`);
@@ -0,0 +1,62 @@
1
+ // Validation and recovery helpers for the machine-readable state that survives compaction.
2
+
3
+ export const WORK_STATE_VERSION = 1;
4
+
5
+ const TEXT_FIELDS = ['objective', 'next_action'];
6
+ const LIST_FIELDS = ['constraints', 'decisions', 'files', 'edits', 'tests', 'failures', 'open_questions', 'tool_artifacts'];
7
+ const ALL_FIELDS = ['schema_version', ...TEXT_FIELDS, ...LIST_FIELDS];
8
+ const MAX_TEXT_CHARS = 4_000;
9
+ const MAX_LIST_ITEMS = 50;
10
+ const MAX_ITEM_CHARS = 2_000;
11
+
12
+ export function validateWorkState(value) {
13
+ const errors = [];
14
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false, errors: ['state must be a JSON object'] };
15
+ if (value.schema_version !== WORK_STATE_VERSION) errors.push(`schema_version must be ${WORK_STATE_VERSION}`);
16
+ for (const key of TEXT_FIELDS) {
17
+ if (typeof value[key] !== 'string') errors.push(`${key} must be a string`);
18
+ else if (value[key].length > MAX_TEXT_CHARS) errors.push(`${key} is longer than ${MAX_TEXT_CHARS} characters`);
19
+ }
20
+ for (const key of LIST_FIELDS) {
21
+ if (!Array.isArray(value[key])) {
22
+ errors.push(`${key} must be an array`);
23
+ continue;
24
+ }
25
+ if (value[key].length > MAX_LIST_ITEMS) errors.push(`${key} has more than ${MAX_LIST_ITEMS} items`);
26
+ for (const [i, item] of value[key].entries()) {
27
+ if (typeof item !== 'string') errors.push(`${key}[${i}] must be a string`);
28
+ else if (item.length > MAX_ITEM_CHARS) errors.push(`${key}[${i}] is longer than ${MAX_ITEM_CHARS} characters`);
29
+ }
30
+ }
31
+ if (errors.length) return { ok: false, errors };
32
+ // Copy only the schema we understand. This keeps future model-added fields from becoming an
33
+ // unbounded part of every later context window while retaining a stable versioned shape.
34
+ return { ok: true, value: Object.fromEntries(ALL_FIELDS.map((key) => [key, key === 'schema_version' ? WORK_STATE_VERSION : value[key]])) };
35
+ }
36
+
37
+ export function workStateFromText(text) {
38
+ const source = String(text ?? '');
39
+ const match = /<work-state>\s*([\s\S]*?)\s*<\/work-state>/i.exec(source);
40
+ if (!match) return { present: false, state: null, errors: [] };
41
+ let value;
42
+ try {
43
+ value = JSON.parse(match[1].replace(/^```(?:json)?\s*|\s*```$/gi, '').trim());
44
+ } catch (err) {
45
+ return { present: true, state: null, errors: [`invalid JSON: ${err.message}`] };
46
+ }
47
+ const checked = validateWorkState(value);
48
+ return { present: true, state: checked.ok ? checked.value : null, errors: checked.errors || [] };
49
+ }
50
+
51
+ export function latestWorkState(messages) {
52
+ for (let i = messages.length - 1; i >= 0; i--) {
53
+ const content = messages[i]?.content;
54
+ const blocks = Array.isArray(content) ? content : [{ type: 'text', text: content }];
55
+ for (let j = blocks.length - 1; j >= 0; j--) {
56
+ if (blocks[j]?.type !== 'text') continue;
57
+ const parsed = workStateFromText(blocks[j].text);
58
+ if (parsed.state) return parsed.state;
59
+ }
60
+ }
61
+ return null;
62
+ }
@@ -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 the Claude subscription ${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 the Claude subscription ${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 Claude 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 Claude subscription 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
- }