codexmate 0.1.32 → 0.1.33
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 +5 -0
- package/README.vi.md +5 -0
- package/README.zh.md +5 -0
- package/cli/claude-proxy.js +2 -2
- package/cli/prompt-history.js +2 -0
- package/cli.js +165 -213
- package/lib/cli-config-engine.js +6 -1
- package/lib/cli-file-utils.js +6 -1
- package/lib/config-change-fs.js +132 -0
- package/lib/config-changes.js +293 -0
- package/lib/handoff-mcp.js +18 -2
- package/lib/local-feature-store.js +39 -0
- package/lib/session-bookmarks.js +72 -0
- package/lib/session-context-health.js +23 -3
- package/lib/session-diagnostics.js +75 -0
- package/lib/session-feature-settings.js +21 -0
- package/lib/session-features.js +63 -0
- package/lib/session-handoff-draft.js +43 -0
- package/lib/session-projects.js +76 -0
- package/lib/session-search-index.js +188 -0
- package/lib/thread-handoff.js +8 -0
- package/lib/web-server.js +216 -0
- package/package.json +1 -1
- package/web-ui/app.js +7 -1
- package/web-ui/index.html +1 -0
- package/web-ui/logic.context-window.mjs +15 -0
- package/web-ui/modules/api.mjs +72 -39
- package/web-ui/modules/app.methods.agents.mjs +5 -0
- package/web-ui/modules/app.methods.claude-config.mjs +2 -0
- package/web-ui/modules/app.methods.codex-config.mjs +9 -0
- package/web-ui/modules/app.methods.config-changes.mjs +124 -0
- package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
- package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
- package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
- package/web-ui/modules/app.methods.pi-config.mjs +12 -3
- package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
- package/web-ui/modules/app.methods.providers.mjs +6 -0
- package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
- package/web-ui/modules/config-change-actions.mjs +9 -0
- package/web-ui/modules/i18n/locales/en.mjs +131 -4
- package/web-ui/modules/i18n/locales/ja.mjs +131 -4
- package/web-ui/modules/i18n/locales/vi.mjs +131 -4
- package/web-ui/modules/i18n/locales/zh-tw.mjs +131 -4
- package/web-ui/modules/i18n/locales/zh.mjs +131 -4
- package/web-ui/modules/request-deadline.mjs +33 -0
- package/web-ui/modules/session-features.mjs +279 -0
- package/web-ui/modules/thread-handoff.mjs +1 -1
- package/web-ui/partials/index/config-changes.html +25 -0
- package/web-ui/partials/index/context-window-reference.html +17 -0
- package/web-ui/partials/index/layout-header.html +7 -30
- package/web-ui/partials/index/modal-openclaw-config.html +0 -2
- package/web-ui/partials/index/modal-skills.html +0 -1
- package/web-ui/partials/index/modals-basic.html +0 -8
- package/web-ui/partials/index/modals-pi-provider.html +0 -1
- package/web-ui/partials/index/panel-config-codex.html +0 -3
- package/web-ui/partials/index/panel-config-openclaw.html +16 -13
- package/web-ui/partials/index/panel-dashboard.html +0 -2
- package/web-ui/partials/index/panel-plugins.html +0 -1
- package/web-ui/partials/index/panel-prompts.html +0 -1
- package/web-ui/partials/index/panel-sessions.html +9 -0
- package/web-ui/partials/index/panel-settings.html +1 -12
- package/web-ui/partials/index/panel-trash.html +0 -1
- package/web-ui/partials/index/session-diagnostics.html +29 -0
- package/web-ui/partials/index/session-features.html +107 -0
- package/web-ui/partials/index/thread-handoff.html +6 -3
- package/web-ui/res/web-ui-render.precompiled.js +1077 -135
- package/web-ui/styles/config-changes.css +30 -0
- package/web-ui/styles/openclaw-structured.css +205 -189
- package/web-ui/styles/session-features.css +148 -0
- package/web-ui/styles.css +3 -1
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const nativeFs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const { AsyncLocalStorage } = require('async_hooks');
|
|
7
|
+
|
|
8
|
+
const storage = new AsyncLocalStorage();
|
|
9
|
+
const hash = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex');
|
|
10
|
+
|
|
11
|
+
function snapshot(filePath, fs = nativeFs, options = {}) {
|
|
12
|
+
try {
|
|
13
|
+
const stat = options.allowSymlinks ? fs.statSync(filePath) : fs.lstatSync(filePath);
|
|
14
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`配置目标不是普通文件: ${filePath}`);
|
|
15
|
+
const buffer = fs.readFileSync(filePath);
|
|
16
|
+
return { exists: true, buffer, hash: hash(buffer), mode: stat.mode & 0o777 };
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error.code !== 'ENOENT') throw error;
|
|
19
|
+
return { exists: false, buffer: null, hash: '', mode: 0o600 };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function getEntry(store, filePath) {
|
|
24
|
+
const key = path.resolve(filePath);
|
|
25
|
+
if (!store.files.has(key)) {
|
|
26
|
+
if (nativeFs.existsSync(key) && nativeFs.statSync(key).size > store.maxFileBytes) throw new Error('配置文件超过预览容量');
|
|
27
|
+
const before = snapshot(key, nativeFs, { allowSymlinks: store.allowSymlinks });
|
|
28
|
+
store.files.set(key, { path: key, before, after: before.buffer, mode: before.mode, written: false });
|
|
29
|
+
}
|
|
30
|
+
return store.files.get(key);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function missing(filePath) {
|
|
34
|
+
const error = new Error(`ENOENT: ${filePath}`);
|
|
35
|
+
error.code = 'ENOENT';
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const stagedMethods = {
|
|
40
|
+
existsSync(store, filePath) {
|
|
41
|
+
const key = path.resolve(filePath);
|
|
42
|
+
if (store.directories.has(key)) return true;
|
|
43
|
+
if (nativeFs.existsSync(key) && nativeFs.statSync(key).isDirectory()) return true;
|
|
44
|
+
return getEntry(store, key).after !== null;
|
|
45
|
+
},
|
|
46
|
+
readFileSync(store, filePath, options) {
|
|
47
|
+
const entry = getEntry(store, filePath);
|
|
48
|
+
if (entry.after === null) return missing(filePath);
|
|
49
|
+
const encoding = typeof options === 'string' ? options : options && options.encoding;
|
|
50
|
+
return encoding ? entry.after.toString(encoding) : Buffer.from(entry.after);
|
|
51
|
+
},
|
|
52
|
+
writeFileSync(store, filePath, content, options) {
|
|
53
|
+
const entry = getEntry(store, filePath);
|
|
54
|
+
const encoding = typeof options === 'string' ? options : options && options.encoding;
|
|
55
|
+
const buffer = Buffer.isBuffer(content) ? Buffer.from(content) : Buffer.from(String(content), encoding || 'utf8');
|
|
56
|
+
if (buffer.length > store.maxFileBytes) throw new Error('配置文件超过预览容量');
|
|
57
|
+
entry.after = buffer;
|
|
58
|
+
if (!entry.before.exists && options && typeof options === 'object' && options.mode !== undefined) entry.mode = options.mode;
|
|
59
|
+
entry.written = true;
|
|
60
|
+
},
|
|
61
|
+
mkdirSync(store, filePath) {
|
|
62
|
+
let dir = path.resolve(filePath);
|
|
63
|
+
while (!nativeFs.existsSync(dir)) {
|
|
64
|
+
store.directories.add(dir);
|
|
65
|
+
const observed = store.files.get(dir);
|
|
66
|
+
if (observed && !observed.written && !observed.before.exists) store.files.delete(dir);
|
|
67
|
+
const parent = path.dirname(dir);
|
|
68
|
+
if (parent === dir) break;
|
|
69
|
+
dir = parent;
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
statSync(store, filePath) {
|
|
73
|
+
const key = path.resolve(filePath);
|
|
74
|
+
if (nativeFs.existsSync(key) && !store.files.has(key)) return nativeFs.statSync(key);
|
|
75
|
+
if (store.directories.has(key)) return { isDirectory: () => true, isFile: () => false, mode: 0o700 };
|
|
76
|
+
const entry = getEntry(store, key);
|
|
77
|
+
if (entry.after === null) return missing(filePath);
|
|
78
|
+
return { isFile: () => true, isDirectory: () => false, mode: entry.mode, size: entry.after.length, mtimeMs: Date.now() };
|
|
79
|
+
},
|
|
80
|
+
readdirSync(store, filePath, options) {
|
|
81
|
+
const key = path.resolve(filePath);
|
|
82
|
+
if (!nativeFs.existsSync(key) && !store.directories.has(key)) return missing(filePath);
|
|
83
|
+
if (options && options.withFileTypes) throw new Error('配置预览不支持目录对象读取');
|
|
84
|
+
const names = new Set(nativeFs.existsSync(key) ? nativeFs.readdirSync(key) : []);
|
|
85
|
+
for (const entry of store.files.values()) {
|
|
86
|
+
if (path.dirname(entry.path) !== key) continue;
|
|
87
|
+
if (entry.after === null) names.delete(path.basename(entry.path));
|
|
88
|
+
else names.add(path.basename(entry.path));
|
|
89
|
+
}
|
|
90
|
+
return [...names];
|
|
91
|
+
},
|
|
92
|
+
chmodSync(store, filePath, mode) {
|
|
93
|
+
const entry = getEntry(store, filePath);
|
|
94
|
+
// Existing user permissions are never broadened by a previewed write.
|
|
95
|
+
if (!entry.before.exists) entry.mode = mode;
|
|
96
|
+
},
|
|
97
|
+
unlinkSync(store, filePath) {
|
|
98
|
+
const entry = getEntry(store, filePath);
|
|
99
|
+
entry.after = null;
|
|
100
|
+
entry.written = true;
|
|
101
|
+
},
|
|
102
|
+
copyFileSync(store, source, target) {
|
|
103
|
+
stagedMethods.writeFileSync(store, target, stagedMethods.readFileSync(store, source));
|
|
104
|
+
},
|
|
105
|
+
renameSync(store, source, target) {
|
|
106
|
+
stagedMethods.copyFileSync(store, source, target);
|
|
107
|
+
stagedMethods.unlinkSync(store, source);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
const mutationPattern = /^(write|append|copy|rename|unlink|mkdir|rmdir|rm|chmod|chown|truncate|open|createWrite|symlink|link|utimes)/;
|
|
111
|
+
|
|
112
|
+
const fs = new Proxy(nativeFs, {
|
|
113
|
+
get(target, name) {
|
|
114
|
+
const original = target[name];
|
|
115
|
+
if (typeof original !== 'function') return original;
|
|
116
|
+
return (...args) => {
|
|
117
|
+
const store = storage.getStore();
|
|
118
|
+
if (!store) return original.apply(target, args);
|
|
119
|
+
if (stagedMethods[name]) return stagedMethods[name](store, ...args);
|
|
120
|
+
if (mutationPattern.test(name)) throw new Error(`配置预览不支持文件操作: ${name}`);
|
|
121
|
+
return original.apply(target, args);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
async function stageConfigWrites(callback, options = {}) {
|
|
127
|
+
const store = { files: new Map(), directories: new Set(), maxFileBytes: options.maxFileBytes === undefined ? 4 * 1024 * 1024 : options.maxFileBytes, allowSymlinks: options.allowSymlinks === true };
|
|
128
|
+
const result = await storage.run(store, callback);
|
|
129
|
+
return { result, files: [...store.files.values()] };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
module.exports = { fs, snapshot, hash, stageConfigWrites, isConfigStaging: () => !!storage.getStore() };
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const JSON5 = require('json5');
|
|
7
|
+
const toml = require('@iarna/toml');
|
|
8
|
+
const { snapshot, hash, stageConfigWrites } = require('./config-change-fs');
|
|
9
|
+
const { writeTextAtomicWithBackup } = require('./cli-config-engine');
|
|
10
|
+
const { buildLineDiff } = require('./text-diff');
|
|
11
|
+
|
|
12
|
+
const PREVIEW_TTL_MS = 5 * 60 * 1000;
|
|
13
|
+
const MAX_PREVIEWS = 20;
|
|
14
|
+
const MAX_PLAN_BYTES = 16 * 1024 * 1024;
|
|
15
|
+
const SECRET_KEY = /api.?key|auth.?token|authorization|password|passwd|secret|credential|bearer|cookie|session|private.?key|preferred_auth_method|(^|_)(access|refresh|id)[_-]?token$|^(key|token|access|refresh)$/i;
|
|
16
|
+
|
|
17
|
+
function parseConfig(buffer) {
|
|
18
|
+
const text = buffer ? buffer.toString('utf8').replace(/^\uFEFF/, '') : '';
|
|
19
|
+
if (!text.trim()) return {};
|
|
20
|
+
try { return JSON5.parse(text); } catch (_) { return toml.parse(text); }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function redactConfig(value, secrets) {
|
|
24
|
+
if (Array.isArray(value)) return value.map(item => redactConfig(item, secrets));
|
|
25
|
+
if (typeof value === 'string') {
|
|
26
|
+
if (/^(?:bearer\s+|sk[-_]|gsk_|AIza|xox[baprs]-|gh[pousr]_)/i.test(value)) { secrets.add(value); return '[REDACTED]'; }
|
|
27
|
+
if (/^https?:\/\//i.test(value)) {
|
|
28
|
+
const url = new URL(value);
|
|
29
|
+
if (url.username) url.username = '[REDACTED]';
|
|
30
|
+
if (url.password) url.password = '[REDACTED]';
|
|
31
|
+
for (const key of [...url.searchParams.keys()]) if (SECRET_KEY.test(key)) url.searchParams.set(key, '[REDACTED]');
|
|
32
|
+
return url.toString();
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
if (!value || typeof value !== 'object') return value;
|
|
37
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => {
|
|
38
|
+
if (SECRET_KEY.test(key)) {
|
|
39
|
+
const collect = (entry) => {
|
|
40
|
+
if (typeof entry === 'string' && entry) secrets.add(entry);
|
|
41
|
+
else if (entry && typeof entry === 'object') Object.values(entry).forEach(collect);
|
|
42
|
+
};
|
|
43
|
+
collect(item);
|
|
44
|
+
return [key, '[REDACTED]'];
|
|
45
|
+
}
|
|
46
|
+
return [key, redactConfig(item, secrets)];
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function buildPreviewFile(entry) {
|
|
51
|
+
const secrets = new Set();
|
|
52
|
+
let before;
|
|
53
|
+
let after;
|
|
54
|
+
let hidden = false;
|
|
55
|
+
try {
|
|
56
|
+
before = JSON.stringify(redactConfig(parseConfig(entry.before.buffer), secrets), null, 2);
|
|
57
|
+
after = JSON.stringify(redactConfig(parseConfig(entry.after), secrets), null, 2);
|
|
58
|
+
} catch (_) {
|
|
59
|
+
before = after = '[内容无法安全解析,已隐藏]';
|
|
60
|
+
hidden = true;
|
|
61
|
+
}
|
|
62
|
+
// Also remove a credential repeated in a URL, comment or a non-secret field.
|
|
63
|
+
for (const secret of [...secrets].sort((a, b) => b.length - a.length)) {
|
|
64
|
+
const escaped = JSON.stringify(secret).slice(1, -1);
|
|
65
|
+
before = before.split(escaped).join('[REDACTED]');
|
|
66
|
+
after = after.split(escaped).join('[REDACTED]');
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
path: entry.path,
|
|
70
|
+
operation: !entry.before.exists ? 'create' : (entry.after === null ? 'delete' : 'modify'),
|
|
71
|
+
hidden,
|
|
72
|
+
maskedOnly: before === after,
|
|
73
|
+
diff: buildLineDiff(before, after)
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function configChangeError(code, message, extra = {}) {
|
|
78
|
+
return { error: message, errorCode: code, ...extra };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function atomicBuffer(filePath, buffer, mode, fsImpl) {
|
|
82
|
+
fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
83
|
+
const temp = `${filePath}.tmp-config-change-${crypto.randomBytes(8).toString('hex')}`;
|
|
84
|
+
try {
|
|
85
|
+
fsImpl.writeFileSync(temp, buffer, { mode, flag: 'wx' });
|
|
86
|
+
fsImpl.chmodSync(temp, mode);
|
|
87
|
+
fsImpl.renameSync(temp, filePath);
|
|
88
|
+
if (hash(fsImpl.readFileSync(filePath)) !== hash(buffer)) throw new Error('写入校验失败');
|
|
89
|
+
} finally {
|
|
90
|
+
if (fsImpl.existsSync(temp)) fsImpl.unlinkSync(temp);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function createConfigChanges(options) {
|
|
95
|
+
const fsImpl = options.fs || fs;
|
|
96
|
+
const plans = new Map();
|
|
97
|
+
let busy = false;
|
|
98
|
+
const now = options.now || Date.now;
|
|
99
|
+
const journalPath = options.journalPath;
|
|
100
|
+
|
|
101
|
+
function readJournal() {
|
|
102
|
+
if (!fsImpl.existsSync(journalPath)) return {};
|
|
103
|
+
const data = JSON.parse(fsImpl.readFileSync(journalPath, 'utf8'));
|
|
104
|
+
if (!data || data.version !== 1 || !data.changes || typeof data.changes !== 'object') throw new Error('变更记录无效');
|
|
105
|
+
return data.changes;
|
|
106
|
+
}
|
|
107
|
+
function writeJournal(changes) {
|
|
108
|
+
atomicBuffer(journalPath, Buffer.from(JSON.stringify({ version: 1, changes }, null, 2) + '\n'), 0o600, fsImpl);
|
|
109
|
+
}
|
|
110
|
+
function publicChange(change) {
|
|
111
|
+
if (!change) return null;
|
|
112
|
+
return { id: change.id, target: change.target, action: change.action, createdAt: change.createdAt, files: change.files.map(item => ({ path: item.path })) };
|
|
113
|
+
}
|
|
114
|
+
function publicBaseline(entries) {
|
|
115
|
+
return entries.map(entry => {
|
|
116
|
+
const current = snapshot(entry.path, fsImpl);
|
|
117
|
+
return { path: entry.path, exists: current.exists, hash: current.hash, mode: current.mode };
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
function permission(target) {
|
|
121
|
+
return options.isAllowed(target) ? null : configChangeError('tool-config-write-disabled', '配置写入权限未开启', { target });
|
|
122
|
+
}
|
|
123
|
+
function checkFile(entry, expected) {
|
|
124
|
+
if (!options.isPathAllowed(entry.path)) throw new Error('配置路径超出允许范围');
|
|
125
|
+
const current = snapshot(entry.path, fsImpl);
|
|
126
|
+
if (current.exists !== expected.exists || current.hash !== expected.hash || (current.exists && current.mode !== expected.mode)) {
|
|
127
|
+
const error = new Error('配置已被外部修改,请刷新后重新预览');
|
|
128
|
+
error.code = 'config-change-conflict';
|
|
129
|
+
error.path = entry.path;
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function prunePlans() {
|
|
134
|
+
for (const [id, plan] of plans) if (plan.expiresAt <= now()) plans.delete(id);
|
|
135
|
+
while (plans.size >= MAX_PREVIEWS) plans.delete(plans.keys().next().value);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function preview(params = {}) {
|
|
139
|
+
if (busy) return configChangeError('config-change-busy', '已有配置变更正在执行');
|
|
140
|
+
const action = params.action;
|
|
141
|
+
const target = options.getTarget(action);
|
|
142
|
+
if (!target) return configChangeError('config-change-unsupported', '该操作不支持配置预览');
|
|
143
|
+
const denied = permission(target);
|
|
144
|
+
if (denied) return denied;
|
|
145
|
+
try {
|
|
146
|
+
const staged = await stageConfigWrites(() => options.execute(action, params.params || {}));
|
|
147
|
+
if (!staged.result || staged.result.error || staged.result.success === false) return configChangeError('config-change-invalid', '配置校验失败,请检查输入格式与必填字段');
|
|
148
|
+
for (const entry of staged.files) if (entry.written && !options.isPathAllowed(entry.path)) throw new Error('配置路径超出允许范围');
|
|
149
|
+
if (Array.isArray(params.baseline)) {
|
|
150
|
+
for (const entry of staged.files) {
|
|
151
|
+
const expected = params.baseline.find(item => item.path === entry.path);
|
|
152
|
+
if (expected) checkFile(entry, expected);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const bytes = staged.files.reduce((total, entry) => total + (entry.before.buffer ? entry.before.buffer.length : 0) + (entry.after ? entry.after.length : 0), 0);
|
|
156
|
+
if (bytes > MAX_PLAN_BYTES) return configChangeError('config-change-too-large', '配置变更超过预览容量');
|
|
157
|
+
const files = staged.files.filter(entry => entry.written && (entry.after === null ? entry.before.exists : (!entry.before.exists || hash(entry.after) !== entry.before.hash)));
|
|
158
|
+
const plan = { id: crypto.randomBytes(24).toString('hex'), action, target, files, reads: staged.files.filter(entry => options.isPathAllowed(entry.path)), result: staged.result, expiresAt: now() + PREVIEW_TTL_MS };
|
|
159
|
+
prunePlans();
|
|
160
|
+
plan.bytes = bytes;
|
|
161
|
+
while ([...plans.values()].reduce((total, item) => total + item.bytes, bytes) > MAX_PLAN_BYTES) plans.delete(plans.keys().next().value);
|
|
162
|
+
plans.set(plan.id, plan);
|
|
163
|
+
return { previewId: plan.id, target, action, expiresAt: plan.expiresAt, hasChanges: files.length > 0, files: files.map(buildPreviewFile) };
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (error.code === 'config-change-conflict') return configChangeError(error.code, error.message, { path: error.path });
|
|
166
|
+
return configChangeError('config-change-invalid', '无法预览配置,请检查文件与输入格式');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function restoreEntries(entries) {
|
|
171
|
+
const failed = [];
|
|
172
|
+
for (const entry of [...entries].reverse()) {
|
|
173
|
+
try {
|
|
174
|
+
// Never roll back a subsequent external edit.
|
|
175
|
+
checkFile(entry, entry.writtenState);
|
|
176
|
+
if (entry.before.exists) atomicBuffer(entry.path, entry.before.buffer, entry.before.mode, fsImpl);
|
|
177
|
+
else if (fsImpl.existsSync(entry.path)) fsImpl.unlinkSync(entry.path);
|
|
178
|
+
} catch (_) { failed.push(entry.path); }
|
|
179
|
+
}
|
|
180
|
+
return failed;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function apply(params = {}) {
|
|
184
|
+
if (busy) return configChangeError('config-change-busy', '已有配置变更正在执行');
|
|
185
|
+
const plan = plans.get(params.previewId);
|
|
186
|
+
if (!plan || plan.expiresAt <= now()) return configChangeError('config-change-expired', '预览已失效,请重新预览');
|
|
187
|
+
const denied = permission(plan.target);
|
|
188
|
+
if (denied) return denied;
|
|
189
|
+
busy = true;
|
|
190
|
+
const applied = [];
|
|
191
|
+
let runtimeState;
|
|
192
|
+
let runtimeTouched = false;
|
|
193
|
+
try {
|
|
194
|
+
const changes = readJournal();
|
|
195
|
+
for (const entry of plan.reads) checkFile(entry, entry.before);
|
|
196
|
+
if (!plan.files.length) { plans.delete(plan.id); return { ...plan.result, success: true, noChanges: true }; }
|
|
197
|
+
runtimeState = options.runtimeState ? options.runtimeState(plan) : null;
|
|
198
|
+
for (const entry of plan.files) {
|
|
199
|
+
checkFile(entry, entry.before);
|
|
200
|
+
if (options.beforeWrite) options.beforeWrite(plan, entry);
|
|
201
|
+
const result = writeTextAtomicWithBackup(entry.path, (entry.after || entry.before.buffer).toString('utf8'), { fs: fsImpl });
|
|
202
|
+
if (entry.after === null) fsImpl.unlinkSync(entry.path);
|
|
203
|
+
applied.push({ ...entry, backupPath: result ? result.backupPath : '', writtenState: snapshot(entry.path, fsImpl) });
|
|
204
|
+
}
|
|
205
|
+
if (options.reconcileRuntime) {
|
|
206
|
+
runtimeTouched = true;
|
|
207
|
+
await options.reconcileRuntime(plan, false, runtimeState);
|
|
208
|
+
}
|
|
209
|
+
for (const entry of applied) checkFile(entry, entry.writtenState);
|
|
210
|
+
const change = {
|
|
211
|
+
id: crypto.randomBytes(24).toString('hex'), target: plan.target, action: plan.action,
|
|
212
|
+
createdAt: new Date(now()).toISOString(), runtimeState,
|
|
213
|
+
files: applied.map(entry => ({ path: entry.path, backupPath: entry.backupPath, before: { exists: entry.before.exists, hash: entry.before.hash, mode: entry.before.mode }, after: entry.writtenState.exists ? { exists: true, hash: entry.writtenState.hash, mode: entry.writtenState.mode } : { exists: false, hash: '', mode: 0o600 } }))
|
|
214
|
+
};
|
|
215
|
+
const baseline = publicBaseline(plan.reads);
|
|
216
|
+
changes[plan.target] = change;
|
|
217
|
+
writeJournal(changes);
|
|
218
|
+
plans.delete(plan.id);
|
|
219
|
+
return { ...plan.result, success: true, change: publicChange(change), configChangeTarget: plan.target, configChangeBaseline: baseline };
|
|
220
|
+
} catch (error) {
|
|
221
|
+
const rollbackFailed = restoreEntries(applied);
|
|
222
|
+
if (error.rollbackFailed) rollbackFailed.push(error.path || 'config-write');
|
|
223
|
+
if (runtimeTouched && options.reconcileRuntime) {
|
|
224
|
+
try { await options.reconcileRuntime(plan, true, runtimeState); } catch (_) { rollbackFailed.push('claude-runtime'); }
|
|
225
|
+
}
|
|
226
|
+
return configChangeError(error.code === 'config-change-conflict' ? error.code : 'config-change-write-failed', error.code === 'config-change-conflict' ? error.message : '配置变更失败,已尝试恢复原内容', { path: error.path || '', rollbackFailed, rolledBack: rollbackFailed.length === 0 });
|
|
227
|
+
} finally { busy = false; }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function last(params = {}) {
|
|
231
|
+
if (!options.isTarget(params.target)) return configChangeError('config-change-invalid', '配置目标无效');
|
|
232
|
+
try { return { change: publicChange(readJournal()[params.target]) }; }
|
|
233
|
+
catch (_) { return configChangeError('config-change-history-invalid', '无法读取最近一次变更记录'); }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function undo(params = {}) {
|
|
237
|
+
if (busy) return configChangeError('config-change-busy', '已有配置变更正在执行');
|
|
238
|
+
if (!options.isTarget(params.target)) return configChangeError('config-change-invalid', '配置目标无效');
|
|
239
|
+
const denied = permission(params.target);
|
|
240
|
+
if (denied) return denied;
|
|
241
|
+
busy = true;
|
|
242
|
+
const restored = [];
|
|
243
|
+
let change;
|
|
244
|
+
let runtimeState;
|
|
245
|
+
let runtimeTouched = false;
|
|
246
|
+
try {
|
|
247
|
+
const changes = readJournal();
|
|
248
|
+
change = changes[params.target];
|
|
249
|
+
if (!change || change.id !== params.changeId) return configChangeError('config-change-expired', '撤销记录已失效,请刷新');
|
|
250
|
+
const entries = change.files.map(item => {
|
|
251
|
+
checkFile(item, item.after);
|
|
252
|
+
let buffer = null;
|
|
253
|
+
if (item.before.exists) {
|
|
254
|
+
if (!item.backupPath || path.dirname(item.backupPath) !== path.dirname(item.path) || !path.basename(item.backupPath).startsWith(path.basename(item.path) + '.codexmate-backup-')) throw new Error('备份路径无效');
|
|
255
|
+
buffer = fsImpl.readFileSync(item.backupPath);
|
|
256
|
+
if (hash(buffer) !== item.before.hash) throw new Error('备份校验失败');
|
|
257
|
+
}
|
|
258
|
+
return { ...item, buffer, current: snapshot(item.path, fsImpl) };
|
|
259
|
+
});
|
|
260
|
+
runtimeState = options.runtimeState ? options.runtimeState(change) : null;
|
|
261
|
+
for (const entry of entries) {
|
|
262
|
+
checkFile(entry, entry.after);
|
|
263
|
+
const restoreEntry = { path: entry.path, before: entry.current, writtenState: { exists: entry.buffer !== null, hash: entry.buffer ? hash(entry.buffer) : '', mode: entry.before.mode } };
|
|
264
|
+
try {
|
|
265
|
+
if (entry.buffer === null) fsImpl.unlinkSync(entry.path);
|
|
266
|
+
else atomicBuffer(entry.path, entry.buffer, entry.before.mode, fsImpl);
|
|
267
|
+
} finally {
|
|
268
|
+
const current = snapshot(entry.path, fsImpl);
|
|
269
|
+
if (current.exists === restoreEntry.writtenState.exists && current.hash === restoreEntry.writtenState.hash) restored.push(restoreEntry);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (options.reconcileRuntime) {
|
|
273
|
+
runtimeTouched = true;
|
|
274
|
+
await options.reconcileRuntime(change, true, change.runtimeState);
|
|
275
|
+
}
|
|
276
|
+
for (const entry of restored) checkFile(entry, entry.writtenState);
|
|
277
|
+
const baseline = publicBaseline(change.files);
|
|
278
|
+
delete changes[params.target];
|
|
279
|
+
writeJournal(changes);
|
|
280
|
+
return { success: true, target: params.target, configChangeTarget: params.target, configChangeBaseline: baseline };
|
|
281
|
+
} catch (error) {
|
|
282
|
+
const rollbackFailed = restoreEntries(restored);
|
|
283
|
+
if (runtimeTouched && options.reconcileRuntime) {
|
|
284
|
+
try { await options.reconcileRuntime(change, true, runtimeState); } catch (_) { rollbackFailed.push('claude-runtime'); }
|
|
285
|
+
}
|
|
286
|
+
return configChangeError(error.code || 'config-change-undo-failed', error.code === 'config-change-conflict' ? error.message : '撤销失败,已保留当前配置', { path: error.path || '', rollbackFailed, rolledBack: rollbackFailed.length === 0 });
|
|
287
|
+
} finally { busy = false; }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return { preview, apply, last, undo, isBusy: () => busy };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
module.exports = { createConfigChanges, buildPreviewFile, PREVIEW_TTL_MS };
|
package/lib/handoff-mcp.js
CHANGED
|
@@ -35,7 +35,7 @@ function discoverServers(options = {}, warnings = []) {
|
|
|
35
35
|
const disabled = new Set([...(config.disabledMcpServers || []), ...(project.disabledMcpServers || [])]);
|
|
36
36
|
for (const [name, entry] of Object.entries(entries)) {
|
|
37
37
|
if (!entry || entry.disabled || entry.enabled === false || disabled.has(name)) continue;
|
|
38
|
-
if (!SHARED_SERVER.test([name, entry.command, ...(entry.args || []), entry.url].join(' '))) continue;
|
|
38
|
+
if (!options.allServers && !SHARED_SERVER.test([name, entry.command, ...(entry.args || []), entry.url].join(' '))) continue;
|
|
39
39
|
if (!servers.some(server => server.name === name)) servers.push({ ...entry, name, cwd: entry.cwd || cwd });
|
|
40
40
|
}
|
|
41
41
|
}
|
|
@@ -279,4 +279,20 @@ async function deliver(handoff, options = {}) {
|
|
|
279
279
|
}
|
|
280
280
|
}
|
|
281
281
|
|
|
282
|
-
|
|
282
|
+
async function probeServer(name, options = {}) {
|
|
283
|
+
const server = discoverServers({ ...options, allServers: true }).find((entry) => entry.name === name);
|
|
284
|
+
if (!server) throw new Error('diagnostic-input-invalid');
|
|
285
|
+
const timeout = Math.min(TIMEOUT_MS, options.timeoutMs || TIMEOUT_MS);
|
|
286
|
+
const connection = server.url ? openHttp(server, timeout) : openStdio(server, timeout);
|
|
287
|
+
try {
|
|
288
|
+
if (options.isCancelled?.()) throw new Error('diagnostic-cancelled');
|
|
289
|
+
const initialized = await connection.request('initialize', { protocolVersion: '2025-11-25',
|
|
290
|
+
capabilities: {}, clientInfo: { name: 'codexmate-doctor', version: '1' } });
|
|
291
|
+
await connection.request('notifications/initialized', {}, true);
|
|
292
|
+
if (options.isCancelled?.()) throw new Error('diagnostic-cancelled');
|
|
293
|
+
const listing = await connection.request('tools/list', {});
|
|
294
|
+
return { ok: true, name, protocolVersion: initialized.protocolVersion,
|
|
295
|
+
tools: (listing.tools || []).map((tool) => tool.name) };
|
|
296
|
+
} finally { await connection.close(); }
|
|
297
|
+
}
|
|
298
|
+
module.exports = { deliver, discoverServers, nativeWrite, probeServer };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
const MAX_STORE_BYTES = 5 * 1024 * 1024;
|
|
6
|
+
const digest = (text) => crypto.createHash('sha256').update(text).digest('hex');
|
|
7
|
+
|
|
8
|
+
function createLocalFeatureStore(filePath, initial) {
|
|
9
|
+
function read() {
|
|
10
|
+
try {
|
|
11
|
+
const stat = fs.lstatSync(filePath);
|
|
12
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_STORE_BYTES) throw new Error('feature-store-invalid');
|
|
13
|
+
const text = fs.readFileSync(filePath, 'utf8');
|
|
14
|
+
const value = JSON.parse(text);
|
|
15
|
+
if (value.version !== initial.version) throw new Error('feature-store-invalid');
|
|
16
|
+
return { value, revision: digest(text) };
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (error.code !== 'ENOENT') throw error;
|
|
19
|
+
return { value: JSON.parse(JSON.stringify(initial)), revision: '' };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function write(value, revision) {
|
|
23
|
+
if (read().revision !== revision) throw new Error('feature-store-conflict');
|
|
24
|
+
const text = JSON.stringify(value) + '\n';
|
|
25
|
+
if (Buffer.byteLength(text) > MAX_STORE_BYTES) throw new Error('feature-store-full');
|
|
26
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
27
|
+
const temporary = `${filePath}.${crypto.randomBytes(12).toString('hex')}.tmp`;
|
|
28
|
+
try {
|
|
29
|
+
fs.writeFileSync(temporary, text, { mode: 0o600, flag: 'wx' });
|
|
30
|
+
if (read().revision !== revision) throw new Error('feature-store-conflict');
|
|
31
|
+
fs.renameSync(temporary, filePath);
|
|
32
|
+
} finally {
|
|
33
|
+
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
|
34
|
+
}
|
|
35
|
+
return { value, revision: digest(text) };
|
|
36
|
+
}
|
|
37
|
+
return { read, write };
|
|
38
|
+
}
|
|
39
|
+
module.exports = { createLocalFeatureStore, digest };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { createLocalFeatureStore, digest } = require('./local-feature-store');
|
|
4
|
+
const MAX_NOTE_LENGTH = 4000;
|
|
5
|
+
const MAX_TAG_LENGTH = 80;
|
|
6
|
+
const MAX_TAGS = 20;
|
|
7
|
+
const MAX_EXCERPT_LENGTH = 50000;
|
|
8
|
+
|
|
9
|
+
function projectKey(cwd) {
|
|
10
|
+
if (!cwd) return '';
|
|
11
|
+
// Respect Windows path rules without merging same-named directories or worktrees.
|
|
12
|
+
return process.platform === 'win32' ? path.resolve(cwd).toLowerCase() : path.resolve(cwd);
|
|
13
|
+
}
|
|
14
|
+
function createSessionBookmarks({ root, readNode }) {
|
|
15
|
+
const store = createLocalFeatureStore(path.join(root, 'bookmarks.json'), { version: 1, items: [] });
|
|
16
|
+
function list(params = {}) {
|
|
17
|
+
const snapshot = store.read();
|
|
18
|
+
if (!Array.isArray(snapshot.value.items)) throw new Error('feature-store-invalid');
|
|
19
|
+
const query = String(params.query || '').toLowerCase();
|
|
20
|
+
const items = snapshot.value.items.filter((item) => (!params.project || item.projectKey === projectKey(params.project))
|
|
21
|
+
&& (!params.tag || item.tags.includes(params.tag))
|
|
22
|
+
&& `${item.excerpt}\n${item.note}\n${item.tags.join(' ')}`.toLowerCase().includes(query));
|
|
23
|
+
return { items, revision: snapshot.revision };
|
|
24
|
+
}
|
|
25
|
+
function edit(params) {
|
|
26
|
+
if (typeof params.note !== 'string' || params.note.length > MAX_NOTE_LENGTH || !Array.isArray(params.tags)
|
|
27
|
+
|| params.tags.length > MAX_TAGS || params.tags.some((tag) => typeof tag !== 'string' || tag.length > MAX_TAG_LENGTH)) {
|
|
28
|
+
throw new Error('bookmark-input-invalid');
|
|
29
|
+
}
|
|
30
|
+
return { note: params.note, tags: [...new Set(params.tags.map((tag) => tag.trim()).filter(Boolean))] };
|
|
31
|
+
}
|
|
32
|
+
async function save(params) {
|
|
33
|
+
const snapshot = store.read();
|
|
34
|
+
if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
|
|
35
|
+
const fields = edit(params);
|
|
36
|
+
const existing = params.id && snapshot.value.items.find((item) => item.id === params.id);
|
|
37
|
+
if (params.id && !existing) throw new Error('bookmark-not-found');
|
|
38
|
+
let item = existing;
|
|
39
|
+
if (!item) {
|
|
40
|
+
const result = await readNode(params);
|
|
41
|
+
if (result.error) throw new Error('bookmark-source-unavailable');
|
|
42
|
+
const node = result.node;
|
|
43
|
+
const id = digest(JSON.stringify([result.source, params.sessionId || params.filePath, node.id]));
|
|
44
|
+
item = snapshot.value.items.find((entry) => entry.id === id);
|
|
45
|
+
if (item) return { ...list(), item };
|
|
46
|
+
if (node.text.length > MAX_EXCERPT_LENGTH) throw new Error('bookmark-excerpt-too-large');
|
|
47
|
+
item = { id, source: result.source, sessionId: params.sessionId || '', filePath: params.filePath || '',
|
|
48
|
+
nodeId: node.id, cwd: params.cwd || '', projectKey: projectKey(params.cwd), excerpt: node.text,
|
|
49
|
+
textHash: digest(node.text), createdAt: new Date().toISOString() };
|
|
50
|
+
snapshot.value.items.unshift(item);
|
|
51
|
+
}
|
|
52
|
+
Object.assign(item, fields, { updatedAt: new Date().toISOString() });
|
|
53
|
+
store.write(snapshot.value, snapshot.revision);
|
|
54
|
+
return { ...list(), item };
|
|
55
|
+
}
|
|
56
|
+
function remove(params) {
|
|
57
|
+
const snapshot = store.read();
|
|
58
|
+
if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
|
|
59
|
+
snapshot.value.items = snapshot.value.items.filter((item) => item.id !== params.id);
|
|
60
|
+
store.write(snapshot.value, snapshot.revision);
|
|
61
|
+
return list();
|
|
62
|
+
}
|
|
63
|
+
async function locate(params) {
|
|
64
|
+
const item = store.read().value.items.find((entry) => entry.id === params.id);
|
|
65
|
+
if (!item) throw new Error('bookmark-not-found');
|
|
66
|
+
const result = await readNode({ ...item, nodeId: item.nodeId });
|
|
67
|
+
if (result.error || digest(result.node.text) !== item.textHash) return { item, available: false };
|
|
68
|
+
return { item, available: true, node: result.node };
|
|
69
|
+
}
|
|
70
|
+
return { list, save, remove, locate };
|
|
71
|
+
}
|
|
72
|
+
module.exports = { createSessionBookmarks, projectKey };
|
|
@@ -53,19 +53,28 @@ function createSessionContextHealthController(deps) {
|
|
|
53
53
|
const analyzer = createContextAnalyzer();
|
|
54
54
|
const reader = createContextRecordReader(target.source, params.cwd || '');
|
|
55
55
|
let index = 0;
|
|
56
|
+
const models = new Set();
|
|
57
|
+
const modelWindows = {};
|
|
56
58
|
for await (const record of records(target.source, target.filePath, target.sessionId)) {
|
|
59
|
+
const metadata = record?.payload || record?.message || record || {};
|
|
60
|
+
const model = metadata.model || metadata.modelID || metadata.info?.modelID;
|
|
61
|
+
const window = metadata.model_context_window ?? metadata.context_window ?? metadata.contextWindow;
|
|
62
|
+
if (typeof model === 'string' && model) {
|
|
63
|
+
models.add(model);
|
|
64
|
+
if (Number.isSafeInteger(window) && window > 0) modelWindows[model] = window;
|
|
65
|
+
}
|
|
57
66
|
for (const node of reader(record, index)) {
|
|
58
67
|
if (!focus) analyzer.add(node);
|
|
59
68
|
if (node.id === focus) {
|
|
60
69
|
return { source: target.source, node: { id: node.id, role: node.role,
|
|
61
70
|
recordLineIndex: node.recordLineIndex, messageIndex: node.messageIndex,
|
|
62
|
-
text: node.parts.map((part) => part.text).join('\n') } };
|
|
71
|
+
text: node.parts.map((part) => part.text).join('\n'), readPaths: node.readPaths || [] } };
|
|
63
72
|
}
|
|
64
73
|
}
|
|
65
74
|
index++;
|
|
66
75
|
}
|
|
67
76
|
if (focus) throw new Error('消息节点不存在,请刷新体检结果');
|
|
68
|
-
return { source: target.source, sessionId: target.sessionId, complete: true, scannedRecords: index, ...analyzer.finish() };
|
|
77
|
+
return { source: target.source, sessionId: target.sessionId, complete: true, scannedRecords: index, models: [...models], modelWindows, ...analyzer.finish() };
|
|
69
78
|
}
|
|
70
79
|
async function readSessionContextHealth(params = {}) {
|
|
71
80
|
try { return await scan(params); } catch (error) { return { error: error.message }; }
|
|
@@ -76,7 +85,18 @@ function createSessionContextHealthController(deps) {
|
|
|
76
85
|
}
|
|
77
86
|
try { return await scan(params, params.nodeId); } catch (error) { return { error: error.message }; }
|
|
78
87
|
}
|
|
79
|
-
|
|
88
|
+
async function* iterateSessionContextNodes(params = {}) {
|
|
89
|
+
const target = resolve(params);
|
|
90
|
+
const reader = createContextRecordReader(target.source, params.cwd || '');
|
|
91
|
+
let index = 0;
|
|
92
|
+
for await (const record of records(target.source, target.filePath, target.sessionId)) {
|
|
93
|
+
for (const node of reader(record, index)) yield { ...node,
|
|
94
|
+
text: node.parts.map((part) => part.text).join('\n'),
|
|
95
|
+
timestamp: record?.timestamp || record?.message?.timestamp || '' };
|
|
96
|
+
index++;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { readSessionContextHealth, readSessionContextNode, iterateSessionContextNodes };
|
|
80
100
|
}
|
|
81
101
|
|
|
82
102
|
module.exports = { createSessionContextHealthController };
|