@yanzc/claude-pro 0.6.0 → 0.7.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yanzc/claude-pro",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "claude-pro: a self-implemented coding agent for Anthropic-compatible APIs or local Claude Code subscription login. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/agent.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { streamMessage, contextTokens, isAbort } from './api.js';
7
- import { compactPrompt, partialCompactPrompt, partialSummaryMessage, continuationMessage, PLAN_MODE_REMINDER, SUMMARY_SYSTEM } from './prompts.js';
7
+ import { compactPrompt, partialCompactPrompt, partialSummaryMessage, continuationMessage, SUMMARY_SYSTEM } from './prompts.js';
8
8
  import { toolResultsDir } from './session.js';
9
9
  import { rebuildFileState } from './filestate.js';
10
10
  import { CacheStats, TTL_MS } from './cache.js';
@@ -169,7 +169,7 @@ function validateInput(schema, input) {
169
169
  }
170
170
 
171
171
  export class Agent {
172
- constructor({ config, modes, tools, systemPrompt, io, model, isSubagent = false, cwd, name = 'main', spawnSubagent, hooks, tasks, checkpoints, depth = 0, refreshSystemPrompt, beforeTurn, effort, compactWindow = 0 }) {
172
+ constructor({ config, tools, systemPrompt, io, model, isSubagent = false, cwd, name = 'main', spawnSubagent, hooks, tasks, checkpoints, depth = 0, refreshSystemPrompt, beforeTurn, effort, compactWindow = 0 }) {
173
173
  this.config = config;
174
174
  this.effort = effort || undefined; // a sub-agent's own effort level; undefined: the session's (config.effort)
175
175
  this.compactWindow = compactWindow; // a sub-agent's own auto-compact window (tokens); 0: the session's
@@ -178,7 +178,6 @@ export class Agent {
178
178
  this.tasks = tasks; // background tasks (sub-agents started with run_in_background)
179
179
  this.notifications = []; // {taskId, text} waiting to be shown to the model
180
180
  this.editsThisRun = 0; // successful file edits since the last verification
181
- this.modes = modes; // session mode: full access, or read-only plan mode
182
181
  this.checkpoints = checkpoints; // snapshots of files before they are edited, per user prompt
183
182
  this.tools = tools;
184
183
  this.systemPrompt = systemPrompt; // string or () => string
@@ -189,6 +188,8 @@ export class Agent {
189
188
  this.spawnSubagent = spawnSubagent;
190
189
  this.messages = [];
191
190
  this.todos = [];
191
+ this.userTurns = 0; // turns the user started (see noteUserTurn)
192
+ this.todosTurn = 0; // ... and the one in which the todo list was last written
192
193
  this.fileState = new Map();
193
194
  this.projectRoot = cwd;
194
195
  this.cwd = cwd;
@@ -385,14 +386,25 @@ export class Agent {
385
386
  }
386
387
 
387
388
  // Run one user turn to completion. Returns {text, interrupted}.
389
+ // A turn the user started (a message of theirs, or a task from another session; not only a report of a background
390
+ // agent). The todo list belongs to a request: one that the whole turn before this one left as it was is done or
391
+ // dropped (its last items never ticked off, or one waiting for the user left in it), so it is put away instead of
392
+ // showing under the next task. The model writes a new one when it needs one.
393
+ noteUserTurn(content) {
394
+ const fromUser = toBlocks(content).some((b) => b.type === 'image' || (b.type === 'text' && !/^<(task-notification|system-reminder)>/.test(b.text)));
395
+ if (!fromUser) return;
396
+ this.userTurns++;
397
+ if (this.todos.length && this.todosTurn < this.userTurns - 1) this.todos = [];
398
+ }
399
+
388
400
  async run(userContent, { signal } = {}) {
389
401
  if (!this.isSubagent) {
390
402
  this.beforeTurn?.();
391
403
  this.endEffortBoost();
404
+ this.noteUserTurn(userContent);
392
405
  }
393
406
  this.clearAfterIdle();
394
407
  let content = toBlocks(userContent);
395
- if (this.modes.mode === 'plan' && !this.isSubagent) content = [...content, { type: 'text', text: PLAN_MODE_REMINDER }];
396
408
  if (this.hooks?.has('UserPromptSubmit') && !this.isSubagent) {
397
409
  const prompt = content.filter((b) => b.type === 'text').map((b) => b.text).join('\n');
398
410
  const h = await this.hooks.run('UserPromptSubmit', { prompt }, { cwd: this.cwd, signal });
@@ -599,7 +611,6 @@ export class Agent {
599
611
  config: this.config,
600
612
  signal,
601
613
  fileState: this.fileState,
602
- modes: this.modes,
603
614
  checkpoints: this.checkpoints,
604
615
  agent: this,
605
616
  io: this.io,
@@ -618,7 +629,7 @@ export class Agent {
618
629
  const batches = [];
619
630
  for (const tu of toolUses) {
620
631
  const tool = map.get(tu.name);
621
- const safe = !!tool?.readOnly && tool.name !== 'ExitPlanMode' && tool.name !== 'AskUserQuestion';
632
+ const safe = !!tool?.readOnly && tool.name !== 'AskUserQuestion';
622
633
  const last = batches[batches.length - 1];
623
634
  if (safe && last?.parallel) last.items.push(tu);
624
635
  else batches.push({ parallel: safe, items: [tu] });
@@ -669,13 +680,7 @@ export class Agent {
669
680
  return fail(invalid);
670
681
  }
671
682
 
672
- // Nothing is ever asked: tools run right away. The only gate is plan mode (read-only research).
673
- const decision = this.modes.check(tool, input);
674
- if (decision.behavior === 'deny') {
675
- this.io.toolRejected?.(tu, tool, decision.message, this);
676
- return fail(decision.message);
677
- }
678
-
683
+ // Nothing is ever asked: tools run right away (a PreToolUse hook can still block one).
679
684
  if (this.hooks?.has('PreToolUse')) {
680
685
  const h = await this.hooks.run('PreToolUse', { tool_name: tool.name, tool_input: input }, { cwd: this.cwd, signal });
681
686
  for (const w of h.warnings) this.io.notice?.(w, 'warn');
package/src/attach.js ADDED
@@ -0,0 +1,132 @@
1
+ // `claude-pro attach [name]`: a background session of this computer (claude-pro --headless, see vterm.js), used
2
+ // here in this terminal with its whole interface, as tmux attach does. It goes through the session's own server on
3
+ // 127.0.0.1 (peers.js), not the gateway: GET /attach upgraded to a connection of its own, the screen coming down as
4
+ // it is drawn, the keys and the size of this terminal going up as JSON lines ({keys: base64}, {resize: [cols,
5
+ // rows]}). ctrl+] detaches; the session goes on. Several terminals can be attached at once (the last one to attach
6
+ // or resize sets the size), and the web page at the same time.
7
+ //
8
+ // A restart of the session (an update, /restart, /cd) ends the connection: this waits for the session to come back
9
+ // under the same registry id and attaches again.
10
+
11
+ import http from 'node:http';
12
+ import readline from 'node:readline';
13
+ import { listPeers } from './peers.js';
14
+
15
+ const DETACH = '\x1d'; // ctrl+]
16
+ const RESET = '\x1b[?1002l\x1b[?1006l\x1b[?1000l\x1b[?2004l\x1b[?1049l\x1b[?25h';
17
+ const BACK_WITHIN_MS = 20_000; // a restart brings the session back within this
18
+
19
+ const backgroundSessions = () => listPeers().filter((p) => p.kind === 'background');
20
+
21
+ // The session `ref` names: its name, its id at the gateway, or the start of its registry id.
22
+ export function findBackground(ref, sessions = backgroundSessions()) {
23
+ const q = String(ref || '').replace(/^[@&&]/, '').toLowerCase();
24
+ if (!q) return null;
25
+ return sessions.find((p) => p.name.toLowerCase() === q)
26
+ || sessions.find((p) => String(p.remoteId || '').toLowerCase() === q)
27
+ || sessions.find((p) => p.id.startsWith(q) || String(p.remoteId || '').toLowerCase().startsWith(q))
28
+ || null;
29
+ }
30
+
31
+ function choose(sessions, io) {
32
+ io.stdout.write('Background sessions on this computer:\n');
33
+ sessions.forEach((p, i) => io.stdout.write(` ${i + 1}. &${p.name} ${p.cwd}${p.remoteId ? ` (${p.remoteId})` : ''}\n`));
34
+ const rl = readline.createInterface({ input: io.stdin, output: io.stdout });
35
+ return new Promise((resolve) => {
36
+ rl.question(`Which one? [1-${sessions.length}, Enter for 1] `, (answer) => {
37
+ rl.close();
38
+ const n = answer.trim() ? Number(answer.trim()) : 1;
39
+ resolve(Number.isInteger(n) && n >= 1 && n <= sessions.length ? sessions[n - 1] : findBackground(answer.trim(), sessions));
40
+ });
41
+ });
42
+ }
43
+
44
+ // One connection: resolves with how it ended, 'detached' or 'closed'.
45
+ function connect(peer, io) {
46
+ return new Promise((resolve, reject) => {
47
+ const { columns = 100, rows = 30 } = io.stdout;
48
+ const req = http.request({
49
+ host: '127.0.0.1', port: peer.port, path: `/attach?cols=${columns}&rows=${rows}`,
50
+ headers: { connection: 'Upgrade', upgrade: 'claude-pro-attach', authorization: `Bearer ${peer.token}` },
51
+ });
52
+ req.on('response', (res) => reject(new Error(res.statusCode === 404 ? 'this session cannot be attached to (a terminal session, or an older claude-pro)' : `HTTP ${res.statusCode}`)));
53
+ req.on('error', reject);
54
+ req.on('upgrade', (_res, socket, head) => {
55
+ let ended = null;
56
+ const finish = (how) => {
57
+ if (ended) return;
58
+ ended = how;
59
+ io.stdin.off('data', onKeys);
60
+ io.stdout.off('resize', onResize);
61
+ socket.destroy();
62
+ resolve(how);
63
+ };
64
+ const send = (msg) => { if (!socket.destroyed) socket.write(`${JSON.stringify(msg)}\n`); };
65
+ const onKeys = (data) => {
66
+ const i = data.indexOf(DETACH);
67
+ if (i >= 0) {
68
+ if (i > 0) send({ keys: data.subarray(0, i).toString('base64') });
69
+ finish('detached');
70
+ return;
71
+ }
72
+ send({ keys: data.toString('base64') });
73
+ };
74
+ const onResize = () => send({ resize: [io.stdout.columns, io.stdout.rows] });
75
+ if (head?.length) io.stdout.write(head);
76
+ socket.on('data', (d) => io.stdout.write(d));
77
+ socket.on('close', () => finish('closed'));
78
+ socket.on('error', () => finish('closed'));
79
+ io.stdin.on('data', onKeys);
80
+ io.stdout.on('resize', onResize);
81
+ });
82
+ req.end();
83
+ });
84
+ }
85
+
86
+ // io: the terminal (process.stdin/stdout/stderr; the tests give their own).
87
+ export async function attachCommand(args = [], io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) {
88
+ if (!io.stdin.isTTY || !io.stdout.isTTY) {
89
+ io.stderr.write('claude-pro attach needs a terminal.\n');
90
+ return 2;
91
+ }
92
+ const sessions = backgroundSessions();
93
+ if (!sessions.length) {
94
+ io.stdout.write('No background session runs on this computer. The web page opens them (新建会话, without "open a terminal window").\n');
95
+ return 1;
96
+ }
97
+ const ref = args.find((a) => !a.startsWith('-'));
98
+ let peer = ref ? findBackground(ref, sessions) : sessions.length === 1 ? sessions[0] : await choose(sessions, io);
99
+ if (!peer) {
100
+ io.stderr.write(`No background session called "${ref}". These run here: ${sessions.map((p) => `&${p.name}`).join(', ')}\n`);
101
+ return 1;
102
+ }
103
+ const label = `&${peer.name}`;
104
+ io.stdin.setRawMode(true);
105
+ io.stdin.resume();
106
+ let how;
107
+ try {
108
+ for (;;) {
109
+ how = await connect(peer, io);
110
+ if (how === 'detached') break;
111
+ // closed: the session restarting (it comes back under the same registry id), or ended
112
+ const id = peer.id;
113
+ let back = null;
114
+ for (let t = 0; t < BACK_WITHIN_MS && !back; t += 300) {
115
+ await new Promise((r) => setTimeout(r, 300));
116
+ back = backgroundSessions().find((p) => p.id === id && p.pid !== peer.pid) || null;
117
+ }
118
+ if (!back) { how = 'ended'; break; }
119
+ peer = back;
120
+ }
121
+ } catch (e) {
122
+ io.stdout.write(RESET);
123
+ io.stdin.setRawMode(false);
124
+ io.stderr.write(`Could not attach to ${label}: ${e.message}\n`);
125
+ return 1;
126
+ }
127
+ io.stdout.write(RESET);
128
+ io.stdin.setRawMode(false);
129
+ io.stdin.pause();
130
+ io.stdout.write(how === 'detached' ? `Detached from ${label}: it goes on in the background (claude-pro attach ${peer.name} comes back).\n` : `${label} has ended.\n`);
131
+ return 0;
132
+ }
@@ -0,0 +1,424 @@
1
+ // The background sessions of this computer: claude-pro --headless processes that the computer service (host.js)
2
+ // starts for the web page, without a window. Each one is a supervisor (bin/claude-pro.js, see supervisor.js) with
3
+ // the session as its child, so that /restart, /cd, the Restart tool and updates restart it as they restart a
4
+ // terminal session, under the same id. The service only watches the supervisor:
5
+ //
6
+ // - it ends with 0, or the session left a mark that it ended (/exit, the service's stop): exited, and off the list
7
+ // of sessions to open again;
8
+ // - otherwise it crashed: opened again with --resume (the same conversation, the same id at the gateway), at most
9
+ // MAX_CRASHES times in CRASH_WINDOW_MS, then failed (with the end of its log as the error);
10
+ // - CONFIG_DIR/host-sessions.json keeps the sessions to open again when the service starts (after a reboot, or a
11
+ // new version of the service): one still running (the same boot, its supervisor alive) is taken over, the others
12
+ // are opened again with --resume. A task that was running is not continued: the conversation is.
13
+ //
14
+ // Each session's output (its log: what it printed, as plain text, and the errors of its processes) goes to
15
+ // CONFIG_DIR/logs/sessions/<id>.log, cut down to LOG_BYTES (copied to .log.1 first) once a minute.
16
+ //
17
+ // What the service learns from a session (its directory after a /cd, its name, its conversation) comes from the
18
+ // registry of this computer's sessions (peers.js), where a session also takes its orders from the service
19
+ // (POST /control: exit, restart).
20
+
21
+ import fs from 'node:fs';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+ import { spawn, spawnSync } from 'node:child_process';
25
+ import { listPeers, controlPeer } from './peers.js';
26
+
27
+ export const CRASH_WINDOW_MS = 10 * 60_000;
28
+ export const MAX_CRASHES = 3;
29
+ const KEEP_ENDED = 20;
30
+ const LOG_BYTES = 1_000_000;
31
+ const STOP_WAIT_MS = 10_000;
32
+ const STARTING_MS = 30_000; // a session that has not shown up in the registry by then counts as running anyway
33
+ const ID = /^[A-Za-z0-9_-]{8,64}$/;
34
+
35
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
36
+
37
+ export function pidAlive(pid) {
38
+ if (!Number.isInteger(pid) || pid <= 0) return false;
39
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
40
+ }
41
+
42
+ // When this computer started (ms, to the minute): a pid saved before a reboot means nothing after it.
43
+ export const bootTime = () => Math.round((Date.now() - os.uptime() * 1000) / 60_000) * 60_000;
44
+
45
+ // Where a background session says it ended for good (see App.exit): the service reads and removes it.
46
+ export const endedMarker = (dir, id) => path.join(dir, 'background-ended', id);
47
+
48
+ export function markEnded(dir, id) {
49
+ if (!ID.test(String(id || ''))) return;
50
+ try {
51
+ fs.mkdirSync(path.dirname(endedMarker(dir, id)), { recursive: true });
52
+ fs.writeFileSync(endedMarker(dir, id), new Date().toISOString());
53
+ } catch { /* the service then thinks it crashed, and opens it again */ }
54
+ }
55
+
56
+ // The last `lines` lines of a log (and of the one before it, when that is not enough).
57
+ export function tailFile(file, lines = 200) {
58
+ const read = (f) => { try { return fs.readFileSync(f, 'utf8'); } catch { return ''; } };
59
+ let text = read(file);
60
+ if (text.split('\n').length <= lines) text = read(`${file}.1`) + text;
61
+ const all = text.replace(/\n$/, '').split('\n');
62
+ return all.slice(-lines).join('\n');
63
+ }
64
+
65
+ // End a process and what it started: the supervisor of a session, and the session under it.
66
+ export function killTree(pid) {
67
+ if (!pidAlive(pid)) return;
68
+ if (process.platform === 'win32') {
69
+ spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
70
+ return;
71
+ }
72
+ try { process.kill(-pid, 'SIGTERM'); } catch { try { process.kill(pid, 'SIGTERM'); } catch { /* gone */ } }
73
+ setTimeout(() => { try { process.kill(-pid, 'SIGKILL'); } catch { /* gone */ } }, 3000).unref?.();
74
+ }
75
+
76
+ export class BackgroundSessions {
77
+ // dir: CONFIG_DIR. entry: bin/claude-pro.js. env: what the sessions get. onChange(): something to report.
78
+ constructor({ dir, entry, env = process.env, log = () => {}, onChange = () => {}, execPath = process.execPath }) {
79
+ this.dir = dir;
80
+ this.entry = entry;
81
+ this.env = env;
82
+ this.log = log;
83
+ this.onChange = onChange;
84
+ this.execPath = execPath;
85
+ this.sessions = new Map(); // sessionId -> record (running, starting, restarting, failed, or suspended)
86
+ this.ended = []; // the public records of the sessions that ended, newest first
87
+ this.timer = null;
88
+ this.rotateTimer = null;
89
+ this.suspended = false;
90
+ }
91
+
92
+ get file() { return path.join(this.dir, 'host-sessions.json'); }
93
+ logFile(id) { return path.join(this.dir, 'logs', 'sessions', `${id}.log`); }
94
+
95
+ // The sessions saved by the service before: taken over when they still run, opened again when not.
96
+ start() {
97
+ let saved = [];
98
+ try { saved = JSON.parse(fs.readFileSync(this.file, 'utf8')); } catch { /* none */ }
99
+ for (const s of Array.isArray(saved) ? saved : []) {
100
+ if (!s || !ID.test(String(s.sessionId || '')) || typeof s.cwd !== 'string') continue;
101
+ const rec = this.record(s);
102
+ this.sessions.set(rec.sessionId, rec);
103
+ if (s.state === 'failed') { rec.state = 'failed'; rec.error = s.error || null; continue; }
104
+ if (s.suspended) { rec.suspended = true; rec.state = 'exited'; continue; }
105
+ if (s.boot === bootTime() && pidAlive(s.pid)) {
106
+ rec.pid = s.pid;
107
+ rec.state = 'running';
108
+ rec.startedAt = s.startedAt || null;
109
+ this.log(`took over the background session ${rec.sessionId} (pid ${rec.pid}) in ${rec.cwd}`);
110
+ } else {
111
+ this.log(`opening the background session ${rec.sessionId} again in ${rec.cwd}`);
112
+ this.launch(rec, { resume: true });
113
+ }
114
+ }
115
+ this.closed = false;
116
+ this.timer = setInterval(() => this.tick(), 2000);
117
+ this.timer.unref?.();
118
+ this.rotateTimer = setInterval(() => this.rotateLogs(), 60_000);
119
+ this.rotateTimer.unref?.();
120
+ this.persist();
121
+ }
122
+
123
+ // The service stops watching (its sessions run on, for the next one to take over).
124
+ close() {
125
+ this.closed = true;
126
+ clearInterval(this.timer);
127
+ clearInterval(this.rotateTimer);
128
+ }
129
+
130
+ record(s) {
131
+ return {
132
+ sessionId: s.sessionId,
133
+ cwd: s.cwd,
134
+ name: s.name || '',
135
+ conversationId: s.conversationId || null,
136
+ model: s.model || null,
137
+ state: 'starting',
138
+ pid: null,
139
+ childPid: null,
140
+ child: null,
141
+ startedAt: null,
142
+ endedAt: null,
143
+ exitCode: null,
144
+ error: null,
145
+ restarts: 0,
146
+ crashes: [],
147
+ boot: null,
148
+ stopping: false,
149
+ restartFrom: null,
150
+ suspended: false,
151
+ };
152
+ }
153
+
154
+ // A new background session for the web page: {sessionId, cwd, name, conversationId (to resume), model}.
155
+ open({ sessionId, cwd, name = '', resume = null, model = null }) {
156
+ if (this.sessions.get(sessionId) && this.alive(this.sessions.get(sessionId))) throw new Error('这个会话已经在运行');
157
+ const rec = this.record({ sessionId, cwd, name, conversationId: resume, model });
158
+ this.sessions.set(sessionId, rec);
159
+ this.ended = this.ended.filter((e) => e.sessionId !== sessionId);
160
+ this.launch(rec, { resume: Boolean(resume), first: true });
161
+ this.persist();
162
+ this.onChange();
163
+ return { pid: rec.pid };
164
+ }
165
+
166
+ launch(rec, { resume = false, first = false } = {}) {
167
+ const args = [this.entry, '--headless', '--remote-id', rec.sessionId];
168
+ if (resume && rec.conversationId) args.push('--resume', rec.conversationId);
169
+ if (first && rec.name) args.push('--name', rec.name);
170
+ if (first && rec.model) args.push('--model', rec.model);
171
+ const log = this.logFile(rec.sessionId);
172
+ let fd = null;
173
+ try {
174
+ fs.mkdirSync(path.dirname(log), { recursive: true });
175
+ fs.appendFileSync(log, `${new Date().toISOString()} [service] starting: claude-pro ${args.slice(1).join(' ')}\n`);
176
+ fd = fs.openSync(log, 'a');
177
+ const child = spawn(this.execPath, args, { cwd: rec.cwd, env: this.env, detached: true, windowsHide: true, stdio: ['ignore', fd, fd] });
178
+ rec.child = child;
179
+ rec.pid = child.pid ?? null;
180
+ rec.childPid = null;
181
+ rec.state = rec.state === 'restarting' ? 'restarting' : 'starting';
182
+ rec.startedAt = new Date().toISOString();
183
+ rec.launchedAt = Date.now();
184
+ rec.endedAt = null;
185
+ rec.exitCode = null;
186
+ rec.error = null;
187
+ rec.boot = bootTime();
188
+ rec.stopping = false;
189
+ rec.suspended = false;
190
+ child.on('error', (e) => {
191
+ if (rec.child !== child) return;
192
+ rec.child = null;
193
+ this.fail(rec, `无法启动:${e.message}`);
194
+ });
195
+ child.on('exit', (code, signal) => {
196
+ if (rec.child !== child) return;
197
+ rec.child = null;
198
+ this.gone(rec, code ?? (signal ? `signal ${signal}` : null));
199
+ });
200
+ child.unref();
201
+ } catch (e) {
202
+ this.fail(rec, `无法启动:${e.message}`);
203
+ } finally {
204
+ if (fd !== null) try { fs.closeSync(fd); } catch { /* closed */ }
205
+ }
206
+ }
207
+
208
+ alive(rec) { return Boolean(rec.child) || pidAlive(rec.pid); }
209
+
210
+ // The supervisor of `rec` is gone: ended for good, or crashed.
211
+ gone(rec, code) {
212
+ if (!this.sessions.has(rec.sessionId)) return;
213
+ let marked = false;
214
+ try { fs.rmSync(endedMarker(this.dir, rec.sessionId)); marked = true; } catch { /* none */ }
215
+ if (rec.suspended) { rec.state = 'exited'; rec.endedAt = new Date().toISOString(); this.persist(); this.onChange(); return; }
216
+ if (rec.stopping || marked || code === 0) {
217
+ this.finish(rec, code);
218
+ return;
219
+ }
220
+ const now = Date.now();
221
+ rec.crashes = rec.crashes.filter((t) => now - t < CRASH_WINDOW_MS);
222
+ rec.crashes.push(now);
223
+ if (rec.crashes.length > MAX_CRASHES) {
224
+ this.fail(rec, tailFile(this.logFile(rec.sessionId), 12) || `退出码 ${code}`, code);
225
+ return;
226
+ }
227
+ rec.restarts++;
228
+ rec.state = 'restarting';
229
+ rec.exitCode = code;
230
+ this.log(`the background session ${rec.sessionId} stopped (${code ?? 'no exit code'}): opening it again (${rec.crashes.length}/${MAX_CRASHES} in ${CRASH_WINDOW_MS / 60_000} minutes)`);
231
+ this.onChange();
232
+ setTimeout(() => { if (!this.closed && this.sessions.get(rec.sessionId) === rec && rec.state === 'restarting' && !this.alive(rec)) this.launch(rec, { resume: true }); }, 1000).unref?.();
233
+ }
234
+
235
+ fail(rec, error, code = null) {
236
+ rec.state = 'failed';
237
+ rec.error = String(error || '').slice(-2000);
238
+ rec.exitCode = code;
239
+ rec.endedAt = new Date().toISOString();
240
+ this.log(`the background session ${rec.sessionId} failed: ${rec.error.split('\n').pop()}`);
241
+ this.persist();
242
+ this.onChange();
243
+ }
244
+
245
+ // Ended for good: off the list of sessions to open again.
246
+ finish(rec, code = null) {
247
+ rec.state = 'exited';
248
+ rec.exitCode = code;
249
+ rec.endedAt = new Date().toISOString();
250
+ this.sessions.delete(rec.sessionId);
251
+ this.ended.unshift(this.public(rec));
252
+ this.ended.length = Math.min(this.ended.length, KEEP_ENDED);
253
+ this.log(`the background session ${rec.sessionId} ended`);
254
+ this.persist();
255
+ this.onChange();
256
+ }
257
+
258
+ peerOf(rec) { return listPeers().find((p) => p.remoteId === rec.sessionId && p.kind === 'background') || null; }
259
+
260
+ // Every two seconds: what the sessions say about themselves in the registry, and whether they still run.
261
+ tick() {
262
+ let changed = false;
263
+ const peers = listPeers();
264
+ for (const rec of this.sessions.values()) {
265
+ if (rec.state === 'failed' || rec.suspended) continue;
266
+ const p = peers.find((x) => x.remoteId === rec.sessionId);
267
+ if (p) {
268
+ for (const [k, v] of [['cwd', p.cwd], ['name', p.name], ['conversationId', p.conversationId], ['childPid', p.pid]]) {
269
+ if (v && rec[k] !== v) { rec[k] = v; changed = true; }
270
+ }
271
+ if (rec.state === 'starting' || (rec.state === 'restarting' && p.pid !== rec.restartFrom)) { rec.state = 'running'; rec.restartFrom = null; changed = true; }
272
+ } else if (rec.state === 'starting' && Date.now() - (rec.launchedAt || 0) > STARTING_MS && this.alive(rec)) {
273
+ rec.state = 'running';
274
+ changed = true;
275
+ }
276
+ // one taken over from an earlier service has no child process here: its pid tells
277
+ if (!rec.child && rec.state !== 'restarting' && !pidAlive(rec.pid)) this.gone(rec, null);
278
+ }
279
+ if (changed) { this.persist(); this.onChange(); }
280
+ }
281
+
282
+ // stop: as /exit (the session stops what it does, then ends); not ended after STOP_WAIT_MS, it is killed.
283
+ async stop(sessionId) {
284
+ const rec = this.sessions.get(sessionId);
285
+ if (!rec) {
286
+ if (this.ended.some((e) => e.sessionId === sessionId)) return {};
287
+ throw new Error('这台电脑上没有这个后台会话');
288
+ }
289
+ if (!this.alive(rec)) { this.finish(rec, rec.exitCode); return {}; }
290
+ rec.stopping = true;
291
+ const peer = this.peerOf(rec);
292
+ if (peer) await controlPeer(peer, { action: 'exit' }).catch(() => { /* killed below */ });
293
+ for (let t = 0; t < STOP_WAIT_MS && this.alive(rec); t += 200) await sleep(200);
294
+ if (this.alive(rec)) {
295
+ this.log(`the background session ${sessionId} did not end in ${STOP_WAIT_MS / 1000} s: killing it`);
296
+ killTree(rec.pid);
297
+ for (let t = 0; t < 5000 && this.alive(rec); t += 200) await sleep(200);
298
+ }
299
+ if (this.sessions.get(sessionId) === rec) this.finish(rec, rec.exitCode);
300
+ return {};
301
+ }
302
+
303
+ // restart: as /restart for one that runs (the same process tree, the conversation kept); one that failed or
304
+ // ended is opened again with --resume, its count of restarts back to 0.
305
+ async restart(sessionId) {
306
+ let rec = this.sessions.get(sessionId);
307
+ if (rec && this.alive(rec) && rec.state !== 'failed') {
308
+ const peer = this.peerOf(rec);
309
+ if (!peer) throw new Error('这个会话还在启动,稍后再试');
310
+ rec.restartFrom = peer.pid;
311
+ rec.state = 'restarting';
312
+ this.onChange();
313
+ try {
314
+ await controlPeer(peer, { action: 'restart' });
315
+ } catch (e) {
316
+ rec.state = 'running';
317
+ rec.restartFrom = null;
318
+ this.onChange();
319
+ throw new Error(`重启失败:${e.message}`);
320
+ }
321
+ return {};
322
+ }
323
+ if (!rec) {
324
+ const old = this.ended.find((e) => e.sessionId === sessionId);
325
+ if (!old) throw new Error('这台电脑上没有这个后台会话');
326
+ rec = this.record(old);
327
+ this.ended = this.ended.filter((e) => e.sessionId !== sessionId);
328
+ this.sessions.set(sessionId, rec);
329
+ }
330
+ rec.crashes = [];
331
+ rec.restarts = 0;
332
+ rec.state = 'starting';
333
+ this.launch(rec, { resume: true });
334
+ this.persist();
335
+ this.onChange();
336
+ return {};
337
+ }
338
+
339
+ // The gateway no longer takes this computer (or it logged out): the sessions end, and are kept to be opened
340
+ // again when it is back (resumeAll).
341
+ async suspendAll() {
342
+ if (this.suspended) return;
343
+ this.suspended = true;
344
+ const running = [...this.sessions.values()].filter((r) => this.alive(r));
345
+ for (const rec of running) rec.suspended = true;
346
+ await Promise.all(running.map(async (rec) => {
347
+ const peer = this.peerOf(rec);
348
+ if (peer) await controlPeer(peer, { action: 'exit' }).catch(() => {});
349
+ for (let t = 0; t < STOP_WAIT_MS && this.alive(rec); t += 200) await sleep(200);
350
+ if (this.alive(rec)) killTree(rec.pid);
351
+ }));
352
+ this.persist();
353
+ this.onChange();
354
+ }
355
+
356
+ resumeAll() {
357
+ if (!this.suspended && ![...this.sessions.values()].some((r) => r.suspended)) return;
358
+ this.suspended = false;
359
+ for (const rec of this.sessions.values()) {
360
+ if (!rec.suspended) continue;
361
+ rec.suspended = false;
362
+ rec.crashes = [];
363
+ this.launch(rec, { resume: true });
364
+ }
365
+ this.persist();
366
+ this.onChange();
367
+ }
368
+
369
+ // The conversation `conversationId` already open in a session of this computer (a background one, or a terminal):
370
+ // its entry in the registry.
371
+ openConversation(conversationId) {
372
+ if (!conversationId) return null;
373
+ return listPeers().find((p) => p.conversationId === conversationId) || null;
374
+ }
375
+
376
+ rotateLogs() {
377
+ for (const rec of this.sessions.values()) {
378
+ const file = this.logFile(rec.sessionId);
379
+ try {
380
+ if (fs.statSync(file).size <= LOG_BYTES) continue;
381
+ // copied, then emptied: the processes write to it all along (in append mode, so they go on at its end)
382
+ fs.copyFileSync(file, `${file}.1`);
383
+ fs.truncateSync(file, 0);
384
+ } catch { /* not there yet */ }
385
+ }
386
+ }
387
+
388
+ public(rec) {
389
+ return {
390
+ sessionId: rec.sessionId,
391
+ cwd: rec.cwd,
392
+ name: rec.name,
393
+ conversationId: rec.conversationId,
394
+ state: rec.state,
395
+ pid: rec.pid,
396
+ startedAt: rec.startedAt,
397
+ endedAt: rec.endedAt,
398
+ exitCode: rec.exitCode,
399
+ error: rec.error,
400
+ restarts: rec.restarts,
401
+ };
402
+ }
403
+
404
+ // For the gateway: the sessions now, then those that ended (at most KEEP_ENDED).
405
+ list() {
406
+ return [...[...this.sessions.values()].map((r) => this.public(r)), ...this.ended];
407
+ }
408
+
409
+ persist() {
410
+ const list = [...this.sessions.values()].map((r) => ({
411
+ sessionId: r.sessionId, cwd: r.cwd, name: r.name, conversationId: r.conversationId, model: r.model,
412
+ pid: r.pid, boot: r.boot, startedAt: r.startedAt, state: r.state === 'failed' ? 'failed' : undefined, error: r.state === 'failed' ? r.error : undefined,
413
+ suspended: r.suspended || undefined,
414
+ }));
415
+ try {
416
+ fs.mkdirSync(this.dir, { recursive: true });
417
+ const tmp = `${this.file}.${process.pid}.tmp`;
418
+ fs.writeFileSync(tmp, JSON.stringify(list, null, 2));
419
+ fs.renameSync(tmp, this.file);
420
+ } catch (e) {
421
+ this.log(`could not save ${this.file}: ${e.message}`);
422
+ }
423
+ }
424
+ }