@yanzc/claude-pro 0.5.9 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,9 +16,7 @@ export const GlobTool = {
16
16
  description: `- Fast file pattern matching tool that works with any codebase size
17
17
  - Supports glob patterns like "**/*.js" or "src/**/*.ts"
18
18
  - Returns matching file paths sorted by modification time (most recent first)
19
- - Use this tool when you need to find files by name patterns
20
- - When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
21
- - You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful.`,
19
+ - Use this tool when you need to find files by name patterns`,
22
20
  input_schema: {
23
21
  type: 'object',
24
22
  properties: {
@@ -266,16 +264,24 @@ function runRg(bin, args, cwd, signal) {
266
264
  });
267
265
  }
268
266
 
267
+ // ripgrep takes inline flags at the start of a pattern, `(?i)` or `(?is)`; a JS RegExp does not, so they become
268
+ // flags. `m` is dropped: ^ and $ are line anchors here anyway, as in ripgrep.
269
+ export function inlineFlags(pattern) {
270
+ const m = /^\(\?([ims]+)\)/.exec(pattern);
271
+ return m ? { pattern: pattern.slice(m[0].length), i: m[1].includes('i'), s: m[1].includes('s') } : { pattern, i: false, s: false };
272
+ }
273
+
269
274
  // JS scanner used when ripgrep isn't available. Returns output lines in rg's format.
270
275
  async function jsGrep(input, base, mode, signal) {
271
276
  const exts = input.type ? TYPE_EXT[String(input.type).toLowerCase()] : null;
272
277
  if (input.type && !exts) throw new Error(`unrecognized file type: ${input.type} (known types: ${Object.keys(TYPE_EXT).join(', ')})`);
273
- const flags = input['-i'] ? 'i' : '';
274
- const dotAll = input.multiline ? 's' : '';
278
+ const inline = inlineFlags(input.pattern);
279
+ const flags = input['-i'] || inline.i ? 'i' : '';
280
+ const dotAll = input.multiline || inline.s ? 's' : '';
275
281
  // ripgrep treats ^ and $ as line anchors, so whole-file matching needs the m flag.
276
- const anyRe = new RegExp(input.pattern, `${flags}m${dotAll}`);
277
- const allRe = new RegExp(input.pattern, `${flags}gm${dotAll}`);
278
- const lineRe = new RegExp(input.pattern, flags);
282
+ const anyRe = new RegExp(inline.pattern, `${flags}m${dotAll}`);
283
+ const allRe = new RegExp(inline.pattern, `${flags}gm${dotAll}`);
284
+ const lineRe = new RegExp(inline.pattern, flags);
279
285
  const content = mode === 'content';
280
286
  const before = content ? Math.max(0, Number(input['-B'] ?? input['-C'] ?? 0) || 0) : 0;
281
287
  const after = content ? Math.max(0, Number(input['-A'] ?? input['-C'] ?? 0) || 0) : 0;
@@ -359,11 +365,10 @@ export const GrepTool = {
359
365
  description: `A powerful search tool built on ripgrep
360
366
 
361
367
  Usage:
362
- - ALWAYS use Grep for search tasks. NEVER invoke \`grep\` or \`rg\` as a Bash command.
368
+ - Use this tool to search file contents rather than \`grep\` or \`rg\` through Bash (rg may not be installed on the machine).
363
369
  - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
364
370
  - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
365
371
  - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
366
- - Use Task tool for open-ended searches requiring multiple rounds
367
372
  - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
368
373
  - Multiline matching: By default patterns match within single lines only. For cross-line patterns like \`struct \\{[\\s\\S]*?field\`, use \`multiline: true\``,
369
374
  input_schema: {
package/src/tools/task.js CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { taskResultText } from '../tasks.js';
6
6
  import { EFFORTS } from '../agents.js';
7
+ import { priceOf } from '../pricing.js';
7
8
 
8
9
  // Wait for `promise`, at most `ms`, or until `signal` aborts. The timer is always cleared so a
9
10
  // finished wait never keeps the process alive.
@@ -20,14 +21,34 @@ function waitFor(promise, ms, signal) {
20
21
  });
21
22
  }
22
23
 
23
- export function makeTaskTool(agents) {
24
+ // How to pick a sub-agent's model, where the main agent chooses it (Config.subagentModelChosen): the models the
25
+ // aliases stand for, with their prices. Built from the configuration of the moment, so that it follows /model and
26
+ // /login (which start a new prompt cache anyway); it holds nothing that changes otherwise.
27
+ export function modelChoiceText(config) {
28
+ if (!config?.subagentModelChosen) return '';
29
+ const main = config.mainModel.id;
30
+ const option = (alias) => {
31
+ const id = config.resolveModel(alias).id;
32
+ const p = priceOf(id);
33
+ return `${alias} (${id}${id === main ? ', your own model' : ''}${p ? `, $${p.input}/$${p.output} per million input/output tokens` : ''})`;
34
+ };
35
+ return `
36
+
37
+ Choosing the model: there is no fixed sub-agent model. Choose one for each task by how hard it is and how much you will rely on the report, and give it in \`model\`:
38
+ - ${option('haiku')}: mechanical work with a clear target: find where something is defined or used, list files, read files and quote the relevant parts.
39
+ - ${option('sonnet')}: searches across a codebase and well-specified subtasks whose steps are clear: gather the call sites of a function and how they use it, run tests and summarize the failures, make a change that is fully described.
40
+ - ${option('opus')}: work whose quality your answer depends on and that you will not redo yourself: hard debugging, design and trade-offs, reviewing code for subtle bugs, analysis that spans many files.
41
+ A shallow or wrong report that you rely on costs more than the difference in price; a strong model on a lookup only wastes money. Set \`effort\` with it (low suits lookups); without it the agent runs at your session's effort. Without \`model\` an agent runs on its definition's model, else on ${config.subagentModel.id}.`;
42
+ }
43
+
44
+ export function makeTaskTool(agents, config = null) {
24
45
  const list = [...agents.values()]
25
- .map((a) => `- ${a.name}: ${a.description} (Tools: ${a.tools === '*' ? 'All tools' : a.tools.join(', ')})`)
46
+ .map((a) => `- ${a.name}: ${a.description} (Tools: ${a.tools === '*' ? 'All tools' : a.tools.join(', ')})${a.model ? ` (model: ${a.model})` : ''}`)
26
47
  .join('\n');
27
48
  return {
28
49
  name: 'Task',
29
50
  readOnly: true, // sub-agents ask for their own permissions; multiple tasks may run in parallel
30
- description: `Launch a new agent to handle complex, multi-step tasks autonomously.
51
+ description: () => `Launch a new agent to handle complex, multi-step tasks autonomously.
31
52
 
32
53
  Available agent types and the tools they have access to:
33
54
  ${list}
@@ -40,12 +61,13 @@ When NOT to use the Task tool:
40
61
  - If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead
41
62
 
42
63
  Usage notes:
43
- - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
64
+ - When several independent tasks are worth delegating, start them in a single message with multiple tool uses so that they run concurrently. Do not split closely coupled work between agents: they do not see each other's work, and each one costs its own context and tokens
44
65
  - When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
45
66
  - Each agent invocation is stateless. Your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message.
46
- - The agent's outputs should generally be trusted
67
+ - Once you have delegated a search or an investigation, do not also do it yourself: wait for the report, doing other work meanwhile. Never make up or predict the result of an agent that is still running; if the user asks before it is done, say that it is still running.
68
+ - A sub-agent may run on a smaller model than yours. Use its report to find your way, but before you build an answer or a change on one of its findings, check that finding yourself (read the lines it cites)
47
69
  - Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
48
- - Set run_in_background: true to start the agent and continue working while it runs (e.g. a long investigation, or several independent jobs). You get a task id back immediately, and the agent's final report arrives automatically in a <task-notification> once it finishes; you do not need to poll. Use TaskOutput to check on or wait for it early, and TaskStop to cancel it. Do not start background agents that edit the same files at the same time.`,
70
+ - Set run_in_background: true to start the agent and continue working while it runs (e.g. a long investigation, or several independent jobs). You get a task id back immediately, and the agent's final report arrives automatically in a <task-notification> once it finishes; you do not need to poll. Use TaskOutput to check on or wait for it early, and TaskStop to cancel it. Do not start background agents that edit the same files at the same time.${modelChoiceText(config)}`,
49
71
  input_schema: {
50
72
  type: 'object',
51
73
  properties: {
@@ -53,7 +75,7 @@ Usage notes:
53
75
  prompt: { type: 'string', description: 'The task for the agent to perform' },
54
76
  subagent_type: { type: 'string', description: 'The type of specialized agent to use for this task' },
55
77
  run_in_background: { type: 'boolean', description: 'Run the agent in the background and return immediately with a task id' },
56
- model: { type: 'string', description: 'Optional model for this agent: sonnet, opus, haiku or a full model id. Defaults to the agent definition\'s model, else the sub-agent default. A smaller model is cheaper and faster for simple searches.' },
78
+ model: { type: 'string', description: 'Model for this agent: haiku, sonnet, opus or a full model id. Pick it by how hard the task is: a smaller model is cheaper and faster for lookups and clear subtasks, a stronger one is right when you rely on the quality of its report. Defaults to the agent definition\'s model, else the sub-agent default.' },
57
79
  effort: { type: 'string', enum: EFFORTS, description: 'Optional effort level for this agent (default: the agent definition\'s, else the session\'s). Low suits quick lookups, high or above hard reasoning.' },
58
80
  },
59
81
  required: ['description', 'prompt', 'subagent_type'],
package/src/ui/repl.js CHANGED
@@ -6,7 +6,7 @@ import path from 'node:path';
6
6
  import os from 'node:os';
7
7
  import readline from 'node:readline';
8
8
  import { spawn } from 'node:child_process';
9
- import { c, ESC, stringWidth, truncate, padEnd, wordWrap, colorEnabled } from './ansi.js';
9
+ import { c, ESC, stringWidth, truncate, padEnd, wordWrap } from './ansi.js';
10
10
  import { Screen, queryCursorRow, mouseFilter } from './screen.js';
11
11
  import { Editor, topBorder } from './editor.js';
12
12
  import { SelectDialog } from './dialogs.js';
@@ -18,7 +18,7 @@ import { createRuntime } from '../runtime.js';
18
18
  import { SessionStore, firstUserText } 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, formatUsd } from '../gateway.js';
21
+ import { readGatewayLogin, normalizeGatewayUrl, formatUsd } from '../gateway.js';
22
22
  import { TOPIC_TITLE_SYSTEM, topicTitlePrompt } from '../prompts.js';
23
23
  import { buildCommands } from '../commands.js';
24
24
  import { canRestart, writeRestartState, runSelfCheck, watchSource, restartNote, RESTART_EXIT_CODE, MAX_RESTARTS, RESTART_WINDOW_MS } from '../restart.js';
@@ -34,7 +34,7 @@ import { copyUnique } from '../transfer.js';
34
34
  import { checkForUpdate, installUpdate, installedVersion, installedByNpm, isNewer, CHECK_EVERY_MS } from '../updater.js';
35
35
  import { PeerNode, peersEnabled, findPeer, resolvePeer, machineName, cleanName, peerMessagePrompt } from '../peers.js';
36
36
  import { RemoteControl, transcriptItems, onlineEnabled, REMOTE_WIDTH } from '../remote.js';
37
- import { qrLines } from '../qr.js';
37
+ import { ensureHost as startHostIfNeeded, hostEnabled } from '../host.js';
38
38
 
39
39
  // A model id as people say it: claude-sonnet-5-5 -> sonnet-5-5, claude-haiku-4-5-20251001 -> haiku-4-5.
40
40
  export const modelTag = (model) => String(model?.id ?? '').replace(/^claude-/, '').replace(/-\d{8}$/, '');
@@ -187,7 +187,8 @@ export class App {
187
187
  this.remoteMuted = 0; // > 0 while printing something the page is told about in its own terms
188
188
  this.remoteDialogs = 0;
189
189
  this.remoteStarting = null;
190
- this.remoteStopped = false; // /rc stop: offline until /rc, also after a restart
190
+ this.remoteRefused = null; // a gateway key the gateway refused: not tried again by itself (a new /login is)
191
+ this.selfCheck = selfCheck;
191
192
  this.sessionName = flags?.restart?.peerName || null; // this session's name when the sessions of this computer do not know it (CLAUDE_PRO_PEERS=0)
192
193
  this.customTitle = null; // the conversation's name given with /rename: the title, instead of the topic
193
194
  this.remotePeers = []; // the account's sessions on other computers, as last listed by the gateway (see peers.js)
@@ -279,6 +280,7 @@ export class App {
279
280
  if (restart) this.resumeAfterRestart(restart, resumable);
280
281
  else if (this.flags.resumeFile) this.loadSession(this.flags.resumeFile, this.flags.resumeId);
281
282
  else if (this.flags.resume) await this.commands.get('resume').run('');
283
+ if (!restart && this.flags.name?.trim()) this.renameSession(this.flags.name); // --name, as /rename does
282
284
  this.autoStartRemote(restart);
283
285
 
284
286
  this.screen.setLive((w) => this.renderLive(w));
@@ -300,6 +302,11 @@ export class App {
300
302
  // and every few minutes while it runs, so that a release reaches a session that stays open for days
301
303
  this.updateTimer = setInterval(() => { if (!this.exiting) this.autoUpdate({ quiet: true }); }, CHECK_EVERY_MS);
302
304
  this.updateTimer.unref?.();
305
+ // online or offline as this computer's gateway login changes (/login or /logout in another window)
306
+ this.loginTimer = setInterval(() => this.syncRemote(), 10_000);
307
+ this.loginTimer.unref?.();
308
+ // the computer service (a process of its own, see host.js), once the session is up
309
+ setTimeout(() => this.ensureHost(), 3000).unref?.();
303
310
  }
304
311
  return new Promise((resolve) => { this.resolveExit = resolve; });
305
312
  }
@@ -388,6 +395,7 @@ export class App {
388
395
  this.runtime?.mcp.close();
389
396
  this.peers?.close();
390
397
  clearInterval(this.remotePeersTimer);
398
+ clearInterval(this.loginTimer);
391
399
  const remoteClosed = this.remote?.close({ restarting: restart });
392
400
  const u = this.agent?.totalUsage();
393
401
  if (!restart && u && u.requests) {
@@ -451,12 +459,12 @@ export class App {
451
459
  let found = resolvePeer(local, this.remotePeers, target);
452
460
  if (!found.peer && !found.error && this.remote) found = resolvePeer(local, await this.refreshRemotePeers(), target);
453
461
  if (!found.peer) {
454
- const offline = this.remote ? '' : ' Sessions on your other computers can be reached once this one is online at the gateway (/login, then /rc).';
462
+ const offline = this.remote ? '' : ' Sessions on your other computers can be reached once this one is online at the gateway (/login).';
455
463
  throw new Error(found.error || `No running session called "${String(target).replace(/^[@&]/, '')}". /peers lists them.${offline}`);
456
464
  }
457
465
  peer = found.peer;
458
466
  }
459
- if (peer.remote && !this.remote) throw new Error(`&${peer.label} is on another computer, and this session is not online at the gateway (/rc connects it).`);
467
+ 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).`);
460
468
  if (!peer.remote && !this.peers) throw new Error('Talking to other sessions on this computer is off (CLAUDE_PRO_PEERS=0).');
461
469
  const send = async () => {
462
470
  let r;
@@ -724,34 +732,68 @@ export class App {
724
732
  this.remote?.emit({ t: 'user', text: images ? `${text}\n[${images} image${images === 1 ? '' : 's'}]` : String(text) });
725
733
  }
726
734
 
727
- // Online at the gateway (see remote.js) from the start: by itself when this computer is logged in to the gateway
728
- // (CLAUDE_PRO_ONLINE=0 turns that off), with --rc (which prints the link too), and after a restart as before (with
729
- // the same id, so that open pages and messages on their way find it again). It does not hold up the start. Never
730
- // in the tests, which drive the App themselves, nor in the self-check, which sets CLAUDE_PRO_ONLINE=0.
735
+ // Whether this session should be online at the gateway (see remote.js): whenever this computer is logged in to
736
+ // it. CLAUDE_PRO_ONLINE=0 keeps it off (the self-check sets it); the tests, which drive the App themselves, go
737
+ // online only with CLAUDE_PRO_ONLINE=1.
738
+ onlineWanted() {
739
+ const env = this.config.env;
740
+ if (!onlineEnabled(env)) return false;
741
+ if (this.driven && !/^(1|true|yes|on)$/i.test(env.CLAUDE_PRO_ONLINE || '')) return false;
742
+ return Boolean(readGatewayLogin(this.config.gatewayUrl));
743
+ }
744
+
745
+ // Online at the gateway from the start, without holding the start up: when this computer is logged in to it; with
746
+ // --remote-id (a session the gateway's web page opened through claude-pro host: online at once, with the id the
747
+ // page waits for); and after a restart as before (with the same id, so that open pages and messages on their way
748
+ // find it again).
731
749
  autoStartRemote(restart) {
732
- const carried = restart?.remote;
733
- if (carried?.off) { this.remoteStopped = true; return; }
734
- const explicit = Boolean(this.flags.remoteControl);
735
- if (this.driven && !explicit) return;
736
- if (!explicit && !carried?.id && !(onlineEnabled(this.config.env) && readGatewayLogin(this.config.gatewayUrl))) return;
737
- this.startRemote({ id: carried?.id, quiet: !explicit || Boolean(carried?.id), persistent: !explicit }).catch((e) => {
738
- this.notice(`${explicit ? 'Remote control could not start' : 'This session could not go online at the gateway'}: ${e.message}${e.code === 'NO_GATEWAY_LOGIN' ? '' : ' (/rc tries again)'}`, 'warn');
750
+ const id = restart?.remote?.id || this.flags.remoteId || null;
751
+ if (!id && !this.onlineWanted()) return;
752
+ this.startRemote({ id }).catch((e) => {
753
+ if (e.code === 'NO_GATEWAY_LOGIN' && !this.flags.remoteId) return;
754
+ this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
739
755
  });
740
756
  }
741
757
 
742
758
  // Connect this session to the gateway (see remote.js): the web page and the sessions on the account's other
743
- // computers reach it from then on. Needs the gateway login of /login (the provider can be another one); throws
744
- // {code: 'NO_GATEWAY_LOGIN'} without it. `persistent`: a gateway that cannot be reached now is tried again in
745
- // the background instead of failing.
746
- startRemote({ id, quiet = false, persistent = quiet } = {}) {
759
+ // computers reach it from then on. Needs the gateway login of /login (the provider of the model requests can be
760
+ // another one); throws {code: 'NO_GATEWAY_LOGIN'} without it. A gateway that cannot be reached now is tried
761
+ // again in the background; one that refuses the key throws, and that key is not tried again (see syncRemote).
762
+ startRemote({ id } = {}) {
747
763
  if (this.remote) return Promise.resolve(this.remote);
748
- this.remoteStarting ??= this.connectRemote({ id, quiet, persistent }).finally(() => { this.remoteStarting = null; });
764
+ this.remoteStarting ??= this.connectRemote({ id }).finally(() => { this.remoteStarting = null; });
749
765
  return this.remoteStarting;
750
766
  }
751
767
 
752
- async connectRemote({ id, quiet, persistent }) {
768
+ // Online or offline as this computer's gateway login is now: after /login and /logout, and every few seconds (a
769
+ // login or a logout in another window, another account). Resolves with the connection, or null.
770
+ syncRemote() {
771
+ if (this.exiting) return Promise.resolve(null);
772
+ if (this.remoteStarting) return this.remoteStarting.catch(() => null);
773
+ const login = readGatewayLogin(this.config.gatewayUrl);
774
+ const r = this.remote;
775
+ // logged out, or another account: not this account's session any more
776
+ if (r && (!login || login.apiKey !== r.apiKey || normalizeGatewayUrl(login.url || this.config.gatewayUrl) !== normalizeGatewayUrl(r.base))) this.stopRemote();
777
+ if (this.remote) return Promise.resolve(this.remote);
778
+ if (!login || login.apiKey === this.remoteRefused || !(this.flags.remoteId || this.onlineWanted())) return Promise.resolve(null);
779
+ return this.startRemote().catch((e) => {
780
+ this.notice(`This session could not go online at the gateway: ${e.message}`, 'warn');
781
+ return null;
782
+ });
783
+ }
784
+
785
+ // The computer service (see host.js): started in the background when none runs, so that the gateway's web page can
786
+ // open sessions on this computer even when no session is open. Not in the tests nor in the self-check.
787
+ ensureHost() {
788
+ const env = this.config.env;
789
+ if (this.driven || this.selfCheck || process.env.NODE_TEST_CONTEXT || this.exiting) return;
790
+ if (!onlineEnabled(env) || !hostEnabled(env) || !readGatewayLogin(this.config.gatewayUrl)) return;
791
+ try { startHostIfNeeded(); } catch { /* the next session tries again */ }
792
+ }
793
+
794
+ async connectRemote({ id }) {
753
795
  const login = readGatewayLogin(this.config.gatewayUrl);
754
- if (!login) throw Object.assign(new Error(`it goes through the gateway ${this.config.gatewayUrl}, and this machine is not logged in to it: run /rc to log in`), { code: 'NO_GATEWAY_LOGIN' });
796
+ 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' });
755
797
  const remote = new RemoteControl({
756
798
  gateway: { url: login.url || this.config.gatewayUrl, apiKey: login.apiKey },
757
799
  id,
@@ -770,13 +812,17 @@ export class App {
770
812
  },
771
813
  });
772
814
  remote.account = login.account?.email || login.account?.name || null;
773
- await remote.start({ persistent });
815
+ try {
816
+ await remote.start({ persistent: true });
817
+ } catch (e) {
818
+ if (e.status === 401 || e.status === 403) this.remoteRefused = login.apiKey;
819
+ throw e;
820
+ }
774
821
  if (this.exiting) { remote.close(); return remote; }
775
822
  this.remote = remote;
776
- this.remoteStopped = false;
823
+ this.remoteRefused = null;
777
824
  this.remotePeersTimer ??= setInterval(() => { if (this.remote?.online) this.refreshRemotePeers(); }, 60_000);
778
825
  this.remotePeersTimer.unref?.();
779
- if (!quiet) this.logLocal(this.remoteInfo({ fresh: true }));
780
826
  this.screen.schedule();
781
827
  return remote;
782
828
  }
@@ -785,26 +831,24 @@ export class App {
785
831
  this.remote?.close();
786
832
  this.remote = null;
787
833
  this.remotePeers = [];
788
- this.remoteStopped = true;
789
834
  this.screen.schedule();
790
835
  }
791
836
 
792
- // Where the session is on the gateway (and a QR code of it, for a phone), for the terminal.
793
- remoteInfo({ fresh = false } = {}) {
837
+ // This session at the gateway, for /status: {text, url} (url: its page, once registered).
838
+ remoteState() {
794
839
  const r = this.remote;
795
- const state = !r.online ? (fresh ? c.dim(' · connecting') : c.yellow(' · not connected now, retrying')) : r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
796
- const lines = [`${c.green('⇄')} ${c.bold('This session is online at the gateway')}${r.account ? ` (${r.account})` : ''}${state}. In a browser:`];
797
- lines.push(` ${c.blue(r.url || r.base)}`);
798
- const qr = r.url ? qrLines(r.url, { color: colorEnabled }) : null;
799
- if (qr) lines.push('', c.dim(' Scan with a phone (log in to the gateway there):'), ...qr.map((l) => ' ' + l));
800
- const notes = [
801
- `It is under 远程控制 in the gateway's user pages (${r.base}), for this gateway account only. Messages typed there go in as if typed here (/commands and !shell too); questions and plan approvals can be answered there; Stop = Esc.`,
802
- `Sessions on your other computers send it tasks with &${machineName(this.config.env)}/${this.peerLabel()} (or &${machineName(this.config.env)} when it is the only session on this computer); /peers lists them all, /rename names this one.`,
803
- 'Whoever can log in to this gateway account, or holds one of its API keys, can run anything on this computer through it.',
804
- '/rc stop takes this session offline · /rc open opens the page in the browser here',
805
- ];
806
- lines.push('', ...notes.flatMap((n) => wordWrap(n, Math.max(20, this.width - 4))).map((l) => c.dim(` ${l.trimEnd()}`)), '');
807
- return lines;
840
+ if (r) {
841
+ const who = r.account ? ` as ${r.account}` : '';
842
+ const pages = r.viewers ? c.dim(` · ${r.viewers} page${r.viewers === 1 ? '' : 's'} open now`) : '';
843
+ const text = r.online ? `${c.green('online')}${who}${pages}` : r.registered ? c.yellow(`not connected now, retrying${who}`) : `connecting to ${r.base}${who}…`;
844
+ return { text, url: r.url };
845
+ }
846
+ if (this.remoteStarting) return { text: 'connecting…', url: null };
847
+ const login = readGatewayLogin(this.config.gatewayUrl);
848
+ if (!login) return { text: c.dim(`offline: this computer is not logged in to the gateway ${this.config.gatewayUrl} (/login)`), url: null };
849
+ if (login.apiKey === this.remoteRefused) return { text: c.red('offline: the gateway refused this computer\'s key (/logout, then /login)'), url: null };
850
+ if (!onlineEnabled(this.config.env)) return { text: c.dim('offline (CLAUDE_PRO_ONLINE=0)'), url: null };
851
+ return { text: c.dim('offline'), url: null };
808
852
  }
809
853
 
810
854
  // The state the page shows below the transcript; sent whenever it changes.
@@ -954,7 +998,7 @@ export class App {
954
998
  restarts: [...this.restarts.filter((t) => now - t < RESTART_WINDOW_MS), now],
955
999
  peerName: this.peers?.name || this.sessionName,
956
1000
  peerId: this.peers?.id,
957
- remote: this.remote?.handoff() || (this.remoteStopped ? { off: true } : null),
1001
+ remote: this.remote?.handoff() || null,
958
1002
  };
959
1003
  try {
960
1004
  writeRestartState(state);
@@ -1795,7 +1839,7 @@ export class App {
1795
1839
  this.agent.lastContextTokens = estimateTokens(loaded.messages);
1796
1840
  // Continue behind the system prompt the conversation had (and its cache), not a freshly built one.
1797
1841
  this.store.systemPrompt = loaded.systemPrompt;
1798
- this.runtime.resumeSystemPrompt(loaded.systemPrompt);
1842
+ this.runtime.resumeSystemPrompt(loaded.systemPrompt, loaded.promptCode);
1799
1843
  if (!this.topic) this.refreshTopic(this.latestPrompt()); // a session from before topics were kept
1800
1844
  this.remote?.resync();
1801
1845
  if (quiet) return;