@yanzc/claude-pro 0.6.0 → 0.7.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/README.md +375 -370
- package/package.json +1 -1
- package/src/attach.js +132 -0
- package/src/background.js +424 -0
- package/src/commands.js +75 -35
- package/src/connect.js +79 -0
- package/src/history.js +94 -0
- package/src/host.js +444 -65
- package/src/main.js +35 -6
- package/src/peers.js +290 -215
- package/src/remote.js +50 -15
- package/src/session.js +24 -0
- package/src/supervisor.js +6 -3
- package/src/tools/bash.js +2 -2
- package/src/ui/dialogs.js +48 -0
- package/src/ui/render.js +10 -0
- package/src/ui/repl.js +308 -38
- package/src/ui/vterm.js +62 -0
package/src/remote.js
CHANGED
|
@@ -13,7 +13,7 @@ import fs from 'node:fs';
|
|
|
13
13
|
import os from 'node:os';
|
|
14
14
|
import crypto from 'node:crypto';
|
|
15
15
|
import { stripAnsi } from './ui/ansi.js';
|
|
16
|
-
import { toolHeader, renderToolResult } from './ui/render.js';
|
|
16
|
+
import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
|
|
17
17
|
import { uploadFile, downloadFile } from './transfer.js';
|
|
18
18
|
|
|
19
19
|
export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
|
|
@@ -120,6 +120,8 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
|
|
|
120
120
|
if (b.type === 'text') {
|
|
121
121
|
const raw = String(b.text || '');
|
|
122
122
|
if (raw.startsWith('This session is being continued')) { items.push({ k: 'summary', text: raw }); continue; }
|
|
123
|
+
const bash = bashModeLines(raw); // `!command`: as it was shown when it ran
|
|
124
|
+
if (bash) { items.push({ k: 'output', lines: [...bash, ''] }); continue; }
|
|
123
125
|
const text = raw.startsWith('<system-reminder>') ? '' : shownUserText(raw);
|
|
124
126
|
if (text) items.push({ k: 'user', text });
|
|
125
127
|
} else if (b.type === 'image') {
|
|
@@ -192,7 +194,8 @@ export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(
|
|
|
192
194
|
|
|
193
195
|
export class RemoteControl {
|
|
194
196
|
// gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model}, seed() -> items, status() -> object,
|
|
195
|
-
// send(text), interrupt(), answer(body) (
|
|
197
|
+
// send(text, images), interrupt(), answer(body), options(body), suggest(body), list(body) (each returns an object
|
|
198
|
+
// or a promise of one, or throws), changed() (online or viewers changed).
|
|
196
199
|
constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
|
|
197
200
|
this.base = String(gateway.url).replace(/\/+$/, '');
|
|
198
201
|
this.apiKey = gateway.apiKey;
|
|
@@ -218,6 +221,7 @@ export class RemoteControl {
|
|
|
218
221
|
this.registered = false;
|
|
219
222
|
this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
|
|
220
223
|
this.peerPending = new Set(); // messages being handled now, acknowledged when done
|
|
224
|
+
this.replying = new Set(); // answers to the page's commands on their way
|
|
221
225
|
}
|
|
222
226
|
|
|
223
227
|
get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
|
|
@@ -335,20 +339,33 @@ export class RemoteControl {
|
|
|
335
339
|
if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
|
|
336
340
|
if (!cmd.cid) return;
|
|
337
341
|
if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
|
|
338
|
-
|
|
342
|
+
// close() waits for it: a /cd from the page restarts the session before its answer goes out
|
|
343
|
+
const reply = (result) => {
|
|
344
|
+
const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
|
|
345
|
+
this.replying.add(sent);
|
|
346
|
+
sent.finally(() => this.replying.delete(sent));
|
|
347
|
+
this.scheduleFlush(30);
|
|
348
|
+
};
|
|
349
|
+
const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
|
|
350
|
+
let r;
|
|
339
351
|
try {
|
|
340
|
-
const body = cmd.body
|
|
341
|
-
|
|
342
|
-
if (cmd.type === 'send') r = this.handlers.send(String(body.text ?? ''));
|
|
352
|
+
const body = cmd.body && typeof cmd.body === 'object' ? cmd.body : {};
|
|
353
|
+
// send, interrupt and dialog act; options, suggest and list only look (and are answered while it works)
|
|
354
|
+
if (cmd.type === 'send') r = this.handlers.send(String(body.text ?? ''), body.images);
|
|
343
355
|
else if (cmd.type === 'interrupt') r = this.handlers.interrupt();
|
|
344
356
|
else if (cmd.type === 'dialog') r = this.handlers.answer(body);
|
|
357
|
+
else if (cmd.type === 'options' && this.handlers.options) r = this.handlers.options(body);
|
|
358
|
+
else if (cmd.type === 'suggest' && this.handlers.suggest) r = this.handlers.suggest(body);
|
|
359
|
+
else if (cmd.type === 'list' && this.handlers.list) r = this.handlers.list(body);
|
|
360
|
+
else if (cmd.type === 'output' && this.handlers.output) r = this.handlers.output(body);
|
|
345
361
|
else throw new Error(`Unknown command: ${cmd.type}`);
|
|
346
|
-
result = { cid: cmd.cid, ok: true, ...(r || {}) };
|
|
347
362
|
} catch (e) {
|
|
348
|
-
|
|
363
|
+
failed(e);
|
|
364
|
+
return;
|
|
349
365
|
}
|
|
350
|
-
|
|
351
|
-
|
|
366
|
+
// an answer that takes a while (a list of models from the gateway, a directory) is sent when it is there
|
|
367
|
+
if (typeof r?.then === 'function') r.then((v) => reply({ cid: cmd.cid, ok: true, ...(v || {}) }), failed);
|
|
368
|
+
else reply({ cid: cmd.cid, ok: true, ...(r || {}) });
|
|
352
369
|
}
|
|
353
370
|
|
|
354
371
|
// ------------------------------------------------------------ messages of the account's other sessions
|
|
@@ -475,12 +492,17 @@ export class RemoteControl {
|
|
|
475
492
|
|
|
476
493
|
// What decides whether the status is sent again: all of it while a page watches; while none does, only what
|
|
477
494
|
// the gateway's session list shows (the token count of a busy session would otherwise go out every few seconds).
|
|
495
|
+
// `asking` (a question waits) is in it too: the gateway tells the user about it even with no page open.
|
|
478
496
|
statusKey(status) {
|
|
479
497
|
if (this.viewing) return JSON.stringify({ ...status, elapsed: 0 });
|
|
480
|
-
const { busy, title, model, cwd, name } = status;
|
|
481
|
-
return JSON.stringify({ busy, title, model, cwd, name });
|
|
498
|
+
const { busy, asking, title, model, cwd, name } = status;
|
|
499
|
+
return JSON.stringify({ busy, asking, title, model, cwd, name });
|
|
482
500
|
}
|
|
483
501
|
|
|
502
|
+
// What is sent at once, without the wait between statuses of an unwatched session: a task that started or ended,
|
|
503
|
+
// a question that came or was answered.
|
|
504
|
+
urgentKey(status) { return `${Boolean(status.busy)}|${Boolean(status.asking)}`; }
|
|
505
|
+
|
|
484
506
|
// What has changed goes into the next upload: a snapshot when one is due, else the events; and the status.
|
|
485
507
|
flush() {
|
|
486
508
|
if (this.closed || !this.registered) return;
|
|
@@ -491,6 +513,7 @@ export class RemoteControl {
|
|
|
491
513
|
this.events = [];
|
|
492
514
|
this.sinceSnapshot = 0;
|
|
493
515
|
this.lastStatus = this.statusKey(status);
|
|
516
|
+
this.lastUrgent = this.urgentKey(status);
|
|
494
517
|
this.lastStatusAt = Date.now();
|
|
495
518
|
this.outbox.push({ t: 'snapshot', seq: this.seq, items: snapshotItems(this.state.items), status });
|
|
496
519
|
} else if (this.events.length) {
|
|
@@ -499,8 +522,10 @@ export class RemoteControl {
|
|
|
499
522
|
this.events = [];
|
|
500
523
|
}
|
|
501
524
|
const key = this.statusKey(status);
|
|
502
|
-
|
|
525
|
+
const urgent = this.urgentKey(status);
|
|
526
|
+
if (key !== this.lastStatus && (urgent !== this.lastUrgent || Date.now() - this.lastStatusAt >= (this.viewing ? 0 : IDLE_STATUS_MS))) {
|
|
503
527
|
this.lastStatus = key;
|
|
528
|
+
this.lastUrgent = urgent;
|
|
504
529
|
this.lastStatusAt = Date.now();
|
|
505
530
|
this.outbox.push({ t: 'status', status });
|
|
506
531
|
}
|
|
@@ -527,8 +552,18 @@ export class RemoteControl {
|
|
|
527
552
|
|
|
528
553
|
// Ends the connection; resolves once the gateway was told (or gave up waiting). `restarting`: the session comes
|
|
529
554
|
// back at once with the same id, and the pages wait for it.
|
|
530
|
-
|
|
531
|
-
|
|
555
|
+
close({ restarting = false } = {}) {
|
|
556
|
+
this.closeDone ??= this.shutdown(restarting);
|
|
557
|
+
return this.closeDone;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async shutdown(restarting) {
|
|
561
|
+
// First the answers on their way, while the command stream is still open (the gateway fails what is still
|
|
562
|
+
// waiting once it closes). Among them the answer to the command that ends the session: a /cd or /exit from the
|
|
563
|
+
// page closes it from inside that command, and its answer is sent when the command returns, hence the wait for
|
|
564
|
+
// the current call to finish first.
|
|
565
|
+
await null;
|
|
566
|
+
if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
|
|
532
567
|
this.closing = true; // what flush() collects now goes out with the last message, not on its own
|
|
533
568
|
this.flush();
|
|
534
569
|
this.closed = true;
|
package/src/session.js
CHANGED
|
@@ -52,6 +52,30 @@ export function autoMemoryDir(cwd) {
|
|
|
52
52
|
return path.join(projectDir(cwd), 'memory');
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
// /cd: the conversation in `file` goes on in another working directory, so its file goes to that directory's project
|
|
56
|
+
// (where /resume there finds it, and where a SessionStore(cwd, id) appends), with the new directory in its first
|
|
57
|
+
// line. The copy is written now; commit() removes the old file, undo() the copy. {file, commit, undo}.
|
|
58
|
+
export function moveSession(file, id, cwd) {
|
|
59
|
+
const target = path.join(projectDir(cwd), `${id}.jsonl`);
|
|
60
|
+
const none = { file: target, commit() {}, undo() {} };
|
|
61
|
+
if (path.resolve(target) === path.resolve(file)) return none;
|
|
62
|
+
let text;
|
|
63
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return none; throw e; } // nothing written yet
|
|
64
|
+
const nl = text.indexOf('\n');
|
|
65
|
+
let first = nl >= 0 ? text.slice(0, nl) : text;
|
|
66
|
+
try {
|
|
67
|
+
const meta = JSON.parse(first);
|
|
68
|
+
if (meta?.type === 'meta') first = JSON.stringify({ ...meta, cwd });
|
|
69
|
+
} catch { /* not a meta line: kept as it is */ }
|
|
70
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
71
|
+
fs.writeFileSync(target, first + (nl >= 0 ? text.slice(nl) : '\n'));
|
|
72
|
+
return {
|
|
73
|
+
file: target,
|
|
74
|
+
commit() { try { fs.rmSync(file, { force: true }); } catch { /* two copies: /resume shows it in both places */ } },
|
|
75
|
+
undo() { try { fs.rmSync(target, { force: true }); } catch { /* left behind */ } },
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
55
79
|
export class SessionStore {
|
|
56
80
|
constructor(cwd, id = crypto.randomUUID()) {
|
|
57
81
|
this.cwd = cwd;
|
package/src/supervisor.js
CHANGED
|
@@ -39,16 +39,18 @@ export function sessionEntry(entry, platform = process.platform) {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
// Whether this invocation is an interactive session that should run under the supervisor.
|
|
42
|
+
// A background session (--headless, started by the computer service) has no terminal and is one all the same.
|
|
42
43
|
export function shouldSupervise(argv, env = process.env, isTty = (fd) => tty.isatty(fd)) {
|
|
43
44
|
if (env[ENV_SUPERVISED] || /^(1|true|yes)$/i.test(env.CLAUDE_PRO_NO_SUPERVISOR || '')) return false;
|
|
44
|
-
if (
|
|
45
|
-
if (
|
|
45
|
+
if (['config', 'host', 'attach', 'connect'].includes(argv[0])) return false;
|
|
46
|
+
if ((!isTty(0) || !isTty(1)) && !argv.includes('--headless')) return false;
|
|
46
47
|
return !argv.some((a) => NOT_INTERACTIVE.has(a));
|
|
47
48
|
}
|
|
48
49
|
|
|
49
50
|
function putTerminalRight() {
|
|
50
51
|
// The child may have died with the terminal in the mode it had set for itself.
|
|
51
52
|
// (the fullscreen renderer's alternate screen and mouse reporting included)
|
|
53
|
+
if (!tty.isatty(1)) return; // a background session's log
|
|
52
54
|
try { process.stdout.write('\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1049l\x1b[?2004l\x1b[?25h'); } catch { /* nothing to do */ }
|
|
53
55
|
try { if (tty.isatty(0)) process.stdin.setRawMode(false); } catch { /* nothing to do */ }
|
|
54
56
|
}
|
|
@@ -84,7 +86,8 @@ export function supervise(argv, { entry, env = process.env, execPath = process.e
|
|
|
84
86
|
const childEnv = { ...env, [ENV_SUPERVISED]: '1', [ENV_RESTART_FILE]: stateFile };
|
|
85
87
|
if (restarted) childEnv[ENV_RESTARTED] = '1'; else delete childEnv[ENV_RESTARTED];
|
|
86
88
|
const startedAt = Date.now();
|
|
87
|
-
|
|
89
|
+
// a background session has no console: without windowsHide Windows would give its child a window of its own
|
|
90
|
+
child = spawn(execPath, [sessionEntry(entry), ...argv], { stdio: 'inherit', env: childEnv, windowsHide: argv.includes('--headless') });
|
|
88
91
|
child.on('error', (e) => {
|
|
89
92
|
child = null;
|
|
90
93
|
err.write(`claude-pro: could not start (${e.message})\n`);
|
package/src/tools/bash.js
CHANGED
|
@@ -57,7 +57,7 @@ export function shutdownBackgroundShells() {
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
export function listBackgroundShells() {
|
|
60
|
-
return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, status: bg.status, exitCode: bg.exitCode }));
|
|
60
|
+
return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, description: bg.description || '', status: bg.status, exitCode: bg.exitCode, startedAt: bg.startedAt }));
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
export function makeBashTool(config) {
|
|
@@ -104,7 +104,7 @@ When you commit (the system prompt says when): run git status, git diff and git
|
|
|
104
104
|
if (input.run_in_background) {
|
|
105
105
|
const child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
|
|
106
106
|
const id = `bash_${++bgCounter}`;
|
|
107
|
-
const bg = { child, command, output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
|
|
107
|
+
const bg = { child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
|
|
108
108
|
background.set(id, bg);
|
|
109
109
|
// Decode as a stream: a multi-byte character (CJK text) can be split between two chunks.
|
|
110
110
|
child.stdout.setEncoding('utf8');
|
package/src/ui/dialogs.js
CHANGED
|
@@ -17,6 +17,54 @@ function box(lines, width, color) {
|
|
|
17
17
|
return out;
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
// A question answered with typed text: Enter submits, Esc cancels (shift/alt+Enter starts a new line when
|
|
21
|
+
// `multiline`). On the remote page it is a text box ({input: {placeholder, value, multiline}}, see App.remoteDialog).
|
|
22
|
+
export class TextDialog {
|
|
23
|
+
constructor({ title, body = [], question, placeholder = '', value = '', multiline = false, color = c.blue, onResolve, cancelValue = null }) {
|
|
24
|
+
this.title = title;
|
|
25
|
+
this.body = body;
|
|
26
|
+
this.question = question;
|
|
27
|
+
this.color = color;
|
|
28
|
+
this.onResolve = onResolve;
|
|
29
|
+
this.cancelValue = cancelValue;
|
|
30
|
+
this.input = { placeholder, multiline };
|
|
31
|
+
this.editor = new Editor();
|
|
32
|
+
if (value) this.editor.set(value, value.length);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
get value() { return this.editor.text; }
|
|
36
|
+
|
|
37
|
+
resolve(value) {
|
|
38
|
+
const cb = this.onResolve;
|
|
39
|
+
this.onResolve = null;
|
|
40
|
+
cb?.(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
handleKey(str, key = {}) {
|
|
44
|
+
if (key.name === 'escape') { this.resolve(this.cancelValue); return true; }
|
|
45
|
+
if (key.name === 'return' && !key.meta && !key.shift) { this.resolve(this.editor.text); return true; }
|
|
46
|
+
if (key.name === 'return' && !this.input.multiline) return true;
|
|
47
|
+
this.editor.handleKey(str, key);
|
|
48
|
+
return true; // modal: everything else is the editor's
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
render(width) {
|
|
52
|
+
const lines = [];
|
|
53
|
+
if (this.title) lines.push(c.bold(this.color(this.title)), '');
|
|
54
|
+
lines.push(...this.body);
|
|
55
|
+
if (this.body.length) lines.push('');
|
|
56
|
+
if (this.question) lines.push(this.question, '');
|
|
57
|
+
const inner = Math.max(20, width - 1) - 4;
|
|
58
|
+
const r = this.editor.render(width - 4, { placeholder: this.input.placeholder || 'Type the answer' });
|
|
59
|
+
const top = lines.length + 1; // +1 for the box's top border
|
|
60
|
+
lines.push(...r.lines.map((l) => truncate(l, inner)));
|
|
61
|
+
const cursor = r.cursor ? { row: top + r.cursor.row, col: 2 + r.cursor.col } : null;
|
|
62
|
+
const out = box(lines, width, this.color);
|
|
63
|
+
out.push(c.dim(` Enter to submit${this.input.multiline ? ' · shift+Enter for a new line' : ''} · Esc to cancel`));
|
|
64
|
+
return { lines: out, cursor };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
20
68
|
export class SelectDialog {
|
|
21
69
|
// options: [{label, value, description?}]
|
|
22
70
|
// selected: the option highlighted at first.
|
package/src/ui/render.js
CHANGED
|
@@ -27,6 +27,16 @@ export function resultLines(lines) {
|
|
|
27
27
|
return lines.map((l, i) => (i === 0 ? c.gray(RESULT_PREFIX) : RESULT_INDENT) + l);
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
// A message of bash mode (`!command`, see App.runBashMode) as it was shown when it ran: the command, then its output
|
|
31
|
+
// (at most 40 lines, the middle left out). null for any other message.
|
|
32
|
+
export function bashModeLines(text) {
|
|
33
|
+
const m = /^<bash-input>([\s\S]*?)<\/bash-input>\n?(?:<bash-stdout>([\s\S]*?)<\/bash-stdout>)?\n?(?:<bash-stderr>([\s\S]*?)<\/bash-stderr>)?/.exec(String(text ?? ''));
|
|
34
|
+
if (!m) return null;
|
|
35
|
+
let lines = [m[2], m[3]].filter((s) => s != null && s !== '').join('\n').split('\n');
|
|
36
|
+
if (lines.length > 40) lines = [...lines.slice(0, 20), c.dim(`… +${lines.length - 40} lines`), ...lines.slice(-20)];
|
|
37
|
+
return [c.magenta('! ') + m[1], ...resultLines(lines.map((l) => c.dim(l)))];
|
|
38
|
+
}
|
|
39
|
+
|
|
30
40
|
function numberWidth(hunks) {
|
|
31
41
|
let max = 1;
|
|
32
42
|
for (const h of hunks) for (const l of h.lines) max = Math.max(max, l.oldNo || 0, l.newNo || 0);
|