@yanzc/claude-pro 0.9.2 → 0.9.4
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 +6 -3
- package/package.json +1 -1
- package/src/config.js +11 -1
- package/src/runtime.js +10 -4
- package/src/session.js +47 -34
- package/src/ui/ansi.js +60 -2
- package/src/ui/repl.js +2 -1
- package/src/ui/screen.js +110 -20
package/README.md
CHANGED
|
@@ -71,7 +71,7 @@ claude-pro -p "用 Read 工具读取 package.json,告诉我项目版本"
|
|
|
71
71
|
|
|
72
72
|
网关 key 只来自 `/login`:登录后保存在 `~/.claude-pro/gateway.json`,不用手动填写,也没有环境变量或 `.env` 文件可以设置它(没有浏览器的机器可以把另一台登录过的电脑的 `gateway.json` 拷过去)。
|
|
73
73
|
|
|
74
|
-
一般只需要 `/login`、`/model`、`/effort`、`/tui` 和 settings
|
|
74
|
+
一般只需要 `/login`、`/model`、`/effort`、`/tui` 和 settings。六个普通设置直接写在 `settings.json` 顶层(下面也是默认值):
|
|
75
75
|
|
|
76
76
|
```json
|
|
77
77
|
{
|
|
@@ -79,10 +79,13 @@ claude-pro -p "用 Read 工具读取 package.json,告诉我项目版本"
|
|
|
79
79
|
"effort": "auto",
|
|
80
80
|
"tui": "fullscreen",
|
|
81
81
|
"promptCacheTtl": "1h",
|
|
82
|
-
"subagentPromptCacheTtl": "5m"
|
|
82
|
+
"subagentPromptCacheTtl": "5m",
|
|
83
|
+
"cleanupPeriodDays": 30
|
|
83
84
|
}
|
|
84
85
|
```
|
|
85
86
|
|
|
87
|
+
`cleanupPeriodDays` 和 Claude Code 的同名设置一样:会话最后一次使用超过这么多天就删除(连同它的 trace,此后 `/resume` 里也看不到),每次启动后在后台清理所有项目,一台机器一小时最多一次;保存的大块工具输出最多留 7 天、`/rewind` 快照最多 14 天,项目记忆从不删。最小 1,想长期保留就设 `3650` 之类的大数。这一项只从 `~/.claude-pro/settings.json` 读,项目里的设置文件改不了它。
|
|
88
|
+
|
|
86
89
|
也可以用命令修改:
|
|
87
90
|
|
|
88
91
|
```bash
|
|
@@ -93,7 +96,7 @@ claude-pro config list --advanced # 另外显示高级配置
|
|
|
93
96
|
claude-pro config set CLAUDE_PRO_GATEWAY_URL https://gw.predix.icu
|
|
94
97
|
```
|
|
95
98
|
|
|
96
|
-
会话中 `/config`
|
|
99
|
+
会话中 `/config` 默认只显示这六项,`/config advanced` 查看高级项;`/config set model sonnet` 等同于 CLI 的 `config set`。普通设置写顶层,高级设置写 `env`。`/config set/unset` 保留 `--project`、`--local`,分别修改项目共享设置或本地设置。`/model`、`/effort` 仍会记住选择,`/tui` 记到顶层 `tui`;`--model`、`--effort` 可覆盖本次启动。
|
|
97
100
|
|
|
98
101
|
设置文件从低到高:`~/.claude-pro/settings.json`、项目 `.claude-pro/settings.json`、`.claude-pro/settings.local.json`。高级项仍兼容进程环境变量(高于设置文件),包括网关地址、远程会话、输出/thinking 预算、缓存总开关、保活、网络重试、工具路径、验证、自动记忆/话题标题和 Trace 开关;普通设置不从进程环境读取。旧 `settings.json.env` 中的 `CLAUDE_PRO_GATEWAY_MODEL`、`CLAUDE_CODE_EFFORT_LEVEL`、`CLAUDE_PRO_TUI`、`CLAUDE_CODE_PROMPT_CACHE_TTL`、`CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL` 只作为兼容别名读取,同文件顶层新字段优先;用 `config set` 或 `/config set` 设置旧别名,会改写顶层新字段并移除同文件旧别名。provider 固定为 `gateway`,已删除 `--provider` 和 `CLAUDE_PRO_PROVIDER` 配置入口。
|
|
99
102
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yanzc/claude-pro",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.4",
|
|
4
4
|
"description": "claude-pro: a command line coding agent for the codex-gateway. Full access with no permission prompts; file edits are checkpointed and can be rewound.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
package/src/config.js
CHANGED
|
@@ -33,6 +33,9 @@ export const BASIC_SETTINGS = {
|
|
|
33
33
|
tui: { default: 'fullscreen', legacy: 'CLAUDE_PRO_TUI', description: 'fullscreen or default; /tui switches and remembers it' },
|
|
34
34
|
promptCacheTtl: { default: '1h', legacy: 'CLAUDE_CODE_PROMPT_CACHE_TTL', description: 'Conversation prompt cache: 5m or 1h' },
|
|
35
35
|
subagentPromptCacheTtl: { default: '5m', legacy: 'CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL', description: 'Sub-agent, compaction and side-query prompt cache: 5m or 1h' },
|
|
36
|
+
// `userOnly`: read from ~/.claude-pro/settings.json only. It deletes the data of every project, so a project's
|
|
37
|
+
// settings file (it comes with the repository) must not lower it.
|
|
38
|
+
cleanupPeriodDays: { default: 30, userOnly: true, description: 'Days a conversation is kept after it was last used (then deleted with its traces, as in Claude Code; at least 1)' },
|
|
36
39
|
};
|
|
37
40
|
|
|
38
41
|
// Advanced keys, shown only by /config advanced (or config list --advanced). Settings files may also carry
|
|
@@ -61,6 +64,11 @@ export const KNOWN_KEYS = {
|
|
|
61
64
|
};
|
|
62
65
|
|
|
63
66
|
function basicValue(key, value) {
|
|
67
|
+
if (key === 'cleanupPeriodDays') {
|
|
68
|
+
const days = typeof value === 'number' ? value : /^\s*\d+\s*$/.test(String(value)) ? Number(value) : NaN;
|
|
69
|
+
if (Number.isInteger(days) && days >= 1) return days;
|
|
70
|
+
throw new Error(`Invalid ${key}: ${value}. A whole number of days, at least 1 (e.g. 3650 to keep conversations for years).`);
|
|
71
|
+
}
|
|
64
72
|
if (typeof value !== 'string') throw new Error(`${key} must be a string.`);
|
|
65
73
|
const text = value.trim();
|
|
66
74
|
if (key === 'model') {
|
|
@@ -92,6 +100,7 @@ export function writeConfigSetting(file, key, value) {
|
|
|
92
100
|
key = configKey(key);
|
|
93
101
|
const basic = BASIC_SETTINGS[key];
|
|
94
102
|
const normalized = basic ? basicValue(key, value) : String(value);
|
|
103
|
+
if (basic?.userOnly && path.resolve(file) !== path.resolve(userSettingsFile())) throw new Error(`${key} is read from ${userSettingsFile()} only.`);
|
|
95
104
|
updateSettingsFile(file, (json) => {
|
|
96
105
|
if (basic) {
|
|
97
106
|
json[key] = normalized;
|
|
@@ -153,8 +162,9 @@ export function loadConfig({ cwd = process.cwd(), flags = {} } = {}) {
|
|
|
153
162
|
if (!json) continue;
|
|
154
163
|
set(json.env, file);
|
|
155
164
|
for (const [key, spec] of Object.entries(BASIC_SETTINGS)) {
|
|
165
|
+
if (spec.userOnly && scope !== 'user') continue;
|
|
156
166
|
// A top-level field wins over its legacy spelling in the same file; later files win over earlier ones.
|
|
157
|
-
const value = json[key] ?? json.env?.[spec.legacy];
|
|
167
|
+
const value = json[key] ?? (spec.legacy ? json.env?.[spec.legacy] : undefined);
|
|
158
168
|
if (value == null) continue;
|
|
159
169
|
try { settings[key] = basicValue(key, value); sources[key] = file; } catch { /* invalid: use the earlier value or default */ }
|
|
160
170
|
}
|
package/src/runtime.js
CHANGED
|
@@ -13,7 +13,7 @@ import { isAbort } from './api.js';
|
|
|
13
13
|
import { McpManager } from './mcp.js';
|
|
14
14
|
import { HookRunner } from './hooks.js';
|
|
15
15
|
import { BackgroundTasks, taskNotification } from './tasks.js';
|
|
16
|
-
import { autoMemoryDir,
|
|
16
|
+
import { autoMemoryDir, sweepOldData, projectDir } from './session.js';
|
|
17
17
|
import { loadAutoMemoryIndex, takeEnvSnapshot, takeEnvSnapshotAsync, localDate } from './context.js';
|
|
18
18
|
import { canRestart } from './restart.js';
|
|
19
19
|
import { RuntimeTrace } from './trace.js';
|
|
@@ -24,9 +24,15 @@ export async function createRuntime({ cwd, flags = {}, io, sessionId = '' }) {
|
|
|
24
24
|
const trace = new RuntimeTrace({ cwd, sessionId, enabled: config.traceEnabled });
|
|
25
25
|
applyRememberedChoices(config, flags); // what /model and /effort chose last time
|
|
26
26
|
if (flags.verify) config.verifyOverride = flags.verify;
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
// Old conversations and what goes with them, in the background a while after the start (not in the self-check's
|
|
28
|
+
// throwaway process, nor a test's: CLAUDE_PRO_CONFIG_DIR points elsewhere then anyway)
|
|
29
|
+
if (process.env.CLAUDE_PRO_SELF_CHECK !== '1') {
|
|
30
|
+
setTimeout(() => {
|
|
31
|
+
sweepOldData({ days: config.setting('cleanupPeriodDays'), keep: [sessionId, config.sessionId] })
|
|
32
|
+
.then((done) => { if (done.files) trace.append('cleanup', { conversations: done.conversations, files: done.files, bytes: done.bytes }); })
|
|
33
|
+
.catch(() => {});
|
|
34
|
+
}, 15_000).unref();
|
|
35
|
+
}
|
|
30
36
|
pruneStaleShellFiles();
|
|
31
37
|
// Full access: nothing is ever asked.
|
|
32
38
|
const checkpoints = new CheckpointStore(path.join(projectDir(cwd), 'checkpoints', `${Date.now()}-${crypto.randomBytes(3).toString('hex')}`));
|
package/src/session.js
CHANGED
|
@@ -88,46 +88,59 @@ export function toolResultsDir(cwd) {
|
|
|
88
88
|
return path.join(projectDir(cwd), 'tool-results');
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
// Delete saved tool output older than maxAgeMs (best effort, run at startup).
|
|
92
|
-
export function pruneToolResults(cwd, maxAgeMs = 7 * 24 * 3600_000) {
|
|
93
|
-
const dir = toolResultsDir(cwd);
|
|
94
|
-
let entries = [];
|
|
95
|
-
try { entries = fs.readdirSync(dir); } catch { return; }
|
|
96
|
-
const cutoff = Date.now() - maxAgeMs;
|
|
97
|
-
for (const name of entries) {
|
|
98
|
-
const file = path.join(dir, name);
|
|
99
|
-
try { if (fs.statSync(file).mtimeMs < cutoff) fs.rmSync(file, { force: true }); } catch { /* ignore */ }
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// Delete the traces (see trace.js) of conversations not traced for maxAgeMs: one file a conversation, up to 40 MB
|
|
104
|
-
// with its rotation, kept for good before (best effort, run at startup).
|
|
105
|
-
export function pruneTraces(cwd, maxAgeMs = 30 * 24 * 3600_000) {
|
|
106
|
-
const dir = path.join(projectDir(cwd), 'traces');
|
|
107
|
-
let entries = [];
|
|
108
|
-
try { entries = fs.readdirSync(dir); } catch { return; }
|
|
109
|
-
const cutoff = Date.now() - maxAgeMs;
|
|
110
|
-
for (const name of entries) {
|
|
111
|
-
const file = path.join(dir, name);
|
|
112
|
-
try { if (fs.statSync(file).mtimeMs < cutoff) fs.rmSync(file, { force: true }); } catch { /* ignore */ }
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
91
|
// Where /rewind keeps file snapshots: one sub-directory per run of the program.
|
|
117
92
|
export function checkpointsDir(cwd) {
|
|
118
93
|
return path.join(projectDir(cwd), 'checkpoints');
|
|
119
94
|
}
|
|
120
95
|
|
|
121
|
-
// Delete
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
96
|
+
// Delete what is older than `days` (the cleanupPeriodDays setting, as in Claude Code: 30 by default), in every
|
|
97
|
+
// project: conversations not written to since (they no longer appear in /resume), their traces, saved tool outputs
|
|
98
|
+
// (at most 7 days) and /rewind snapshots (at most 14 days). The memory is never touched. Conversations were kept
|
|
99
|
+
// for good before: 646 MB in 176 files in a month (2026-11-11), of which only the current project's tool outputs,
|
|
100
|
+
// 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() } = {}) {
|
|
103
|
+
const done = { conversations: 0, files: 0, bytes: 0 };
|
|
104
|
+
if (!(days >= 1)) return done;
|
|
105
|
+
const marker = path.join(root, '.last-sweep');
|
|
106
|
+
try { if (now - fs.statSync(marker).mtimeMs < 3600_000) return done; } catch { /* never swept */ }
|
|
107
|
+
try { fs.mkdirSync(root, { recursive: true }); fs.writeFileSync(marker, ''); } catch { return done; }
|
|
108
|
+
const day = 24 * 3600_000;
|
|
109
|
+
const keepIds = new Set(keep.filter(Boolean));
|
|
110
|
+
const fsp = fs.promises;
|
|
111
|
+
const list = async (dir) => { try { return await fsp.readdir(dir, { withFileTypes: true }); } catch { return []; } };
|
|
112
|
+
const old = async (file, maxAgeMs) => { try { return now - (await fsp.stat(file)).mtimeMs > maxAgeMs; } catch { return false; } };
|
|
113
|
+
const remove = async (file, isDir = false) => {
|
|
114
|
+
try {
|
|
115
|
+
const size = isDir ? 0 : (await fsp.stat(file)).size;
|
|
116
|
+
await fsp.rm(file, { recursive: isDir, force: true });
|
|
117
|
+
done.files++;
|
|
118
|
+
done.bytes += size;
|
|
119
|
+
return true;
|
|
120
|
+
} catch { return false; }
|
|
121
|
+
};
|
|
122
|
+
for (const project of await list(root)) {
|
|
123
|
+
if (!project.isDirectory()) continue;
|
|
124
|
+
const dir = path.join(root, project.name);
|
|
125
|
+
for (const e of await list(dir)) {
|
|
126
|
+
const id = e.name.replace(/\.jsonl$/, '');
|
|
127
|
+
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++;
|
|
129
|
+
}
|
|
130
|
+
for (const e of await list(path.join(dir, 'traces'))) { // a conversation's trace is written with it
|
|
131
|
+
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);
|
|
133
|
+
}
|
|
134
|
+
for (const e of await list(path.join(dir, 'tool-results'))) {
|
|
135
|
+
const f = path.join(dir, 'tool-results', e.name);
|
|
136
|
+
if (await old(f, Math.min(days, 7) * day)) await remove(f);
|
|
137
|
+
}
|
|
138
|
+
for (const e of await list(path.join(dir, 'checkpoints'))) { // one directory per run of the program
|
|
139
|
+
const f = path.join(dir, 'checkpoints', e.name);
|
|
140
|
+
if (await old(f, Math.min(days, 14) * day)) await remove(f, true);
|
|
141
|
+
}
|
|
130
142
|
}
|
|
143
|
+
return done;
|
|
131
144
|
}
|
|
132
145
|
|
|
133
146
|
// Persistent, model-maintained memory for this project (MEMORY.md + topic files).
|
package/src/ui/ansi.js
CHANGED
|
@@ -96,11 +96,69 @@ function inRanges(cp, ranges) {
|
|
|
96
96
|
return false;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
// East Asian Ambiguous characters (UAX #11: the Basic Multilingual Plane, without combining marks and the private
|
|
100
|
+
// use area). A terminal gives them one cell or two depending on its font and settings: the Windows console with a
|
|
101
|
+
// Chinese, Japanese or Korean font draws those its font has full-width glyphs for (“ ” — … · × ° ① → ■ α Я) in
|
|
102
|
+
// two cells and the others (é, box drawing) in one, whatever the code page. So their widths are measured where
|
|
103
|
+
// that matters (see queryCursorRow in screen.js), not looked up. (Ranges end where a block does: neighbours in a
|
|
104
|
+
// block mostly have the same width, which is what measuring them together relies on.)
|
|
105
|
+
const AMBIGUOUS = [
|
|
106
|
+
[0xa1, 0xa1], [0xa4, 0xa4], [0xa7, 0xa8], [0xaa, 0xaa], [0xae, 0xae], [0xb0, 0xb4], [0xb6, 0xba], [0xbc, 0xbf],
|
|
107
|
+
[0xc6, 0xc6], [0xd0, 0xd0], [0xd7, 0xd8], [0xde, 0xe1], [0xe6, 0xe6], [0xe8, 0xea], [0xec, 0xed], [0xf0, 0xf0],
|
|
108
|
+
[0xf2, 0xf3], [0xf7, 0xfa], [0xfc, 0xfc], [0xfe, 0xfe], [0x101, 0x101], [0x111, 0x111], [0x113, 0x113],
|
|
109
|
+
[0x11b, 0x11b], [0x126, 0x127], [0x12b, 0x12b], [0x131, 0x133], [0x138, 0x138], [0x13f, 0x142], [0x144, 0x144],
|
|
110
|
+
[0x148, 0x14b], [0x14d, 0x14d], [0x152, 0x153], [0x166, 0x167], [0x16b, 0x16b], [0x1ce, 0x1ce], [0x1d0, 0x1d0],
|
|
111
|
+
[0x1d2, 0x1d2], [0x1d4, 0x1d4], [0x1d6, 0x1d6], [0x1d8, 0x1d8], [0x1da, 0x1da], [0x1dc, 0x1dc], [0x251, 0x251],
|
|
112
|
+
[0x261, 0x261], [0x2c4, 0x2c4], [0x2c7, 0x2c7], [0x2c9, 0x2cb], [0x2cd, 0x2cd], [0x2d0, 0x2d0], [0x2d8, 0x2db],
|
|
113
|
+
[0x2dd, 0x2dd], [0x2df, 0x2df], [0x391, 0x3a1], [0x3a3, 0x3a9], [0x3b1, 0x3c1], [0x3c3, 0x3c9], [0x401, 0x401],
|
|
114
|
+
[0x410, 0x44f], [0x451, 0x451], [0x2010, 0x2010], [0x2013, 0x2016], [0x2018, 0x2019], [0x201c, 0x201d],
|
|
115
|
+
[0x2020, 0x2022], [0x2024, 0x2027], [0x2030, 0x2030], [0x2032, 0x2033], [0x2035, 0x2035], [0x203b, 0x203b],
|
|
116
|
+
[0x203e, 0x203e], [0x2074, 0x2074], [0x207f, 0x207f], [0x2081, 0x2084], [0x20ac, 0x20ac], [0x2103, 0x2103],
|
|
117
|
+
[0x2105, 0x2105], [0x2109, 0x2109], [0x2113, 0x2113], [0x2116, 0x2116], [0x2121, 0x2122], [0x2126, 0x2126],
|
|
118
|
+
[0x212b, 0x212b], [0x2153, 0x2154], [0x215b, 0x215e], [0x2160, 0x216b], [0x2170, 0x2179], [0x2189, 0x2189],
|
|
119
|
+
[0x2190, 0x2199], [0x21b8, 0x21b9], [0x21d2, 0x21d2], [0x21d4, 0x21d4], [0x21e7, 0x21e7], [0x2200, 0x2200], [0x2202, 0x2203],
|
|
120
|
+
[0x2207, 0x2208], [0x220b, 0x220b], [0x220f, 0x220f], [0x2211, 0x2211], [0x2215, 0x2215], [0x221a, 0x221a],
|
|
121
|
+
[0x221d, 0x2220], [0x2223, 0x2223], [0x2225, 0x2225], [0x2227, 0x222c], [0x222e, 0x222e], [0x2234, 0x2237],
|
|
122
|
+
[0x223c, 0x223d], [0x2248, 0x2248], [0x224c, 0x224c], [0x2252, 0x2252], [0x2260, 0x2261], [0x2264, 0x2267],
|
|
123
|
+
[0x226a, 0x226b], [0x226e, 0x226f], [0x2282, 0x2283], [0x2286, 0x2287], [0x2295, 0x2295], [0x2299, 0x2299],
|
|
124
|
+
[0x22a5, 0x22a5], [0x22bf, 0x22bf], [0x2312, 0x2312], [0x2460, 0x24e9], [0x24eb, 0x24ff], [0x2500, 0x254b],
|
|
125
|
+
[0x2550, 0x2573], [0x2580, 0x258f], [0x2592, 0x2595], [0x25a0, 0x25a1], [0x25a3, 0x25a9], [0x25b2, 0x25b3], [0x25b6, 0x25b7],
|
|
126
|
+
[0x25bc, 0x25bd], [0x25c0, 0x25c1], [0x25c6, 0x25c8], [0x25cb, 0x25cb], [0x25ce, 0x25d1], [0x25e2, 0x25e5],
|
|
127
|
+
[0x25ef, 0x25ef], [0x2605, 0x2606], [0x2609, 0x2609], [0x260e, 0x260f], [0x261c, 0x261c], [0x261e, 0x261e],
|
|
128
|
+
[0x2640, 0x2640], [0x2642, 0x2642], [0x2660, 0x2661], [0x2663, 0x2665], [0x2667, 0x266a], [0x266c, 0x266d],
|
|
129
|
+
[0x266f, 0x266f], [0x269e, 0x269f], [0x26bf, 0x26bf], [0x26c6, 0x26cd], [0x26cf, 0x26d3], [0x26d5, 0x26e1],
|
|
130
|
+
[0x26e3, 0x26e3], [0x26e8, 0x26e9], [0x26eb, 0x26f1], [0x26f4, 0x26f4], [0x26f6, 0x26f9], [0x26fb, 0x26fc],
|
|
131
|
+
[0x26fe, 0x26ff], [0x273d, 0x273d], [0x2776, 0x277f], [0x2b56, 0x2b59], [0x3248, 0x324f], [0xfffd, 0xfffd],
|
|
132
|
+
];
|
|
133
|
+
|
|
134
|
+
// Those characters as strings of neighbours: each range, in pieces of at most `max` characters.
|
|
135
|
+
export function ambiguousGroups(max) {
|
|
136
|
+
const groups = [];
|
|
137
|
+
for (const [from, to] of AMBIGUOUS) {
|
|
138
|
+
for (let cp = from; cp <= to; cp += max) {
|
|
139
|
+
let text = '';
|
|
140
|
+
for (let k = cp; k <= Math.min(to, cp + max - 1); k++) text += String.fromCodePoint(k);
|
|
141
|
+
groups.push(text);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return groups;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// The widths this terminal was measured to give characters (see queryCursorRow): [[character, cells], ...]. They
|
|
148
|
+
// come before the tables above, which is what makes the program's layout and the terminal's agree where the
|
|
149
|
+
// terminal draws a symbol such as ·, … or “ in two cells.
|
|
150
|
+
const terminalWidths = new Map();
|
|
151
|
+
export function setTerminalWidths(widths) {
|
|
152
|
+
terminalWidths.clear();
|
|
153
|
+
for (const [char, width] of widths) {
|
|
154
|
+
if (width === 1 || width === 2) terminalWidths.set(char.codePointAt(0), width);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
99
158
|
export function codePointWidth(cp) {
|
|
100
159
|
if (cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0;
|
|
101
160
|
if (inRanges(cp, ZERO)) return 0;
|
|
102
|
-
|
|
103
|
-
return 1;
|
|
161
|
+
return terminalWidths.get(cp) ?? (inRanges(cp, WIDE) ? 2 : 1);
|
|
104
162
|
}
|
|
105
163
|
|
|
106
164
|
const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|
package/src/ui/repl.js
CHANGED
|
@@ -2418,7 +2418,8 @@ export class App {
|
|
|
2418
2418
|
// ---------------------------------------------------------------- live region
|
|
2419
2419
|
|
|
2420
2420
|
spinnerLine() {
|
|
2421
|
-
|
|
2421
|
+
// (as wide as the widest frame: where the terminal draws some of them in two cells, the text behind moved back and forth)
|
|
2422
|
+
const frame = padEnd(SPINNER[Math.floor(Date.now() / 120) % SPINNER.length], Math.max(...SPINNER.map(stringWidth)));
|
|
2422
2423
|
if (this.rateWait) {
|
|
2423
2424
|
const w = this.rateWait;
|
|
2424
2425
|
const left = humanDuration(w.resumeAt - Date.now()); // the same wording as the notice above it
|
package/src/ui/screen.js
CHANGED
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
// of a restart) goes on right below the output.
|
|
30
30
|
|
|
31
31
|
import { PassThrough } from 'node:stream';
|
|
32
|
-
import { ESC, wrapLine, termWidth, truncate, stringWidth, stripAnsi, graphemes, graphemeWidth } from './ansi.js';
|
|
32
|
+
import { ESC, wrapLine, termWidth, truncate, stringWidth, stripAnsi, graphemes, graphemeWidth, setTerminalWidths, ambiguousGroups } from './ansi.js';
|
|
33
33
|
|
|
34
34
|
const SYNC_START = '\x1b[?2026h';
|
|
35
35
|
const SYNC_END = '\x1b[?2026l';
|
|
@@ -136,32 +136,91 @@ export function mouseFilter(stdin, onMouse) {
|
|
|
136
136
|
});
|
|
137
137
|
return out;
|
|
138
138
|
}
|
|
139
|
-
const CPR = /\x1b\[(\d+);(\d+)R
|
|
139
|
+
const CPR = /\x1b\[(\d+);(\d+)R/g; // the terminal's answer to DSR 6: row;column
|
|
140
|
+
// Windows: the symbols the interface is drawn with are measured at start-up (see queryCursorRow), as its terminals
|
|
141
|
+
// do not agree on their widths. The first FONT_SIZED of them are East Asian Ambiguous characters: a terminal that
|
|
142
|
+
// draws one of those in two cells sizes all such characters by its font, and is asked about all of them.
|
|
143
|
+
const UI_PROBES = process.platform === 'win32' ? Array.from('·…↑↓←→↻⇣⏎◷⇄•◦⏺⎿✻✢✳✶✽✉⚠') : [];
|
|
144
|
+
const FONT_SIZED = 6;
|
|
145
|
+
const AMBIGUOUS_TIMEOUT_MS = 1500; // some 200 to 400 answers: 0.2 ms each in the Windows 11 console, 0.5 on a server
|
|
140
146
|
|
|
141
147
|
// Ask the terminal where the cursor is (DSR 6): resolves with its row (1-based), or null when it does not answer
|
|
142
148
|
// within `timeout`. Run before anything else reads `stdin`, with the terminal in raw mode; what else arrives
|
|
143
|
-
// meanwhile (keys typed during start-up) is put back for the key reader.
|
|
149
|
+
// meanwhile (keys typed during start-up) is put back for the key reader, byte for byte.
|
|
150
|
+
//
|
|
151
|
+
// On Windows the widths of characters are measured too (setTerminalWidths): each one is written at the start of the
|
|
152
|
+
// cursor's row and the cursor's column asked for, and the row is erased afterwards. The interface's own symbols
|
|
153
|
+
// first; then, only where the terminal sizes ambiguous characters by its font (the console with a Chinese font: ·
|
|
154
|
+
// … “ ” — × ① in two cells), all of those: text with them in it was wrapped and padded as if they took one cell,
|
|
155
|
+
// which broke rows in two and left the footer on screen twice. Those are some 800 characters, so neighbours are
|
|
156
|
+
// written together first: one answer does for all of them when they are all one cell wide or all two, which most
|
|
157
|
+
// are, and only the others are then asked about one by one. A batch that is not answered whole in time is not used.
|
|
144
158
|
export function queryCursorRow(stdin, out, timeout = 300) {
|
|
145
159
|
return new Promise((resolve) => {
|
|
146
160
|
let buf = Buffer.alloc(0);
|
|
147
|
-
let timer = null;
|
|
148
|
-
const
|
|
161
|
+
let timer = null, finished = false, batch = 0;
|
|
162
|
+
const sent = []; // what was written to be measured (a character, or neighbours), in the order of the answers
|
|
163
|
+
let answered = 0; // how many of them have an answer: counted when a whole batch is in
|
|
164
|
+
const replies = () => [...buf.toString('latin1').matchAll(CPR)];
|
|
165
|
+
const cells = (matches, i) => Number(matches[1 + i][2]) - 1;
|
|
166
|
+
// The width of each character of `text`, which took `n` cells: 0 when they are not all one or all two cells wide.
|
|
167
|
+
const uniform = (text, n) => (n === text.length ? 1 : n === 2 * text.length ? 2 : 0);
|
|
168
|
+
// What to measure next, decided by the answers so far.
|
|
169
|
+
const next = (matches) => {
|
|
170
|
+
batch++;
|
|
171
|
+
if (batch === 1) return UI_PROBES.length && !(out.columns && out.columns < 3) ? UI_PROBES : [];
|
|
172
|
+
if (batch === 2) {
|
|
173
|
+
if (!UI_PROBES.slice(0, FONT_SIZED).some((_, i) => cells(matches, i) === 2)) return [];
|
|
174
|
+
return ambiguousGroups(Math.max(1, Math.min(40, Math.floor(((out.columns || 80) - 2) / 2)))); // a piece fits the row at two cells each
|
|
175
|
+
}
|
|
176
|
+
if (batch === 3) return sent.flatMap((text, i) => (text.length > 1 && !uniform(text, cells(matches, i)) ? [...text] : []));
|
|
177
|
+
return [];
|
|
178
|
+
};
|
|
179
|
+
const done = () => {
|
|
180
|
+
if (finished) return;
|
|
181
|
+
finished = true;
|
|
149
182
|
clearTimeout(timer);
|
|
150
183
|
stdin.off('data', onData);
|
|
151
184
|
stdin.pause();
|
|
152
|
-
const
|
|
153
|
-
const
|
|
185
|
+
const matches = replies();
|
|
186
|
+
const first = matches[0];
|
|
187
|
+
if (sent.length) {
|
|
188
|
+
const answers = matches.slice(1, 1 + answered);
|
|
189
|
+
// (an answer from another row: the screen moved meanwhile, and nothing that was measured is trusted)
|
|
190
|
+
if (answers.every((m) => m[1] === first[1])) {
|
|
191
|
+
const widths = [];
|
|
192
|
+
answers.forEach((m, i) => {
|
|
193
|
+
const width = uniform(sent[i], Number(m[2]) - 1);
|
|
194
|
+
if (width) for (const char of sent[i]) widths.push([char, width]);
|
|
195
|
+
});
|
|
196
|
+
setTerminalWidths(widths);
|
|
197
|
+
}
|
|
198
|
+
try { out.write('\r' + ESC.right(Number(first[2]) - 1) + ESC.showCursor + SYNC_END); } catch { /* the terminal is gone */ }
|
|
199
|
+
}
|
|
200
|
+
// latin1 keeps a one-to-one mapping of bytes, including keys/pastes split in the middle of a UTF-8 character.
|
|
201
|
+
const rest = Buffer.from(buf.toString('latin1').replace(CPR, ''), 'latin1');
|
|
154
202
|
if (rest.length) stdin.unshift(rest);
|
|
155
|
-
resolve(
|
|
203
|
+
resolve(first ? Number(first[1]) : null);
|
|
204
|
+
};
|
|
205
|
+
const measure = (texts, ms) => {
|
|
206
|
+
const start = sent.length ? '' : SYNC_START + ESC.hideCursor;
|
|
207
|
+
sent.push(...texts);
|
|
208
|
+
clearTimeout(timer);
|
|
209
|
+
timer = setTimeout(done, ms);
|
|
210
|
+
try { out.write(start + texts.map((text) => '\r' + text + '\x1b[6n').join('') + '\r\x1b[K'); } catch { done(); }
|
|
156
211
|
};
|
|
157
212
|
const onData = (d) => {
|
|
158
213
|
buf = Buffer.concat([buf, Buffer.isBuffer(d) ? d : Buffer.from(String(d), 'utf8')]);
|
|
159
|
-
const
|
|
160
|
-
if (
|
|
214
|
+
const matches = replies();
|
|
215
|
+
if (matches.length < 1 + sent.length) return; // the first answer is the cursor's position
|
|
216
|
+
answered = sent.length;
|
|
217
|
+
const more = next(matches);
|
|
218
|
+
if (more.length) measure(more, batch === 1 ? timeout : AMBIGUOUS_TIMEOUT_MS);
|
|
219
|
+
else done();
|
|
161
220
|
};
|
|
162
|
-
timer = setTimeout(
|
|
221
|
+
timer = setTimeout(done, timeout);
|
|
163
222
|
stdin.on('data', onData);
|
|
164
|
-
try { out.write('\x1b[6n'); } catch { done(
|
|
223
|
+
try { out.write('\x1b[6n'); } catch { done(); }
|
|
165
224
|
});
|
|
166
225
|
}
|
|
167
226
|
|
|
@@ -186,6 +245,7 @@ export class Screen {
|
|
|
186
245
|
// pin: keep the live region on the last rows of the screen (see the top of this file).
|
|
187
246
|
constructor(out = process.stdout, { pin = true } = {}) {
|
|
188
247
|
this.out = out;
|
|
248
|
+
this.dimensions = this.readSize();
|
|
189
249
|
this.pin = pin;
|
|
190
250
|
this.pinned = null; // rows from the top of the live region to the bottom of the screen; null: not known
|
|
191
251
|
this.full = false; // fullscreen: see the top of this file
|
|
@@ -220,6 +280,12 @@ export class Screen {
|
|
|
220
280
|
this.titleInherited = false; // the process before this one in the session already saved the shell's title
|
|
221
281
|
this.exitTitle = '';
|
|
222
282
|
out.on('resize', () => this.onResize());
|
|
283
|
+
// RDP display changes can leave Node's columns/rows cache behind. Check the native size even while idle;
|
|
284
|
+
// finding a change takes the same debounced full-repaint path as a normal resize event.
|
|
285
|
+
if (process.platform === 'win32' && out.isTTY && out._handle?.getWindowSize) {
|
|
286
|
+
this.sizeTimer = setInterval(() => this.checkSize(), 250);
|
|
287
|
+
this.sizeTimer.unref();
|
|
288
|
+
}
|
|
223
289
|
}
|
|
224
290
|
|
|
225
291
|
// Keep the terminal's title (the label of its tab or window) following `provider()`. `exitTitle` is what
|
|
@@ -242,8 +308,28 @@ export class Screen {
|
|
|
242
308
|
return (first ? TITLE_PUSH : '') + `\x1b]0;${text}\x07`;
|
|
243
309
|
}
|
|
244
310
|
|
|
245
|
-
|
|
246
|
-
|
|
311
|
+
readSize() {
|
|
312
|
+
const fallback = [this.out.columns || this.dimensions?.[0] || termWidth(), this.out.rows || this.dimensions?.[1] || 30];
|
|
313
|
+
if (process.platform === 'win32' && this.out.isTTY && this.out._handle?.getWindowSize) {
|
|
314
|
+
try {
|
|
315
|
+
const size = [0, 0];
|
|
316
|
+
if (!this.out._handle.getWindowSize(size) && size.every((n) => Number.isInteger(n) && n > 0)) return size;
|
|
317
|
+
} catch { /* closed or unsupported handle: keep the last valid size */ }
|
|
318
|
+
return this.dimensions || fallback;
|
|
319
|
+
}
|
|
320
|
+
return fallback;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
checkSize() {
|
|
324
|
+
if (this.closed) return false;
|
|
325
|
+
const size = this.readSize();
|
|
326
|
+
if (size[0] === this.dimensions[0] && size[1] === this.dimensions[1]) return false;
|
|
327
|
+
this.onResize(size);
|
|
328
|
+
return true;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
get width() { return Math.max(20, this.dimensions[0]); }
|
|
332
|
+
get height() { return Math.max(10, this.dimensions[1]); }
|
|
247
333
|
// True from a size change until the repaint that follows it.
|
|
248
334
|
get resizing() { return this.resizeTimer !== null; }
|
|
249
335
|
|
|
@@ -707,9 +793,10 @@ export class Screen {
|
|
|
707
793
|
// Draw the screen: the conversation above, the live region on the last rows, the cursor in the input box.
|
|
708
794
|
draw({ full = false } = {}) {
|
|
709
795
|
if (this.closed || !this.full) return;
|
|
796
|
+
if (this.checkSize() || this.resizing) return;
|
|
710
797
|
if (this.scheduled) { clearTimeout(this.scheduled); this.scheduled = null; }
|
|
711
798
|
const cols = this.width;
|
|
712
|
-
const screenRows = Math.max(1, this.
|
|
799
|
+
const screenRows = Math.max(1, this.dimensions[1]);
|
|
713
800
|
if (!this.scroll) this.scrollLiveRows = null;
|
|
714
801
|
else if (full) this.scrollLiveRows = null; // a resize changes wrapping; capture the new live layout below
|
|
715
802
|
let layout = this.layoutLive(cols);
|
|
@@ -841,7 +928,7 @@ export class Screen {
|
|
|
841
928
|
const end = input ? starts[input.row + input.rows] : undefined;
|
|
842
929
|
const box = end !== undefined && end - starts[input.row] === input.rows ? { top: starts[input.row], rows: input.rows, col: input.col } : null;
|
|
843
930
|
// Cap to the terminal height so there is always a way back to the top.
|
|
844
|
-
const maxRows = Math.max(1,
|
|
931
|
+
const maxRows = Math.max(1, this.dimensions[1] - 1);
|
|
845
932
|
if (rows.length > maxRows) {
|
|
846
933
|
const dropped = rows.length - maxRows;
|
|
847
934
|
rows.splice(0, dropped);
|
|
@@ -864,8 +951,9 @@ export class Screen {
|
|
|
864
951
|
return buf;
|
|
865
952
|
}
|
|
866
953
|
|
|
867
|
-
onResize() {
|
|
954
|
+
onResize(size = this.readSize()) {
|
|
868
955
|
if (this.closed) return;
|
|
956
|
+
this.dimensions = size;
|
|
869
957
|
const now = Date.now();
|
|
870
958
|
if (!this.resizeSince) this.resizeSince = now;
|
|
871
959
|
clearTimeout(this.resizeTimer);
|
|
@@ -876,7 +964,7 @@ export class Screen {
|
|
|
876
964
|
settleResize() {
|
|
877
965
|
this.resizeTimer = null;
|
|
878
966
|
this.resizeSince = 0;
|
|
879
|
-
this.repaint();
|
|
967
|
+
if (!this.checkSize()) this.repaint();
|
|
880
968
|
}
|
|
881
969
|
|
|
882
970
|
// Write the whole viewport again after a resize: the newest static lines that fit, then the live region,
|
|
@@ -888,6 +976,7 @@ export class Screen {
|
|
|
888
976
|
// What was on screen above our output (a short session: the shell that started us) is overwritten.
|
|
889
977
|
repaint() {
|
|
890
978
|
if (this.closed) return;
|
|
979
|
+
this.dimensions = this.readSize();
|
|
891
980
|
if (this.full) {
|
|
892
981
|
clearTimeout(this.resizeTimer);
|
|
893
982
|
this.resizeTimer = null;
|
|
@@ -901,7 +990,7 @@ export class Screen {
|
|
|
901
990
|
this.resizeTimer = null;
|
|
902
991
|
this.resizeSince = 0;
|
|
903
992
|
const cols = this.width;
|
|
904
|
-
const screenRows = Math.max(1, this.
|
|
993
|
+
const screenRows = Math.max(1, this.dimensions[1]);
|
|
905
994
|
this.takeStatic();
|
|
906
995
|
const layout = this.layoutLive(cols);
|
|
907
996
|
const room = Math.max(0, screenRows - layout.rows.length);
|
|
@@ -933,7 +1022,7 @@ export class Screen {
|
|
|
933
1022
|
|
|
934
1023
|
flush() {
|
|
935
1024
|
if (this.closed) return;
|
|
936
|
-
if (this.resizing) return; // the repaint after the resize writes everything that is waiting
|
|
1025
|
+
if (this.checkSize() || this.resizing) return; // the repaint after the resize writes everything that is waiting
|
|
937
1026
|
if (this.full) { this.takeStatic(); this.draw(); return; }
|
|
938
1027
|
if (this.scheduled) { clearTimeout(this.scheduled); this.scheduled = null; }
|
|
939
1028
|
const cols = this.width;
|
|
@@ -1004,6 +1093,7 @@ export class Screen {
|
|
|
1004
1093
|
this.flush();
|
|
1005
1094
|
}
|
|
1006
1095
|
this.closed = true;
|
|
1096
|
+
clearInterval(this.sizeTimer);
|
|
1007
1097
|
clearTimeout(this.resizeTimer);
|
|
1008
1098
|
// Give the tab back its old label: a terminal with a title stack restores it, and one without is
|
|
1009
1099
|
// left with a neutral one rather than a title that still looks like a program that is running.
|