@yanzc/claude-pro 0.7.8 → 0.9.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/ui/screen.js CHANGED
@@ -38,6 +38,20 @@ const RESIZE_QUIET_MS = 80; // repaint once the size has not changed for this lo
38
38
  const RESIZE_MAX_WAIT_MS = 300; // ... or at the latest this long after it started changing
39
39
  const HISTORY_KEEP = 600; // static lines remembered for repainting (a screen shows far fewer)
40
40
  const HISTORY_LINE_CHARS = 20_000;
41
+
42
+ // A line as the terminal would show it, so that what is drawn is what was measured: a tab becomes the 4 spaces
43
+ // stringWidth counts it as (the terminal moved to its next 8-column stop instead, past what was measured, and a
44
+ // fullscreen row's erase left old glyphs in the cells it skipped), only what follows the last carriage return
45
+ // stays (a progress bar's "40%\r80%" shows 80%, and no longer overwrites the prefix drawn before it), and other
46
+ // control characters (BEL, backspace...) go. ANSI escapes stay.
47
+ const CONTROLS = /[\x00-\x08\x09\x0b-\x1a\x1c-\x1f\x7f\r]/;
48
+ export function cleanLine(line) {
49
+ if (!CONTROLS.test(line)) return line;
50
+ let s = line.replace(/\r+$/, '');
51
+ const cr = s.lastIndexOf('\r');
52
+ if (cr >= 0) s = s.slice(cr + 1);
53
+ return s.replace(/\t/g, ' ').replace(/[\x00-\x08\x0b-\x1a\x1c-\x1f\x7f]/g, '');
54
+ }
41
55
  const FULL_KEEP = 20_000; // fullscreen: lines of the conversation kept to scroll back through
42
56
  // The alternate screen, and the mouse reported (SGR): buttons, the wheel, and moves while a button is held (a drag).
43
57
  const ALT_ON = '\x1b[?1049h\x1b[?1002h\x1b[?1006h';
@@ -503,9 +517,9 @@ export class Screen {
503
517
  return { anchor: { ...p, col: from }, focus: { ...p, col: to } };
504
518
  }
505
519
 
506
- // A mouse report (fullscreen). Returns {copy: text} when a selection was made, for the caller to put on the
507
- // clipboard. Drag to select (the view scrolls at its edges), double-click a word, triple-click a line; a click
508
- // clears the selection; a click on the "Jump to bottom" bar goes there.
520
+ // A mouse report (fullscreen). Mouse selection only highlights text; Ctrl+C copies it. Drag to select (the view
521
+ // scrolls at its edges), double-click a word, triple-click a line; a click clears the selection; a click on the
522
+ // "Jump to bottom" bar goes there.
509
523
  mouse({ button, x, y, release }) {
510
524
  if (!this.full || this.closed) return null;
511
525
  if (button & 64) return null; // the wheel: the caller scrolls
@@ -526,8 +540,7 @@ export class Screen {
526
540
  this.selection = sel;
527
541
  this.dragging = false;
528
542
  this.draw();
529
- const text = sel ? this.selectedText() : '';
530
- return text ? { copy: text } : null;
543
+ return null;
531
544
  }
532
545
  this.selection = { anchor: p, focus: { ...p }, moved: false };
533
546
  this.dragging = true;
@@ -547,8 +560,7 @@ export class Screen {
547
560
  this.dragging = false;
548
561
  if (!this.selection.moved) { this.clearSelection(); return null; } // a plain click
549
562
  this.lastClick.count = 0; // a drag: the next click starts a count of its own
550
- const text = this.selectedText();
551
- return text ? { copy: text } : null;
563
+ return null;
552
564
  }
553
565
 
554
566
  // Scroll the conversation up (`rows` > 0) or down. 'top' and 'bottom' go to its ends.
@@ -648,12 +660,23 @@ export class Screen {
648
660
  // Append lines (strings, may contain \n) to the static log. `onLog(items)` is told about each call (the remote
649
661
  // control mirrors what the terminal prints).
650
662
  log(...items) {
663
+ this.queueLog(items);
664
+ this.flush();
665
+ }
666
+
667
+ // As log(), drawn with the next frame (within 16 ms) instead of at once: for streamed text, where a line comes
668
+ // with nearly every delta and drawing each at once rewrote the whole screen (fullscreen) for every line.
669
+ logSoon(...items) {
670
+ this.queueLog(items);
671
+ this.schedule();
672
+ }
673
+
674
+ queueLog(items) {
651
675
  if (this.onLog) { try { this.onLog(items); } catch { /* the listener's problem */ } }
652
676
  for (const item of items) {
653
677
  if (Array.isArray(item)) this.staticQueue.push(...item);
654
678
  else this.staticQueue.push(String(item));
655
679
  }
656
- this.flush();
657
680
  }
658
681
 
659
682
  schedule() {
@@ -664,7 +687,7 @@ export class Screen {
664
687
  // Take the queued static output as lines, remembering them for a later repaint.
665
688
  takeStatic() {
666
689
  if (!this.staticQueue.length) return [];
667
- const lines = this.staticQueue.join('\n').split(/\r?\n/);
690
+ const lines = this.staticQueue.join('\n').split(/\r?\n/).map(cleanLine);
668
691
  this.staticQueue = [];
669
692
  const first = this.history.length;
670
693
  for (const line of lines) this.history.push(line.length > HISTORY_LINE_CHARS ? line.slice(0, HISTORY_LINE_CHARS) : line);
@@ -701,7 +724,7 @@ export class Screen {
701
724
  const rows = [];
702
725
  let cursorRow = null, cursorCol = 0;
703
726
  lines.forEach((line, i) => {
704
- const wrapped = wrapLine(line, cols - 1);
727
+ const wrapped = wrapLine(cleanLine(line), cols - 1);
705
728
  if (cursor && cursor.row === i) {
706
729
  const col = cursor.col;
707
730
  const extra = Math.floor(col / (cols - 1));
@@ -856,7 +879,9 @@ export class Screen {
856
879
 
857
880
  // Print any pending output, then remove the live region (input box etc.) for good.
858
881
  // `keepTitle`: another process takes the terminal over at once (a restart), so the tab keeps its title.
859
- close({ keepTitle = false } = {}) {
882
+ // `after`: lines to leave on the terminal (the exit's usage and resume hint). In fullscreen they are written after
883
+ // the alternate screen is gone: logged before, they were drawn on it and vanished with it.
884
+ close({ keepTitle = false, after = [] } = {}) {
860
885
  if (this.closed) return;
861
886
  if (this.resizing) this.repaint(); // the cursor is not where the last draw left it: put things in order first
862
887
  this.renderLive = () => ({ lines: [] });
@@ -865,7 +890,9 @@ export class Screen {
865
890
  this.takeStatic();
866
891
  this.full = false;
867
892
  this.out.write(ALT_OFF); // the shell's screen comes back as it was
893
+ if (after.length) this.out.write(`${after.map((l) => `${l}\x1b[0m`).join('\r\n')}\r\n`);
868
894
  } else {
895
+ this.staticQueue.push(...after);
869
896
  this.flush();
870
897
  }
871
898
  this.closed = true;
package/src/updater.js CHANGED
@@ -8,6 +8,7 @@ import path from 'node:path';
8
8
  import https from 'node:https';
9
9
  import { spawn } from 'node:child_process';
10
10
  import { CONFIG_DIR, INSTALL_DIR, VERSION } from './config.js';
11
+ import { killTree } from './utils/shell.js';
11
12
 
12
13
  // The name on npm (scoped: npm refused plain `claude-pro` as too close to another package's name).
13
14
  export const PACKAGE_NAME = JSON.parse(fs.readFileSync(path.join(INSTALL_DIR, 'package.json'), 'utf8')).name;
@@ -101,9 +102,12 @@ function runNpm(args, { timeoutMs = 300_000 } = {}) {
101
102
  return new Promise((resolve) => {
102
103
  const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, { shell: process.platform === 'win32', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
103
104
  let out = '';
104
- child.stdout.on('data', (d) => { out += d; });
105
- child.stderr.on('data', (d) => { out += d; });
106
- const timer = setTimeout(() => child.kill(), timeoutMs);
105
+ const take = (d) => { out = (out + d).slice(-200_000); };
106
+ child.stdout.on('data', take);
107
+ child.stderr.on('data', take);
108
+ // With shell: true, child.kill() ends only cmd.exe: npm kept the pipes open, 'close' never came and the
109
+ // timeout did nothing. The whole tree goes.
110
+ const timer = setTimeout(() => { killTree(child); }, timeoutMs);
107
111
  child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, output: e.message }); });
108
112
  child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, output: out.trim() }); });
109
113
  });
@@ -1,6 +1,5 @@
1
- // Read an image from the system clipboard (alt+v / ctrl+v in the prompt), like Claude Code.
2
- // Windows: PowerShell + System.Windows.Forms; macOS: osascript; Linux: wl-paste / xclip.
3
- // Large images are scaled so the long edge is at most 1568px (the API's recommended size).
1
+ // Clipboard helpers for explicit Ctrl+C copy and Ctrl+V text/image paste.
2
+ // Image files can also be attached by path through imageFromFile.
4
3
 
5
4
  import fs from 'node:fs';
6
5
  import os from 'node:os';
@@ -28,9 +27,7 @@ function run(cmd, args, { env, timeout = 15_000 } = {}) {
28
27
  });
29
28
  }
30
29
 
31
- // Prints "IMG <format> <w>x<h>" after writing $env:CLAUDE_PRO_IMG_OUT, or "FILE <path>" when the
32
- // clipboard holds a copied image file. Exit code 2 = no image. CLAUDE_PRO_IMG_SOURCE (a file) replaces
33
- // the clipboard as input, which the tests use so they don't clobber the real clipboard.
30
+ // Read an image from the system clipboard for Ctrl+V in the prompt dialog.
34
31
  const PS_SCRIPT = `
35
32
  $ErrorActionPreference = 'Stop'
36
33
  Add-Type -AssemblyName System.Windows.Forms
@@ -120,8 +117,8 @@ async function readLinux() {
120
117
  for (const [cmd, args] of [['wl-paste', ['--type', 'image/png']], ['xclip', ['-selection', 'clipboard', '-t', 'image/png', '-o']]]) {
121
118
  const r = await new Promise((resolve) => {
122
119
  const chunks = [];
123
- const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'ignore'] });
124
- // A clipboard owner that never answers must not leave the reader hanging.
120
+ let child;
121
+ try { child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'ignore'] }); } catch { resolve(null); return; }
125
122
  const timer = setTimeout(() => child.kill(), 5000);
126
123
  child.stdout.on('data', (d) => chunks.push(d));
127
124
  child.on('error', () => { clearTimeout(timer); resolve(null); });
@@ -135,9 +132,15 @@ async function readLinux() {
135
132
  return { error: null };
136
133
  }
137
134
 
138
- // Put `text` on the system clipboard (the fullscreen renderer's selection): Windows PowerShell (read as UTF-8 from
139
- // stdin, so any text and any length), pbcopy on macOS, wl-copy / xclip / xsel elsewhere. Resolves with whether
140
- // one of them took it.
135
+ export async function readClipboardImage({ source } = {}) {
136
+ if (process.platform === 'win32') return readWindows(source);
137
+ if (process.platform === 'darwin') return readMac();
138
+ return readLinux();
139
+ }
140
+
141
+ // Put `text` on the system clipboard for an explicit Ctrl+C copy: Windows PowerShell (read as UTF-8 from stdin,
142
+ // so any text and any length), pbcopy on macOS, wl-copy / xclip / xsel elsewhere. Resolves with whether one of them
143
+ // took it.
141
144
  export async function writeClipboard(text) {
142
145
  const tries = process.platform === 'win32'
143
146
  ? [['powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '$s=[IO.StreamReader]::new([Console]::OpenStandardInput(),[Text.Encoding]::UTF8).ReadToEnd(); Set-Clipboard -Value $s']]]
@@ -164,9 +167,8 @@ export async function writeClipboard(text) {
164
167
  return false;
165
168
  }
166
169
 
167
- // The text on the system clipboard ('' when there is none), for a right click in the fullscreen renderer, which
168
- // gets the mouse instead of the terminal: Windows PowerShell (written out as UTF-8), pbpaste on macOS,
169
- // wl-paste / xclip / xsel elsewhere.
170
+ // Read the text on the system clipboard for an explicit Ctrl+V paste: Windows PowerShell (written out as UTF-8),
171
+ // pbpaste on macOS, wl-paste / xclip / xsel elsewhere. Returns '' when there is no readable clipboard.
170
172
  export async function readClipboardText() {
171
173
  const tries = process.platform === 'win32'
172
174
  ? [['powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '$t = Get-Clipboard -Raw; if ($t) { $b = [Text.Encoding]::UTF8.GetBytes($t); $o = [Console]::OpenStandardOutput(); $o.Write($b, 0, $b.Length) }']]]
@@ -192,64 +194,3 @@ export async function readClipboardText() {
192
194
  }
193
195
  return '';
194
196
  }
195
-
196
- // Returns {image} on success, {error: string} on failure, or {error: null} when the clipboard has no image.
197
- export async function readClipboardImage({ source } = {}) {
198
- if (process.platform === 'win32') return readWindows(source);
199
- if (process.platform === 'darwin') return readMac();
200
- return readLinux();
201
- }
202
-
203
- // Watch the clipboard and call `onCopy(chars)` when something new is put on it, so that the program can say
204
- // "copied" after the user copies text selected in the terminal (the terminal itself does not tell the program).
205
- // Windows only: one long-lived PowerShell that polls the clipboard's sequence number, which is cheap, and leaves
206
- // when this process is gone. Returns {close()}; elsewhere it never calls back.
207
- const WATCH_SCRIPT = `
208
- $ErrorActionPreference = 'SilentlyContinue'
209
- Add-Type -Namespace ClaudePro -Name Clip -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();'
210
- $parent = [int]$env:CLAUDE_PRO_PARENT_PID
211
- $last = [ClaudePro.Clip]::GetClipboardSequenceNumber()
212
- $n = 0
213
- while ($true) {
214
- Start-Sleep -Milliseconds 250
215
- $seq = [ClaudePro.Clip]::GetClipboardSequenceNumber()
216
- if ($seq -ne $last) {
217
- $last = $seq
218
- Start-Sleep -Milliseconds 50
219
- $text = Get-Clipboard -Raw
220
- $len = if ($text) { $text.Length } else { 0 }
221
- [Console]::Out.WriteLine("COPY $len")
222
- [Console]::Out.Flush()
223
- }
224
- $n++
225
- if ($n % 8 -eq 0) { try { [void][System.Diagnostics.Process]::GetProcessById($parent) } catch { exit } }
226
- }
227
- `;
228
-
229
- export function watchClipboard(onCopy) {
230
- if (process.platform !== 'win32') return { close() {} };
231
- let child;
232
- try {
233
- const encoded = Buffer.from(WATCH_SCRIPT, 'utf16le').toString('base64'); // "-Command -" runs a loop line by line, which breaks it
234
- child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], {
235
- env: { ...process.env, CLAUDE_PRO_PARENT_PID: String(process.pid) }, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'],
236
- });
237
- } catch {
238
- return { close() {} };
239
- }
240
- child.on('error', () => {});
241
- let buf = '';
242
- child.stdout.setEncoding('utf8');
243
- child.stdout.on('data', (d) => {
244
- buf += d;
245
- let i;
246
- while ((i = buf.indexOf('\n')) >= 0) {
247
- const m = /^COPY (\d+)/.exec(buf.slice(0, i).trim());
248
- buf = buf.slice(i + 1);
249
- if (m) { try { onCopy(Number(m[1])); } catch { /* the callback's problem */ } }
250
- }
251
- });
252
- child.unref();
253
- child.stdout.unref?.();
254
- return { close() { try { child.kill(); } catch { /* gone already */ } } };
255
- }
package/src/utils/diff.js CHANGED
@@ -1,6 +1,20 @@
1
1
  // Line diff (Myers O(ND)) and hunk construction for displaying edits.
2
2
 
3
+ // The lines both versions start and end with are left out of the Myers run: an edit of a big file differs in a few
4
+ // lines, and the search's memory grows with lines × differences (a one-line edit of a 6,000-line file used to hit
5
+ // the size guard and show as the whole file removed and added again).
3
6
  export function diffLines(a, b) {
7
+ let pre = 0;
8
+ while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
9
+ let post = 0;
10
+ while (post < a.length - pre && post < b.length - pre && a[a.length - 1 - post] === b[b.length - 1 - post]) post++;
11
+ const same = (lines) => lines.map((line) => ({ op: ' ', line }));
12
+ return [...same(a.slice(0, pre)), ...myers(a.slice(pre, a.length - post), b.slice(pre, b.length - post)), ...same(a.slice(a.length - post))];
13
+ }
14
+
15
+ const MAX_D = 2000; // differences searched for (about 16 MB of trace)
16
+
17
+ function myers(a, b) {
4
18
  const n = a.length, m = b.length;
5
19
  const max = n + m;
6
20
  if (max === 0) return [];
@@ -9,11 +23,14 @@ export function diffLines(a, b) {
9
23
  return [...a.map((line) => ({ op: '-', line })), ...b.map((line) => ({ op: '+', line }))];
10
24
  }
11
25
  const v = new Int32Array(2 * max + 2);
26
+ // For each d only the diagonals the backtrack reads (-d-1 .. d+1), not the whole of v. The trace still grows
27
+ // with d², so past MAX_D differences (a rewrite rather than an edit) the middle shows as removed and added.
12
28
  const trace = [];
13
29
  const off = max + 1;
14
30
  let found = false;
15
31
  for (let d = 0; d <= max && !found; d++) {
16
- trace.push(v.slice());
32
+ if (d > MAX_D) return [...a.map((line) => ({ op: '-', line })), ...b.map((line) => ({ op: '+', line }))];
33
+ trace.push(v.slice(off - d - 1, off + d + 2));
17
34
  for (let k = -d; k <= d; k += 2) {
18
35
  let x;
19
36
  if (k === -d || (k !== d && v[off + k - 1] < v[off + k + 1])) x = v[off + k + 1];
@@ -29,11 +46,12 @@ export function diffLines(a, b) {
29
46
  let x = n, y = m;
30
47
  for (let d = trace.length - 1; d >= 0; d--) {
31
48
  const vv = trace[d];
49
+ const at = (k) => vv[k + d + 1]; // v[off + k] as it was before step d
32
50
  const k = x - y;
33
51
  let prevK;
34
- if (k === -d || (k !== d && vv[off + k - 1] < vv[off + k + 1])) prevK = k + 1;
52
+ if (k === -d || (k !== d && at(k - 1) < at(k + 1))) prevK = k + 1;
35
53
  else prevK = k - 1;
36
- const prevX = vv[off + prevK];
54
+ const prevX = at(prevK);
37
55
  const prevY = prevX - prevK;
38
56
  while (x > prevX && y > prevY) { ops.push({ op: ' ', line: a[x - 1] }); x--; y--; }
39
57
  if (d > 0) {
@@ -0,0 +1,136 @@
1
+ // Directories of this computer for the gateway's web page: what it shows to choose a working directory from
2
+ // (/cd from the page, see App.remoteList). Moved here from the computer service (host.js, removed in 0.8.0), whose
3
+ // listing the page was built for: the fields and the messages (Chinese, as the page is) are the same.
4
+
5
+ import fs from 'node:fs';
6
+ import fsp from 'node:fs/promises';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { normalizeDir } from './paths.js';
10
+
11
+ const MAX_ENTRIES = 1000;
12
+ const MAX_RECENT = 15;
13
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
14
+
15
+ const describeFsError = (e, dir) => (e.code === 'ENOENT' || e.code === 'ENOTDIR' ? `目录不存在:${dir}`
16
+ : e.code === 'EACCES' || e.code === 'EPERM' ? `没有权限读取:${dir}`
17
+ : `读取 ${dir} 失败:${e.message}`);
18
+
19
+ let rootsCache = { at: 0, roots: [] };
20
+ async function roots(platform = process.platform) {
21
+ if (platform !== 'win32') return ['/'];
22
+ if (Date.now() - rootsCache.at < 30_000) return rootsCache.roots;
23
+ // a disconnected network drive can take long to answer: 1.5 seconds each, all at once
24
+ const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
25
+ const found = await Promise.all(letters.map((l) => Promise.race([
26
+ fsp.access(`${l}:\\`).then(() => `${l}:\\`, () => null),
27
+ sleep(1500).then(() => null),
28
+ ])));
29
+ rootsCache = { at: Date.now(), roots: found.filter(Boolean) };
30
+ return rootsCache.roots;
31
+ }
32
+
33
+ // The directories in `input` (only directories, links to them included), for the page to choose from:
34
+ // {path, parent, sep, entries: [{name, path}], truncated, home, roots, recent}.
35
+ export async function listDirectory(input, { home = os.homedir(), recent = () => [] } = {}) {
36
+ const dir = normalizeDir(input, { home });
37
+ if (!dir) throw new Error(`不是绝对路径:${input}`);
38
+ let st;
39
+ try { st = await fsp.stat(dir); } catch (e) { throw new Error(describeFsError(e, dir)); }
40
+ if (!st.isDirectory()) throw new Error(`不是目录:${dir}`);
41
+ let dirents;
42
+ try { dirents = await fsp.readdir(dir, { withFileTypes: true }); } catch (e) { throw new Error(describeFsError(e, dir)); }
43
+ const entries = [];
44
+ for (const d of dirents) {
45
+ const full = path.join(dir, d.name);
46
+ let isDir = d.isDirectory();
47
+ if (!isDir && d.isSymbolicLink()) {
48
+ // a link to a directory counts, unless it cannot be opened (Windows' old junctions in the profile:
49
+ // "My Documents", "Application Data" ... refuse to be listed)
50
+ try { isDir = (await fsp.stat(full)).isDirectory(); } catch { isDir = false; }
51
+ if (isDir) {
52
+ let handle = null;
53
+ try {
54
+ handle = await fsp.opendir(full);
55
+ await handle.read(); // Windows checks the access at the first read, not at the opening
56
+ } catch {
57
+ isDir = false;
58
+ } finally {
59
+ await handle?.close().catch(() => {});
60
+ }
61
+ }
62
+ // ... and the profile's other compatibility junctions ("Application Data", "Recent", the Start Menu in the
63
+ // system's language ...), which Explorer hides: all lead into AppData
64
+ if (isDir && process.platform === 'win32' && dir.toLowerCase() === path.resolve(home).toLowerCase()) {
65
+ try {
66
+ if ((await fsp.realpath(full)).toLowerCase().startsWith(`${path.join(home, 'AppData').toLowerCase()}\\`)) isDir = false;
67
+ } catch { isDir = false; }
68
+ }
69
+ }
70
+ if (isDir) entries.push({ name: d.name, path: full });
71
+ }
72
+ const hidden = (name) => (name.startsWith('.') ? 1 : 0);
73
+ entries.sort((a, b) => hidden(a.name) - hidden(b.name) || a.name.localeCompare(b.name, undefined, { sensitivity: 'accent', numeric: true }));
74
+ const parent = path.dirname(dir);
75
+ return {
76
+ path: dir,
77
+ parent: parent === dir ? null : parent,
78
+ sep: path.sep,
79
+ entries: entries.slice(0, MAX_ENTRIES),
80
+ truncated: entries.length > MAX_ENTRIES,
81
+ home,
82
+ roots: await roots(),
83
+ recent: recent(),
84
+ };
85
+ }
86
+
87
+ // The first line of a session file is {type: 'meta', cwd, ...} (see SessionStore.append).
88
+ function sessionCwd(file) {
89
+ let fd = null;
90
+ try {
91
+ fd = fs.openSync(file, 'r');
92
+ const buf = Buffer.alloc(16 * 1024);
93
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
94
+ const meta = JSON.parse(buf.subarray(0, n).toString('utf8').split('\n')[0]);
95
+ return meta?.type === 'meta' && typeof meta.cwd === 'string' ? meta.cwd : null;
96
+ } catch {
97
+ return null;
98
+ } finally {
99
+ if (fd !== null) fs.closeSync(fd);
100
+ }
101
+ }
102
+
103
+ // Where claude-pro sessions ran lately on this computer, newest first: [{path, at}] of the directories that are
104
+ // still there. `projects`: the config directory's projects folder. One line read per project (its newest session's
105
+ // first line).
106
+ export function recentDirectories({ projects, max = MAX_RECENT }) {
107
+ let dirs = [];
108
+ try { dirs = fs.readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory()); } catch { return []; }
109
+ const found = [];
110
+ for (const d of dirs) {
111
+ const sub = path.join(projects, d.name);
112
+ let newest = null;
113
+ try {
114
+ for (const f of fs.readdirSync(sub)) {
115
+ if (!f.endsWith('.jsonl')) continue;
116
+ const m = fs.statSync(path.join(sub, f)).mtimeMs;
117
+ if (!newest || m > newest.m) newest = { f, m };
118
+ }
119
+ } catch { continue; }
120
+ if (!newest) continue;
121
+ const cwd = sessionCwd(path.join(sub, newest.f));
122
+ if (cwd) found.push({ path: path.resolve(cwd), at: newest.m });
123
+ }
124
+ found.sort((a, b) => b.at - a.at);
125
+ const seen = new Set();
126
+ const out = [];
127
+ for (const r of found) {
128
+ const key = process.platform === 'win32' ? r.path.toLowerCase() : r.path;
129
+ if (seen.has(key)) continue;
130
+ seen.add(key);
131
+ try { if (!fs.statSync(r.path).isDirectory()) continue; } catch { continue; }
132
+ out.push({ path: r.path, at: new Date(r.at).toISOString() });
133
+ if (out.length >= max) break;
134
+ }
135
+ return out;
136
+ }
@@ -0,0 +1,187 @@
1
+ // Text files in the encodings met on Chinese Windows machines: UTF-8 (with or without a BOM), UTF-16 with a BOM
2
+ // (what Windows PowerShell 5 redirects to), and GBK (code page 936: legacy projects, files saved by older tools).
3
+ // decodeText() says which one a file is in and encodeText() writes text back in it, so that an edit leaves every
4
+ // byte it did not change as it was. Decoding everything as UTF-8 used to turn each Chinese character of a GBK file
5
+ // into U+FFFD on its first edit. A file that is none of these is marked `lossy`: it can be read, not rewritten.
6
+
7
+ import { spawnSync } from 'node:child_process';
8
+
9
+ const strictUtf8 = new TextDecoder('utf-8', { fatal: true });
10
+ const lenientUtf8 = new TextDecoder('utf-8');
11
+ const strictGbk = new TextDecoder('gbk', { fatal: true }); // the WHATWG gbk decoder, which is the gb18030 one
12
+
13
+ // Whether bytes that are not valid UTF-8 as a whole are still UTF-8 text with a few bad bytes (a character cut at
14
+ // the end of a line by `cut -c` or `head -c`, a stray Latin-1 byte), rather than text in another encoding. Chinese
15
+ // UTF-8 is often valid GBK by chance (E4 B8 AD E6 96 87, "中文", reads as "涓枃"), so trying GBK first turned such
16
+ // a line or file into mojibake; GBK text read as UTF-8, the other way round, is mostly invalid sequences, with a
17
+ // valid two-byte character here and there by chance. An incomplete sequence counts once, however long.
18
+ export function mostlyUtf8(buf) {
19
+ let good = 0;
20
+ let bad = 0;
21
+ for (let i = 0; i < buf.length;) {
22
+ const b = buf[i];
23
+ if (b < 0x80) { i++; continue; }
24
+ const n = b >= 0xc2 && b <= 0xdf ? 2 : b >= 0xe0 && b <= 0xef ? 3 : b >= 0xf0 && b <= 0xf4 ? 4 : 0;
25
+ let k = 1;
26
+ while (n && k < n && i + k < buf.length && (buf[i + k] & 0xc0) === 0x80) k++;
27
+ if (n && k === n) good++;
28
+ else bad++;
29
+ i += n ? k : 1;
30
+ }
31
+ return bad === 0 || good >= 4 * bad;
32
+ }
33
+
34
+ // {text, encoding: 'utf8'|'utf16le'|'utf16be'|'gbk', bom, lossy}, or null for binary data. `lossy`: writing the
35
+ // text back would not give these bytes (undecodable bytes became U+FFFD, or GB18030 forms GBK cannot write).
36
+ // `writable: false` skips that check for a GBK file, for a caller that only reads (Grep).
37
+ export function decodeText(buf, { writable = true } = {}) {
38
+ if (buf[0] === 0xff && buf[1] === 0xfe) return { text: buf.toString('utf16le', 2), encoding: 'utf16le', bom: true, lossy: buf.length % 2 !== 0 };
39
+ if (buf[0] === 0xfe && buf[1] === 0xff) return { text: new TextDecoder('utf-16be').decode(buf.subarray(2)), encoding: 'utf16be', bom: true, lossy: buf.length % 2 !== 0 };
40
+ const bom = buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf;
41
+ const body = bom ? buf.subarray(3) : buf;
42
+ if (body.subarray(0, 8000).includes(0)) return null;
43
+ try { return { text: strictUtf8.decode(body), encoding: 'utf8', bom, lossy: false }; } catch { /* not UTF-8 */ }
44
+ if (!bom && !mostlyUtf8(body)) {
45
+ let text = null;
46
+ try { text = strictGbk.decode(body); } catch { /* not GBK either */ }
47
+ // Writable only when the text turns back into exactly these bytes (GB18030's four-byte forms do not).
48
+ if (text !== null) return { text, encoding: 'gbk', bom: false, lossy: writable && !encodeGbk(text).buffer?.equals(body) };
49
+ }
50
+ return { text: lenientUtf8.decode(body), encoding: 'utf8', bom, lossy: true };
51
+ }
52
+
53
+ // The name of an encoding for messages.
54
+ export const encodingName = (encoding) => ({ utf8: 'UTF-8', utf16le: 'UTF-16 LE', utf16be: 'UTF-16 BE', gbk: 'GBK' })[encoding] || encoding;
55
+
56
+ // `text` as bytes in `encoding` (with its BOM when `bom`): {buffer}, or {error, chars} when some characters cannot
57
+ // be written in it (GBK has no emoji, say).
58
+ export function encodeText(text, { encoding = 'utf8', bom = false } = {}) {
59
+ if (encoding === 'utf16le') return { buffer: Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, 'utf16le')]) };
60
+ if (encoding === 'utf16be') {
61
+ const le = Buffer.from(text, 'utf16le');
62
+ for (let i = 0; i + 1 < le.length; i += 2) { const t = le[i]; le[i] = le[i + 1]; le[i + 1] = t; }
63
+ return { buffer: Buffer.concat([Buffer.from([0xfe, 0xff]), le]) };
64
+ }
65
+ if (encoding === 'gbk') return encodeGbk(text);
66
+ const utf8 = Buffer.from(text, 'utf8');
67
+ return { buffer: bom ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), utf8]) : utf8 };
68
+ }
69
+
70
+ // GBK's two-byte table, character -> bytes, built once from the decoder itself (there is no GBK encoder in Node).
71
+ let gbkTable = null;
72
+ function gbkCodes() {
73
+ if (gbkTable) return gbkTable;
74
+ gbkTable = new Map();
75
+ const lenient = new TextDecoder('gbk');
76
+ const pair = Buffer.alloc(2);
77
+ for (let lead = 0x81; lead <= 0xfe; lead++) {
78
+ for (let trail = 0x40; trail <= 0xfe; trail++) {
79
+ if (trail === 0x7f) continue;
80
+ pair[0] = lead; pair[1] = trail;
81
+ const ch = lenient.decode(pair);
82
+ if (ch.length === 1 && ch !== '\ufffd' && !gbkTable.has(ch)) gbkTable.set(ch, (lead << 8) | trail);
83
+ }
84
+ }
85
+ gbkTable.set('\u20ac', 0x80); // the euro sign, GBK's one single-byte character above ASCII
86
+ return gbkTable;
87
+ }
88
+
89
+ function encodeGbk(text) {
90
+ const out = Buffer.alloc(text.length * 2);
91
+ let n = 0;
92
+ let codes = null;
93
+ const missing = new Set();
94
+ for (const ch of text) {
95
+ const cp = ch.codePointAt(0);
96
+ if (cp < 0x80) { out[n++] = cp; continue; }
97
+ codes ??= gbkCodes();
98
+ const code = codes.get(ch);
99
+ if (code === undefined) { missing.add(ch); continue; }
100
+ if (code > 0xff) out[n++] = code >> 8;
101
+ out[n++] = code & 0xff;
102
+ }
103
+ if (missing.size) {
104
+ const chars = [...missing].slice(0, 10).map((c) => `${c} (U+${c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0')})`);
105
+ return { error: `characters GBK cannot represent: ${chars.join(', ')}${missing.size > 10 ? ', …' : ''}`, chars: [...missing] };
106
+ }
107
+ return { buffer: out.subarray(0, n) };
108
+ }
109
+
110
+ // ---- Output of commands
111
+ //
112
+ // MSYS tools, git and node write UTF-8, but native Windows programs writing to a pipe use the console code page:
113
+ // 936 (GBK) on Chinese Windows, so the output of ipconfig, tasklist, schtasks, cmd, javac or MSBuild used to reach
114
+ // the model as mojibake. OutputDecoder decodes it line by line: UTF-8 where a line is UTF-8, else in the console
115
+ // code page. A line is decoded once it is complete, so a character is never cut between two chunks.
116
+
117
+ const CODE_PAGES = { 936: 'gbk', 54936: 'gb18030', 950: 'big5', 932: 'shift_jis', 949: 'euc-kr', 866: 'ibm866', 874: 'windows-874' };
118
+ let legacyDecoder; // undefined: not looked up yet; null: none (UTF-8 console, not Windows, unknown code page)
119
+
120
+ // A strict TextDecoder for this machine's console code page (`chcp`, looked up once), or null.
121
+ export function consoleDecoder() {
122
+ if (legacyDecoder !== undefined) return legacyDecoder;
123
+ legacyDecoder = null;
124
+ if (process.platform !== 'win32') return null;
125
+ try {
126
+ const r = spawnSync('chcp', [], { windowsHide: true, timeout: 3000 });
127
+ const cp = Number(/(\d+)\s*$/.exec(String(r.stdout || '').trim())?.[1]);
128
+ const label = CODE_PAGES[cp] || (cp >= 1250 && cp <= 1258 ? `windows-${cp}` : null);
129
+ if (label) legacyDecoder = new TextDecoder(label, { fatal: true });
130
+ } catch { /* none: such lines stay lenient UTF-8 */ }
131
+ return legacyDecoder;
132
+ }
133
+
134
+ const isAscii = (buf) => { for (let i = 0; i < buf.length; i++) if (buf[i] > 0x7f) return false; return true; };
135
+
136
+ // Complete lines (or a whole stream) of command output as text.
137
+ export function decodeOutput(buf) {
138
+ if (!buf.length) return '';
139
+ try { return strictUtf8.decode(buf); } catch { /* some line is not UTF-8 */ }
140
+ let out = '';
141
+ let start = 0;
142
+ while (start < buf.length) {
143
+ const nl = buf.indexOf(0x0a, start);
144
+ const end = nl < 0 ? buf.length : nl + 1;
145
+ const line = buf.subarray(start, end);
146
+ let text = null;
147
+ try { text = strictUtf8.decode(line); } catch {
148
+ const legacy = mostlyUtf8(line) ? null : consoleDecoder();
149
+ if (legacy) { try { text = legacy.decode(line); } catch { /* neither */ } }
150
+ }
151
+ out += text ?? lenientUtf8.decode(line);
152
+ start = end;
153
+ }
154
+ return out;
155
+ }
156
+
157
+ export class OutputDecoder {
158
+ constructor() { this.pending = null; }
159
+
160
+ // The text of `chunk` that can be decoded now. An unfinished last line waits for the next chunk when it has
161
+ // non-ASCII bytes (it could end inside a character); a long one is let through at a UTF-8 character boundary.
162
+ write(chunk) {
163
+ let buf = this.pending ? Buffer.concat([this.pending, chunk]) : chunk;
164
+ this.pending = null;
165
+ const cut = buf.lastIndexOf(0x0a) + 1;
166
+ const tail = buf.subarray(cut);
167
+ if (!tail.length || isAscii(tail)) return decodeOutput(buf);
168
+ if (tail.length > 65_536) {
169
+ let keep = tail.length;
170
+ for (let i = tail.length - 1; i >= tail.length - 3 && i >= 0; i--) {
171
+ if (tail[i] < 0x80) break;
172
+ if (tail[i] >= 0xc0) { if (tail.length - i < (tail[i] >= 0xf0 ? 4 : tail[i] >= 0xe0 ? 3 : 2)) keep = i; break; }
173
+ }
174
+ this.pending = keep < tail.length ? Buffer.from(tail.subarray(keep)) : null;
175
+ return decodeOutput(buf.subarray(0, cut + keep));
176
+ }
177
+ this.pending = Buffer.from(tail);
178
+ return decodeOutput(buf.subarray(0, cut));
179
+ }
180
+
181
+ // What is still held back, at the end of the stream.
182
+ end() {
183
+ const rest = this.pending;
184
+ this.pending = null;
185
+ return rest ? decodeOutput(rest) : '';
186
+ }
187
+ }