@yanzc/claude-pro 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/session.js CHANGED
@@ -7,6 +7,8 @@ import path from 'node:path';
7
7
  import crypto from 'node:crypto';
8
8
  import { CONFIG_DIR } from './config.js';
9
9
  import { PROMPT_CODE_VERSION } from './prompts.js';
10
+ import { processAlive } from './utils/shell.js';
11
+ import { listPeers } from './peers.js';
10
12
 
11
13
  // The directory of a project's state (conversations, memory, checkpoints, traces): its path with every character
12
14
  // but a-z, A-Z and 0-9 made '-', as Claude Code names it. A path with characters beyond ASCII in it also gets a hash
@@ -93,23 +95,117 @@ export function checkpointsDir(cwd) {
93
95
  return path.join(projectDir(cwd), 'checkpoints');
94
96
  }
95
97
 
98
+ // 归档 (archived) conversations: put away from the web console's workspace, kept whole, and never deleted by age
99
+ // (sweepOldData). A mark in CONFIG_DIR/archived.json ({id: {at}}); the conversation's file stays where it is, so
100
+ // /resume and --resume still find it.
101
+ const archivedFile = () => path.join(CONFIG_DIR, 'archived.json');
102
+ export function archivedSessions() {
103
+ try {
104
+ const data = JSON.parse(fs.readFileSync(archivedFile(), 'utf8'));
105
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
106
+ } catch { return {}; }
107
+ }
108
+ export function setArchived(ids, archived = true) {
109
+ const data = archivedSessions();
110
+ const at = Date.now();
111
+ for (const id of ids) {
112
+ if (typeof id !== 'string' || !id) continue;
113
+ if (archived) data[id] = { at };
114
+ else delete data[id];
115
+ }
116
+ fs.mkdirSync(path.dirname(archivedFile()), { recursive: true });
117
+ const tmp = `${archivedFile()}.${process.pid}.tmp`;
118
+ fs.writeFileSync(tmp, JSON.stringify(data));
119
+ fs.renameSync(tmp, archivedFile());
120
+ return data;
121
+ }
122
+
123
+ // Ownership is independent of peer servers: even --print and CLAUDE_PRO_PEERS=0 can own a transcript.
124
+ // Both sides publish their intent before checking the other's marks. If a sweep got there first, the resume
125
+ // must not read the transcript until it can claim it; if the owner got there first, the sweep leaves it alone.
126
+ function markSession(id, kind) {
127
+ const key = crypto.createHash('sha256').update(process.platform === 'win32' ? id.toLowerCase() : id).digest('hex');
128
+ const dir = path.join(CONFIG_DIR, 'session-owners', key);
129
+ const file = path.join(dir, `${kind}-${process.pid}-${crypto.randomUUID()}`);
130
+ const create = () => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, '', { flag: 'wx' }); };
131
+ try { create(); } catch (e) { if (e.code !== 'ENOENT') throw e; create(); } // a concurrent release removed the empty dir
132
+ return {
133
+ dir,
134
+ close() {
135
+ try { fs.unlinkSync(file); } catch { /* already gone, or still protected */ }
136
+ try { fs.rmdirSync(dir); } catch { /* still in use */ }
137
+ },
138
+ };
139
+ }
140
+
141
+ function hasSessionMark(dir, kind) {
142
+ return fs.readdirSync(dir).some((name) => {
143
+ const [, type, pid] = /^(owner|sweep)-(\d+)-/.exec(name) || [];
144
+ if (!type) return false;
145
+ if (processAlive(Number(pid))) return type === kind;
146
+ try { fs.unlinkSync(path.join(dir, name)); } catch { /* already gone */ }
147
+ return false;
148
+ });
149
+ }
150
+
151
+ export function claimSession(id) {
152
+ const mark = markSession(id, 'owner');
153
+ try {
154
+ if (hasSessionMark(mark.dir, 'sweep')) throw new Error(`Session ${id} is being checked for expiration; try again.`);
155
+ return mark.close;
156
+ } catch (e) {
157
+ mark.close();
158
+ throw e;
159
+ }
160
+ }
161
+
162
+ // During an upgrade an older process may not publish ownership marks yet. Peer IDs aren't transcript IDs,
163
+ // and /status can time out or change after a /resume. Conservatively keep its project's transcripts and traces.
164
+ // (A process of this version says so in its peer file and is covered by its marks.)
165
+ function foreignPeerIn(dir) {
166
+ return listPeers().some(({ pid, cwd, sessionClaims }) => {
167
+ if (pid === process.pid || sessionClaims) return false;
168
+ if (typeof cwd !== 'string' || !cwd) return true;
169
+ const abs = path.resolve(cwd);
170
+ const name = abs.replace(/[^a-zA-Z0-9]/g, '-');
171
+ const key = pathKey(dir);
172
+ const legacy = path.join(path.dirname(dir), name);
173
+ return key === pathKey(legacy) || key === pathKey(`${legacy}-${pathHash(abs)}`);
174
+ });
175
+ }
176
+
96
177
  // Delete what is older than `days` (the cleanupPeriodDays setting, as in Claude Code: 30 by default), in every
97
178
  // project: conversations not written to since (they no longer appear in /resume), their traces, saved tool outputs
98
179
  // (at most 7 days) and /rewind snapshots (at most 14 days). The memory is never touched. Conversations were kept
99
180
  // for good before: 646 MB in 176 files in a month (2026-11-11), of which only the current project's tool outputs,
100
181
  // snapshots and traces were deleted, and only when a session started there. Runs in the background, at most once
101
- // an hour on the machine (`marker`); `keep`: conversation ids not to delete whatever their age. Returns what went.
102
- export async function sweepOldData({ days, keep = [], root = path.join(CONFIG_DIR, 'projects'), now = Date.now() } = {}) {
182
+ // an hour on the machine (`marker`); `keep`: conversation ids not to delete whatever their age (and the archived
183
+ // ones are never deleted). `isOwned` is a synchronous fallback for owners without a claim. Returns what went.
184
+ export async function sweepOldData({ days, keep = [], isOwned = () => false, root = path.join(CONFIG_DIR, 'projects'), now = Date.now() } = {}) {
103
185
  const done = { conversations: 0, files: 0, bytes: 0 };
104
186
  if (!(days >= 1)) return done;
105
187
  const marker = path.join(root, '.last-sweep');
106
188
  try { if (now - fs.statSync(marker).mtimeMs < 3600_000) return done; } catch { /* never swept */ }
107
189
  try { fs.mkdirSync(root, { recursive: true }); fs.writeFileSync(marker, ''); } catch { return done; }
108
190
  const day = 24 * 3600_000;
109
- const keepIds = new Set(keep.filter(Boolean));
191
+ const keepIds = new Set([...keep.filter(Boolean), ...Object.keys(archivedSessions())]);
110
192
  const fsp = fs.promises;
111
193
  const list = async (dir) => { try { return await fsp.readdir(dir, { withFileTypes: true }); } catch { return []; } };
112
194
  const old = async (file, maxAgeMs) => { try { return now - (await fsp.stat(file)).mtimeMs > maxAgeMs; } catch { return false; } };
195
+ const removeSessionFile = (file, id, dir) => {
196
+ let mark;
197
+ try {
198
+ mark = markSession(id, 'sweep');
199
+ // Check after the async age test, then keep the ownership check, final stat and unlink together.
200
+ if (hasSessionMark(mark.dir, 'owner') || isOwned(id, dir) || foreignPeerIn(dir) || Object.hasOwn(archivedSessions(), id)) return false;
201
+ const stats = fs.statSync(file);
202
+ if (now - stats.mtimeMs <= days * day) return false;
203
+ fs.unlinkSync(file);
204
+ done.files++;
205
+ done.bytes += stats.size;
206
+ return true;
207
+ } catch { return false; } finally { mark?.close(); }
208
+ };
113
209
  const remove = async (file, isDir = false) => {
114
210
  try {
115
211
  const size = isDir ? 0 : (await fsp.stat(file)).size;
@@ -119,17 +215,26 @@ export async function sweepOldData({ days, keep = [], root = path.join(CONFIG_DI
119
215
  return true;
120
216
  } catch { return false; }
121
217
  };
218
+ // marks left by processes that ended without releasing them (a crash): nothing else removes them
219
+ const owners = path.join(CONFIG_DIR, 'session-owners');
220
+ for (const d of await list(owners)) {
221
+ if (!d.isDirectory()) continue;
222
+ try { hasSessionMark(path.join(owners, d.name), 'owner'); } catch { /* gone meanwhile */ }
223
+ try { fs.rmdirSync(path.join(owners, d.name)); } catch { /* still in use */ }
224
+ }
122
225
  for (const project of await list(root)) {
123
226
  if (!project.isDirectory()) continue;
124
227
  const dir = path.join(root, project.name);
125
228
  for (const e of await list(dir)) {
126
229
  const id = e.name.replace(/\.jsonl$/, '');
127
230
  if (!e.isFile() || id === e.name || keepIds.has(id)) continue;
128
- if (await old(path.join(dir, e.name), days * day) && (await remove(path.join(dir, e.name)))) done.conversations++;
231
+ const f = path.join(dir, e.name);
232
+ if (await old(f, days * day) && removeSessionFile(f, id, dir)) done.conversations++;
129
233
  }
130
234
  for (const e of await list(path.join(dir, 'traces'))) { // a conversation's trace is written with it
131
235
  const f = path.join(dir, 'traces', e.name);
132
- if (!keepIds.has(e.name.replace(/\.jsonl(\.\d+)?$/, '')) && (await old(f, days * day))) await remove(f);
236
+ const id = e.name.replace(/\.jsonl(\.\d+)?$/, '');
237
+ if (!keepIds.has(id) && (await old(f, days * day))) removeSessionFile(f, id, dir);
133
238
  }
134
239
  for (const e of await list(path.join(dir, 'tool-results'))) {
135
240
  const f = path.join(dir, 'tool-results', e.name);
@@ -174,6 +279,7 @@ export function moveSession(file, id, cwd) {
174
279
 
175
280
  export class SessionStore {
176
281
  static onError = null; // (error, store): a write of the conversation failed (the first time for a store)
282
+ onError = null; // the same for this store alone (its session's: the web console runs several in one process)
177
283
 
178
284
  constructor(cwd, id = crypto.randomUUID()) {
179
285
  this.cwd = cwd;
@@ -195,7 +301,7 @@ export class SessionStore {
195
301
  // Best effort, but a message that did not get in leaves the file without it, and a restart or /resume would go
196
302
  // on from a conversation that lacks it: noted (`lost`, see App.restartNow), and said once (SessionStore.onError).
197
303
  this.lost = true;
198
- if (!this.warned) { this.warned = true; try { SessionStore.onError?.(e, this); } catch { /* ignore */ } }
304
+ if (!this.warned) { this.warned = true; try { (this.onError || SessionStore.onError)?.(e, this); } catch { /* ignore */ } }
199
305
  }
200
306
  }
201
307
 
@@ -205,6 +311,11 @@ export class SessionStore {
205
311
  // The name the user gave the conversation with /rename (null: none again); it wins over the topic.
206
312
  setName(name) { this.append({ type: 'meta', name, at: Date.now() }); }
207
313
  reset(messages) { this.append({ type: 'reset', messages, at: Date.now() }); }
314
+ // Where a turn ended (after how many messages) and the line shown then ("✻ Done at 14:05 · worked 1m 3s · …"):
315
+ // the web console's view is rebuilt from the conversation (a reload, a restart) and puts it back under the answer.
316
+ turnEnd(after, text) { this.append({ type: 'turn', after, text, at: Date.now() }); }
317
+ // All of them again after the messages were replaced: a reset drops those before it (see App.messagesReplaced).
318
+ setTurns(marks) { this.append({ type: 'turns', marks: marks.map(({ after, text }) => ({ after, text })), at: Date.now() }); }
208
319
  // What the conversation's requests have cost so far (USD, see pricing.js), written after each one; the newest wins.
209
320
  setCost(usd) { this.append({ type: 'meta', cost: usd, at: Date.now() }); }
210
321
  // Until when the conversation's prompt cache lasts (ms since epoch; 0: cold), for the footer's clock of a
@@ -235,6 +346,7 @@ export class SessionStore {
235
346
  let meta = {};
236
347
  let title = null;
237
348
  let lastAt = 0; // when the conversation last changed: the latest message or reset (0: unknown)
349
+ let turns = []; // [{after, text}]: see turnEnd
238
350
  for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
239
351
  if (!line.trim()) continue;
240
352
  let e;
@@ -242,6 +354,8 @@ export class SessionStore {
242
354
  if (e.type === 'message' || e.type === 'reset') lastAt = Math.max(lastAt, e.at || 0);
243
355
  if (e.type === 'reset') meta = { ...meta, cacheState: null }; // what was cached is not the new messages' prefix
244
356
  if (e.type === 'meta') meta = { ...meta, ...e };
357
+ else if (e.type === 'turn') turns.push({ after: e.after, text: e.text });
358
+ else if (e.type === 'turns') turns = Array.isArray(e.marks) ? e.marks.slice() : [];
245
359
  else if (e.type === 'message') {
246
360
  messages.push(e.message);
247
361
  times.push(e.at || 0);
@@ -251,10 +365,13 @@ export class SessionStore {
251
365
  // so their own times are unknown.
252
366
  messages.splice(0, messages.length, ...e.messages);
253
367
  times.splice(0, times.length, ...e.messages.map(() => 0));
368
+ turns = [];
254
369
  }
255
370
  }
371
+ turns = turns.filter((t) => Number.isInteger(t?.after) && t.after >= 1 && t.after <= messages.length && typeof t.text === 'string' && t.text)
372
+ .sort((a, b) => a.after - b.after);
256
373
  return {
257
- messages, times, lastAt, meta, title,
374
+ messages, times, lastAt, meta, title, turns,
258
375
  topic: typeof meta.topic === 'string' && meta.topic.trim() ? meta.topic : null,
259
376
  name: typeof meta.name === 'string' && meta.name.trim() ? meta.name : null,
260
377
  systemPrompt: typeof meta.systemPrompt === 'string' && meta.systemPrompt.trim() ? meta.systemPrompt : null,
@@ -312,5 +429,8 @@ const SESSION_INDEX = 'sessions-index.json';
312
429
  export function firstUserText(message) {
313
430
  const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content;
314
431
  const t = blocks.find((b) => b.type === 'text' && !b.text.startsWith('<system-reminder>') && !b.text.startsWith('['));
315
- return t ? t.text.replace(/\s+/g, ' ').trim().slice(0, 100) : null;
432
+ if (!t) return null;
433
+ // a command of bash mode (!cmd): the command, as it was typed
434
+ const bash = /^<bash-input>([\s\S]*?)<\/bash-input>/.exec(t.text);
435
+ return (bash ? `! ${bash[1]}` : t.text).replace(/\s+/g, ' ').trim().slice(0, 100);
316
436
  }
package/src/supervisor.js CHANGED
@@ -41,7 +41,7 @@ export function sessionEntry(entry, platform = process.platform) {
41
41
  // Whether this invocation is an interactive session that should run under the supervisor.
42
42
  export function shouldSupervise(argv, env = process.env, isTty = (fd) => tty.isatty(fd)) {
43
43
  if (env[ENV_SUPERVISED] || /^(1|true|yes)$/i.test(env.CLAUDE_PRO_NO_SUPERVISOR || '')) return false;
44
- if (['config', 'host', 'attach', 'connect'].includes(argv[0])) return false; // a command, or a removed one (see main.js)
44
+ if (['config', 'web', 'host', 'attach', 'connect'].includes(argv[0])) return false; // a command, or a removed one (see main.js)
45
45
  if (!isTty(0) || !isTty(1)) return false;
46
46
  return !argv.some((a) => NOT_INTERACTIVE.has(a));
47
47
  }
package/src/tools/bash.js CHANGED
@@ -8,7 +8,11 @@ import { stripAnsi } from '../ui/ansi.js';
8
8
  import { OutputDecoder } from '../utils/encoding.js';
9
9
  import { toolResultsDir } from '../session.js';
10
10
 
11
- const background = new Map(); // id -> {child, command, output, readPos, status, exitCode, startedAt}
11
+ // id -> {owner, child, command, output, readPos, status, exitCode, startedAt}. `owner`: the session's (config.owner):
12
+ // the web console runs several sessions in one process, and each sees and stops only its own shells.
13
+ const background = new Map();
14
+ const ownedBy = (bg, owner) => !owner || !bg.owner || bg.owner === owner;
15
+ const shellOf = (id, owner) => { const bg = background.get(id); return bg && ownedBy(bg, owner) ? bg : null; };
12
16
  let bgCounter = 0;
13
17
  const PROGRESS_CHARS = 8192; // the end of the output the live view gets while a command runs
14
18
 
@@ -46,13 +50,18 @@ export function appendOutput(bg, text, max = 5_000_000, keep = 2_000_000) {
46
50
 
47
51
  export { childEnv };
48
52
 
49
- export function shutdownBackgroundShells() {
50
- // the program is exiting; `orphans`: a shell that has ended but is still "running" left something holding its output
51
- for (const bg of background.values()) if (bg.status === 'running') killTreeSync(bg.child, { orphans: true });
53
+ // The session `owner` ends (every session when not given: the program is exiting).
54
+ export function shutdownBackgroundShells(owner) {
55
+ for (const [id, bg] of background) {
56
+ if (!ownedBy(bg, owner)) continue;
57
+ // `orphans`: a shell that has ended but is still "running" left something holding its output
58
+ if (bg.status === 'running') killTreeSync(bg.child, { orphans: true });
59
+ if (owner) background.delete(id);
60
+ }
52
61
  }
53
62
 
54
- export function listBackgroundShells() {
55
- return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, description: bg.description || '', status: bg.status, exitCode: bg.exitCode, startedAt: bg.startedAt }));
63
+ export function listBackgroundShells(owner) {
64
+ return [...background.entries()].filter(([, bg]) => ownedBy(bg, owner)).map(([id, bg]) => ({ id, command: bg.command, description: bg.description || '', status: bg.status, exitCode: bg.exitCode, startedAt: bg.startedAt }));
56
65
  }
57
66
 
58
67
  export function makeBashTool(config) {
@@ -98,10 +107,10 @@ When you commit (the system prompt says when): run git status, git diff and git
98
107
  if (input.run_in_background) {
99
108
  const child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
100
109
  const id = `bash_${++bgCounter}`;
101
- const bg = { child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
110
+ const bg = { owner: config.owner || null, child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
102
111
  background.set(id, bg);
103
112
  // the shells that ended stay listed, with what was not read of their output: the oldest go past 50
104
- const ended = [...background].filter(([, b]) => b.status !== 'running');
113
+ const ended = [...background].filter(([, b]) => b.status !== 'running' && b.owner === bg.owner);
105
114
  for (const [old] of ended.slice(0, Math.max(0, ended.length - 50))) background.delete(old);
106
115
  // Line by line, UTF-8 or the console code page (GBK here), never cutting a character (see OutputDecoder).
107
116
  for (const stream of [child.stdout, child.stderr]) {
@@ -189,8 +198,8 @@ export const BashOutputTool = {
189
198
  },
190
199
  summarize(input) { return input.bash_id; },
191
200
  async call(input, ctx = {}) {
192
- const bg = background.get(input.bash_id);
193
- if (!bg) return { isError: true, content: `No background shell with id ${input.bash_id}. Known: ${[...background.keys()].join(', ') || 'none'}` };
201
+ const bg = shellOf(input.bash_id, ctx.config?.owner);
202
+ if (!bg) return { isError: true, content: `No background shell with id ${input.bash_id}. Known: ${listBackgroundShells(ctx.config?.owner).map((s) => s.id).join(', ') || 'none'}` };
194
203
  let fresh = bg.output.slice(bg.readPos);
195
204
  bg.output = ''; // what was read is not read again (up to 5 MB a shell, kept for good before)
196
205
  bg.readPos = 0;
@@ -222,8 +231,8 @@ export const KillShellTool = {
222
231
  required: ['shell_id'],
223
232
  },
224
233
  summarize(input) { return input.shell_id; },
225
- async call(input) {
226
- const bg = background.get(input.shell_id);
234
+ async call(input, ctx = {}) {
235
+ const bg = shellOf(input.shell_id, ctx.config?.owner);
227
236
  if (!bg) return { isError: true, content: `No background shell with id ${input.shell_id}` };
228
237
  if (bg.status !== 'running') return { content: `Shell ${input.shell_id} is not running (status: ${bg.status})` };
229
238
  bg.status = 'killed';
@@ -4,11 +4,16 @@
4
4
 
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
- import { browserSession, BrowserError, CdpError, refId, safeUrl } from '../browser/session.js';
7
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import { browserSessionFor, BrowserError, CdpError, refId, safeUrl } from '../browser/session.js';
8
9
  import { snapshotLines, renderLines, diffLines, renderDiff, findLines } from '../browser/snapshot.js';
9
10
  import { CONFIG_DIR } from '../config.js';
10
11
  import { resolvePath } from '../utils/paths.js';
11
12
 
13
+ // The browser session of the call being run: the session's own (see browserSessionFor), passed down the call.
14
+ const current = new AsyncLocalStorage();
15
+ const session = () => current.getStore();
16
+
12
17
  export const browserToolLimits = { snapshotChars: 10_000, diffLines: 60, diffChars: 5_000, textChars: 30_000, evalChars: 20_000, findMatches: 30 };
13
18
 
14
19
  const ACTIONS = ['tabs', 'open', 'switch', 'navigate', 'back', 'forward', 'reload', 'close', 'snapshot', 'find', 'text', 'click', 'type', 'press', 'hover', 'scroll', 'select', 'upload', 'wait', 'eval', 'screenshot', 'dialog', 'disconnect'];
@@ -78,7 +83,7 @@ const header = (tab) => `${tab.id} ${cut(tab.url || '', 200)}${tab.title ? ` —
78
83
  // text and the links' addresses too (what find searches, and what the changes after an action are taken from, so
79
84
  // that a message or a counter that changes shows up).
80
85
  async function readPage(tab) {
81
- const trees = await browserSession.trees(tab);
86
+ const trees = await session().trees(tab);
82
87
  const title = trees.main?.find((n) => !n.parentId)?.name?.value; // the document's title, before the browser reports it
83
88
  if (title) tab.title = title;
84
89
  return {
@@ -104,7 +109,7 @@ function named(tab, ref) {
104
109
 
105
110
  // A tab by id (t3f9a; see BrowserSession.relabel) or by words of its title or address.
106
111
  function findTab(spec) {
107
- const s = browserSession;
112
+ const s = session();
108
113
  const want = String(spec ?? '').trim();
109
114
  if (!want) throw new BrowserError('switch needs tab: an id from tabs, or words of its title or address');
110
115
  if (/^t(?:\d+|[0-9a-f]{4,})$/i.test(want)) return s.tab(want);
@@ -116,7 +121,7 @@ function findTab(spec) {
116
121
  }
117
122
 
118
123
  async function step(input, ctx) {
119
- const s = browserSession;
124
+ const s = session();
120
125
  const a = input.action;
121
126
  const need = (field) => {
122
127
  if (input[field] === undefined || input[field] === null || input[field] === '') throw new BrowserError(`${a} needs ${field}`);
@@ -234,7 +239,7 @@ async function step(input, ctx) {
234
239
 
235
240
  // The page after what was done: what changed since the last snapshot, or the page itself.
236
241
  async function pageState(tab, kind) {
237
- const s = browserSession;
242
+ const s = session();
238
243
  await s.settle(tab);
239
244
  if (tab.dialog) return `A ${tab.dialog.type} dialog is open: ${JSON.stringify(tab.dialog.message)}. Answer it with dialog (accept: true or false${tab.dialog.type === 'prompt' ? ', text' : ''}).`;
240
245
  const page = await readPage(tab);
@@ -254,13 +259,13 @@ async function pageState(tab, kind) {
254
259
  // When the last step read the page (switch, then find): only where the tab is, the page not shown again. It is
255
260
  // still recorded, so that the next action shows what it changed instead of the whole page.
256
261
  async function quietState(tab, unsettled) {
257
- if (unsettled) await browserSession.settle(tab);
262
+ if (unsettled) await session().settle(tab);
258
263
  if (!tab.dialog) remember(tab, await readPage(tab));
259
264
  return header(tab);
260
265
  }
261
266
 
262
267
  async function run(input, ctx) {
263
- const s = browserSession;
268
+ const s = session();
264
269
  const steps = Array.isArray(input.steps) && input.steps.length ? input.steps : [input];
265
270
  if (steps.some((x) => !x || typeof x !== 'object' || !x.action)) {
266
271
  return { isError: true, content: 'Each call needs an action (or steps: a list of {action, …}).' };
@@ -359,7 +364,8 @@ export function makeBrowserTool() {
359
364
  return one(input);
360
365
  },
361
366
  async call(input, ctx) {
362
- return browserSession.run(ctx.signal, () => run(input, ctx));
367
+ const s = browserSessionFor(ctx.config?.owner);
368
+ return s.run(ctx.signal, () => current.run(s, () => run(input, ctx)));
363
369
  },
364
370
  };
365
371
  }
package/src/tools/code.js CHANGED
@@ -329,11 +329,17 @@ class Interpreter {
329
329
  }
330
330
  }
331
331
 
332
- const interpreters = new Map(); // language -> Interpreter
332
+ // "<owner> <language>" -> Interpreter. The owner is the session's (config.owner): the web console runs several
333
+ // sessions in one process, and each has its own interpreters.
334
+ const interpreters = new Map();
333
335
 
334
- export function shutdownInterpreters() {
335
- for (const i of interpreters.values()) i.kill(true); // the program is exiting
336
- interpreters.clear();
336
+ // The session `owner` ends (all of them when not given: the program is exiting).
337
+ export function shutdownInterpreters(owner) {
338
+ for (const [key, i] of interpreters) {
339
+ if (owner && !key.startsWith(`${owner} `)) continue;
340
+ i.kill(true);
341
+ interpreters.delete(key);
342
+ }
337
343
  }
338
344
 
339
345
  const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
@@ -367,15 +373,16 @@ Use it to work with data: load a log, a JSON or CSV file, a database or an API r
367
373
  if (!lang) return { isError: true, content: 'language must be python or node' };
368
374
  const { label } = LANGUAGES[lang];
369
375
  const code = typeof input.code === 'string' ? input.code : '';
370
- let interp = interpreters.get(lang);
376
+ const key = `${config?.owner || ''} ${lang}`;
377
+ let interp = interpreters.get(key);
371
378
  const notes = [];
372
379
  if (input.reset && interp) {
373
380
  interp.kill();
374
- interpreters.delete(lang);
381
+ interpreters.delete(key);
375
382
  interp = null;
376
383
  notes.push(`(a new ${label} process: the old one's variables are gone)`);
377
384
  } else if (interp && !interp.alive) {
378
- interpreters.delete(lang);
385
+ interpreters.delete(key);
379
386
  interp = null;
380
387
  notes.push(`(the ${label} process had ended, so this is a new one: earlier variables are gone)`);
381
388
  }
@@ -386,24 +393,24 @@ Use it to work with data: load a log, a JSON or CSV file, a database or an API r
386
393
  const cwd = fs.existsSync(ctx.cwd) ? ctx.cwd : ctx.projectRoot;
387
394
  if (!interp) {
388
395
  interp = new Interpreter(lang, { cwd, env: ctx.config?.env });
389
- interpreters.set(lang, interp);
396
+ interpreters.set(key, interp);
390
397
  }
391
398
  const timeoutMs = Math.min(Math.max(1000, Number(input.timeout) || replLimits.defaultTimeoutMs), replLimits.maxTimeoutMs);
392
399
  const started = Date.now();
393
400
  const r = await interp.run(lang === 'node' ? rewriteDynamicImports(code) : code, { cwd, timeoutMs, signal: ctx.signal });
394
401
  if (r.startError) {
395
- interpreters.delete(lang);
402
+ interpreters.delete(key);
396
403
  const hint = lang === 'python' ? ` Is Python installed and on PATH? CLAUDE_PRO_PYTHON can name the interpreter (now: ${pythonCommand(ctx.config?.env)}).` : '';
397
404
  return { isError: true, content: `Cannot start ${label}: ${r.startError.message}.${hint}` };
398
405
  }
399
406
  if (r.aborted || ctx.signal?.aborted) {
400
- interpreters.delete(lang);
407
+ interpreters.delete(key);
401
408
  throw Object.assign(new Error('aborted'), { name: 'AbortError', partialOutput: r.output });
402
409
  }
403
410
  let text = stripAnsi([r.output, r.stderr ? `[stderr]\n${r.stderr.replace(/\s+$/, '')}` : ''].filter(Boolean).join('\n')).replace(/\r\n/g, '\n').replace(/\s+$/, '');
404
411
  let isError = false;
405
412
  if (r.died) {
406
- interpreters.delete(lang);
413
+ interpreters.delete(key);
407
414
  isError = true;
408
415
  const why = r.timedOut ? `timed out after ${timeoutMs / 1000} s and was stopped` : `ended (exit code ${interp.exited?.code ?? '?'})`;
409
416
  text += `${text ? '\n' : ''}The ${label} process ${why}: its variables are gone, and the next call starts a new one.`;
@@ -28,7 +28,7 @@ How it works:
28
28
  summarize(input) { return input.reason || ''; },
29
29
  async call(input, ctx) {
30
30
  const io = ctx.io;
31
- if (!canRestart() || typeof io?.requestRestart !== 'function') {
31
+ if (!(io?.canRestart ? io.canRestart() : canRestart()) || typeof io?.requestRestart !== 'function') {
32
32
  return { isError: true, content: `Restart is not available here: it needs an interactive session started with \`${APP_NAME}\` (not -p, and not with CLAUDE_PRO_NO_SUPERVISOR set). Ask the user to restart the program themselves.` };
33
33
  }
34
34
  const blockers = io.restartBlockers?.() || [];
package/src/ui/dialogs.js CHANGED
@@ -1,25 +1,18 @@
1
1
  // Modal dialogs rendered in the live region: selection menus (questions, the model and session pickers, /rewind),
2
2
  // with a typed answer of their own when they offer "Other", and a text field (/connect asks for a key or an address).
3
3
 
4
- import { c, glyphs, padEnd, stringWidth, truncate, wordWrap } from './ansi.js';
4
+ import { c, glyphs, stringWidth, truncate, wordWrap } from './ansi.js';
5
5
  import { Editor } from './editor.js';
6
6
 
7
- function box(lines, width, color) {
8
- const w = Math.max(20, width - 1);
9
- const inner = w - 4;
10
- const out = [color(glyphs.topLeft + '─'.repeat(w - 2) + glyphs.topRight)];
11
- for (const l of lines) {
12
- for (const part of stringWidth(l) > inner ? wordWrap(l, inner) : [l]) {
13
- out.push(color('│') + ' ' + padEnd(part, inner) + ' ' + color('│'));
14
- }
15
- }
16
- out.push(color(glyphs.bottomLeft + '─'.repeat(w - 2) + glyphs.bottomRight));
17
- return out;
7
+ // A dialog is drawn without a frame: its lines, the long ones wrapped between words.
8
+ const innerWidth = (width) => Math.max(20, width - 1);
9
+ function wrapAll(lines, width) {
10
+ const inner = innerWidth(width);
11
+ return lines.flatMap((l) => (stringWidth(l) > inner ? wordWrap(l, inner) : [l]));
18
12
  }
19
-
20
- // The rows `lines` take inside box(), which wraps the long ones.
21
- function boxRows(lines, width) {
22
- const inner = Math.max(20, width - 1) - 4;
13
+ // The rows `lines` take once wrapAll() has wrapped the long ones.
14
+ function rowsOf(lines, width) {
15
+ const inner = innerWidth(width);
23
16
  return lines.reduce((n, l) => n + (stringWidth(l) > inner ? wordWrap(l, inner).length : 1), 0);
24
17
  }
25
18
 
@@ -100,10 +93,10 @@ export class SelectDialog {
100
93
  lines.push(...this.body);
101
94
  if (this.body.length) lines.push('');
102
95
  if (this.question) lines.push(this.question);
103
- const inner = Math.max(20, width - 1) - 4;
96
+ const inner = innerWidth(width);
104
97
  // Show a window of options around the selection when they don't all fit.
105
98
  const perOption = this.options.some((o) => o.description) ? 2 : 1;
106
- const room = Math.max(3, Math.floor((maxHeight - boxRows(lines, width) - 4 - (this.other ? 5 : 0)) / perOption));
99
+ const room = Math.max(3, Math.floor((maxHeight - rowsOf(lines, width) - 2 - (this.other ? 3 : 0)) / perOption));
107
100
  let first = 0;
108
101
  if (this.options.length > room) first = Math.min(Math.max(0, this.selected - Math.floor(room / 2)), this.options.length - room);
109
102
  const last = Math.min(this.options.length, first + room);
@@ -120,12 +113,12 @@ export class SelectDialog {
120
113
  let cursor = null;
121
114
  if (this.other) {
122
115
  lines.push('');
123
- const r = this.other.render(width - 4, { placeholder: 'Type your answer, Enter to submit, Esc to go back' });
124
- const top = boxRows(lines, width) + 1; // the rows above it once box() has wrapped the long ones, and its top border
116
+ const r = this.other.render(width, { placeholder: 'Type your answer, Enter to submit, Esc to go back' });
117
+ const top = rowsOf(lines, width); // the rows above it once wrapAll() has wrapped the long ones
125
118
  lines.push(...r.lines.map((l) => truncate(l, inner)));
126
- if (r.cursor) cursor = { row: top + r.cursor.row, col: 2 + r.cursor.col };
119
+ if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
127
120
  }
128
- const out = box(lines, width, this.color);
121
+ const out = wrapAll(lines, width);
129
122
  const hint = this.footer ?? (this.multi ? 'Space to toggle · Enter to confirm · Esc to cancel' : 'Enter to confirm · Esc to cancel');
130
123
  out.push(c.dim(' ' + hint));
131
124
  return { lines: out, cursor };
@@ -186,23 +179,23 @@ export class TextInputDialog {
186
179
  lines.push(...this.body);
187
180
  if (this.body.length) lines.push('');
188
181
  if (this.question) lines.push(this.question);
189
- const inner = Math.max(20, width - 1) - 4;
182
+ const inner = innerWidth(width);
190
183
  let cursor = null;
191
184
  if (this.secret) {
192
185
  const n = this.value().length;
193
186
  const room = Math.max(4, inner - 20);
194
187
  const stars = n ? `${'*'.repeat(Math.min(n, room))}${n > room ? '...' : ''}` : '';
195
- const row = boxRows(lines, width) + 1; // the row it takes once box() has wrapped the long ones, and the top border
196
- lines.push(`> ${stars}${n ? c.dim(` (${n} characters)`) : c.dim(this.placeholder)}`);
197
- cursor = { row, col: 2 + 2 + stringWidth(stars) };
188
+ const row = rowsOf(lines, width); // the row it takes once wrapAll() has wrapped the long ones
189
+ lines.push(`${c.claude('>')} ${stars}${n ? c.dim(` (${n} characters)`) : c.dim(this.placeholder)}`);
190
+ cursor = { row, col: 2 + stringWidth(stars) };
198
191
  } else {
199
- const r = this.editor.render(width - 4, { placeholder: this.placeholder });
200
- const top = boxRows(lines, width) + 1;
192
+ const r = this.editor.render(width, { placeholder: this.placeholder });
193
+ const top = rowsOf(lines, width);
201
194
  lines.push(...r.lines.map((l) => truncate(l, inner)));
202
- if (r.cursor) cursor = { row: top + r.cursor.row, col: 2 + r.cursor.col };
195
+ if (r.cursor) cursor = { row: top + r.cursor.row, col: r.cursor.col };
203
196
  }
204
197
  if (this.error) lines.push('', c.red(this.error));
205
- const out = box(lines, width, this.color);
198
+ const out = wrapAll(lines, width);
206
199
  out.push(c.dim(` Enter to confirm · Esc to cancel${this.secret ? ' · Ctrl+V pastes' : ''}`));
207
200
  return { lines: out, cursor };
208
201
  }