agentdock-cli 1.1.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -4
- package/dist/package.json +2 -2
- package/dist/src/agents/registry.js +551 -0
- package/dist/src/agents/semantic.js +208 -0
- package/dist/src/cli.js +45 -1
- package/dist/src/commands/agents.js +84 -0
- package/dist/src/commands/diff.js +73 -0
- package/dist/src/commands/doctor.js +1 -0
- package/dist/src/commands/history.js +109 -0
- package/dist/src/commands/list.js +2 -1
- package/dist/src/commands/recover.js +185 -0
- package/dist/src/commands/restore.js +103 -0
- package/dist/src/commands/snapshot.js +155 -0
- package/dist/src/commands/sync.js +5 -1
- package/dist/src/constants/command-error-codes.js +4 -0
- package/dist/src/core/doctor.js +319 -6
- package/dist/src/core/installer.js +18 -15
- package/dist/src/core/list.js +6 -0
- package/dist/src/core/report.js +29 -8
- package/dist/src/core/scan-export.js +31 -30
- package/dist/src/core/scan.js +59 -34
- package/dist/src/core/snapshot-diff.js +111 -0
- package/dist/src/core/snapshot.js +535 -0
- package/dist/src/core/uninstall.js +12 -7
- package/dist/src/i18n/index.js +112 -4
- package/dist/src/scanners/semantic-scanner.js +272 -0
- package/dist/src/utils/config-format.js +168 -0
- package/package.json +2 -2
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.SNAPSHOT_BUNDLE_DIR = void 0;
|
|
7
|
+
exports.configFilesFor = configFilesFor;
|
|
8
|
+
exports.snapshotsDir = snapshotsDir;
|
|
9
|
+
exports.hashBuffer = hashBuffer;
|
|
10
|
+
exports.redactConfigText = redactConfigText;
|
|
11
|
+
exports.createSnapshot = createSnapshot;
|
|
12
|
+
exports.listSnapshots = listSnapshots;
|
|
13
|
+
exports.latestSnapshot = latestSnapshot;
|
|
14
|
+
exports.loadSnapshot = loadSnapshot;
|
|
15
|
+
exports.readSnapshotContents = readSnapshotContents;
|
|
16
|
+
exports.readLiveConfig = readLiveConfig;
|
|
17
|
+
exports.findUnchangedSnapshot = findUnchangedSnapshot;
|
|
18
|
+
exports.exportSnapshot = exportSnapshot;
|
|
19
|
+
exports.importSnapshots = importSnapshots;
|
|
20
|
+
exports.planRestore = planRestore;
|
|
21
|
+
exports.applyRestore = applyRestore;
|
|
22
|
+
exports.prepareUndo = prepareUndo;
|
|
23
|
+
exports.applyUndo = applyUndo;
|
|
24
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
25
|
+
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
26
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
27
|
+
const package_json_1 = __importDefault(require("../../package.json"));
|
|
28
|
+
const registry_1 = require("../agents/registry");
|
|
29
|
+
const snapshot_diff_1 = require("./snapshot-diff");
|
|
30
|
+
const fs_1 = require("../utils/fs");
|
|
31
|
+
/**
|
|
32
|
+
* 配置快照(v1.2)。
|
|
33
|
+
* 只采集关键配置文件(不复制 skills / memory 全量),默认明文保存,
|
|
34
|
+
* `--redact` 时对疑似令牌值打码。所有写入都限制在 `<root>/.agentdock` 内。
|
|
35
|
+
*/
|
|
36
|
+
const SECRET_KEY_PATTERN = /(token|secret|passw|api[_-]?key|auth|credential|cookie)/i;
|
|
37
|
+
const REDACTED = '***REDACTED***';
|
|
38
|
+
/** 只保留最近这么多个快照的索引条目,避免 index.json 无限增长。 */
|
|
39
|
+
const MAX_INDEX_ENTRIES = 200;
|
|
40
|
+
/** 该工具(或 `all`)需要纳入快照的配置文件,来自适配器注册表。 */
|
|
41
|
+
function configFilesFor(agent) {
|
|
42
|
+
return (0, registry_1.agentConfigFiles)(agent).map((file) => file.relPath);
|
|
43
|
+
}
|
|
44
|
+
function snapshotsDir(root) {
|
|
45
|
+
return node_path_1.default.join(root, '.agentdock', 'snapshots');
|
|
46
|
+
}
|
|
47
|
+
function indexPath(root) {
|
|
48
|
+
return node_path_1.default.join(snapshotsDir(root), 'index.json');
|
|
49
|
+
}
|
|
50
|
+
function restoreRecordPath(root) {
|
|
51
|
+
return node_path_1.default.join(root, '.agentdock', 'last-restore.json');
|
|
52
|
+
}
|
|
53
|
+
function hashBuffer(data) {
|
|
54
|
+
return node_crypto_1.default.createHash('sha256').update(data).digest('hex');
|
|
55
|
+
}
|
|
56
|
+
function fileKind(relPath) {
|
|
57
|
+
if (relPath.endsWith('.jsonc'))
|
|
58
|
+
return 'jsonc';
|
|
59
|
+
if (relPath.endsWith('.json'))
|
|
60
|
+
return 'json';
|
|
61
|
+
if (relPath.endsWith('.toml'))
|
|
62
|
+
return 'toml';
|
|
63
|
+
if (relPath.endsWith('.yml') || relPath.endsWith('.yaml'))
|
|
64
|
+
return 'yaml';
|
|
65
|
+
return 'text';
|
|
66
|
+
}
|
|
67
|
+
/** 按行脱敏:兼容 `a = b`(TOML/INI)、`"a": "b"`(JSON/JSONC)与 `a: b`(YAML)。 */
|
|
68
|
+
function redactTextByLine(text) {
|
|
69
|
+
return text
|
|
70
|
+
.split(/\r?\n/)
|
|
71
|
+
.map((line) => {
|
|
72
|
+
const match = /^(\s*"?[A-Za-z0-9_.-]*(?:token|secret|passw|api[_-]?key|auth|credential)[A-Za-z0-9_.-]*"?\s*[:=]\s*).*$/i.exec(line);
|
|
73
|
+
return match ? `${match[1]}"${REDACTED}"` : line;
|
|
74
|
+
})
|
|
75
|
+
.join('\n');
|
|
76
|
+
}
|
|
77
|
+
function redactJsonValue(value) {
|
|
78
|
+
if (Array.isArray(value)) {
|
|
79
|
+
return value.map(redactJsonValue);
|
|
80
|
+
}
|
|
81
|
+
if (value && typeof value === 'object') {
|
|
82
|
+
const out = {};
|
|
83
|
+
for (const [key, value2] of Object.entries(value)) {
|
|
84
|
+
out[key] = SECRET_KEY_PATTERN.test(key) ? REDACTED : redactJsonValue(value2);
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
/** 对单个配置文件内容做脱敏;解析失败时退回按行正则。 */
|
|
91
|
+
function redactConfigText(relPath, text) {
|
|
92
|
+
if (fileKind(relPath) === 'json') {
|
|
93
|
+
try {
|
|
94
|
+
return `${JSON.stringify(redactJsonValue(JSON.parse(text)), null, 2)}\n`;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return redactTextByLine(text);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return redactTextByLine(text);
|
|
101
|
+
}
|
|
102
|
+
function computeCounts(files) {
|
|
103
|
+
let topLevelKeys = 0;
|
|
104
|
+
let envKeys = 0;
|
|
105
|
+
let mcpCount = 0;
|
|
106
|
+
for (const [relPath, buffer] of files) {
|
|
107
|
+
const parsed = (0, snapshot_diff_1.parseConfigObject)(relPath, buffer.toString('utf8'));
|
|
108
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const obj = parsed;
|
|
112
|
+
topLevelKeys += Object.keys(obj).length;
|
|
113
|
+
if (relPath.endsWith('settings.json') || relPath.endsWith('settings.local.json')) {
|
|
114
|
+
const env = obj.env;
|
|
115
|
+
if (env && typeof env === 'object' && !Array.isArray(env)) {
|
|
116
|
+
envKeys += Object.keys(env).length;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for (const key of ['mcpServers', 'mcp_servers', 'mcp']) {
|
|
120
|
+
const mcp = obj[key];
|
|
121
|
+
if (mcp && typeof mcp === 'object' && !Array.isArray(mcp)) {
|
|
122
|
+
mcpCount += Object.keys(mcp).length;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { topLevelKeys, envKeys, mcpCount };
|
|
127
|
+
}
|
|
128
|
+
function newSnapshotId(now = new Date()) {
|
|
129
|
+
return now.toISOString().replace(/[:.]/g, '-');
|
|
130
|
+
}
|
|
131
|
+
async function readIndex(root) {
|
|
132
|
+
try {
|
|
133
|
+
const parsed = await (0, fs_1.readJsonFile)(indexPath(root));
|
|
134
|
+
if (Array.isArray(parsed)) {
|
|
135
|
+
return parsed;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// 索引缺失或损坏时按目录重建
|
|
140
|
+
}
|
|
141
|
+
return rebuildIndex(root);
|
|
142
|
+
}
|
|
143
|
+
async function rebuildIndex(root) {
|
|
144
|
+
const dir = snapshotsDir(root);
|
|
145
|
+
if (!(await (0, fs_1.pathExists)(dir))) {
|
|
146
|
+
return [];
|
|
147
|
+
}
|
|
148
|
+
const entries = [];
|
|
149
|
+
const names = await promises_1.default.readdir(dir);
|
|
150
|
+
for (const name of names) {
|
|
151
|
+
if (name === 'index.json') {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const meta = await (0, fs_1.readJsonFile)(node_path_1.default.join(dir, name, 'snapshot.json'));
|
|
156
|
+
entries.push({
|
|
157
|
+
id: meta.id,
|
|
158
|
+
createdAt: meta.createdAt,
|
|
159
|
+
agent: meta.agent,
|
|
160
|
+
files: meta.files.length,
|
|
161
|
+
redacted: meta.redacted,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
// 不是快照目录,跳过
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return entries.sort((a, b) => b.id.localeCompare(a.id));
|
|
169
|
+
}
|
|
170
|
+
async function writeIndex(root, entries) {
|
|
171
|
+
// 快照 id 以 ISO 时间戳开头,按 id 倒序即时间倒序;同毫秒时 `-1` 后缀排在更前。
|
|
172
|
+
const sorted = [...entries].sort((a, b) => b.id.localeCompare(a.id));
|
|
173
|
+
await (0, fs_1.writeJsonFile)(indexPath(root), sorted.slice(0, MAX_INDEX_ENTRIES));
|
|
174
|
+
}
|
|
175
|
+
/** 采集当前配置并写入快照,返回快照元数据。 */
|
|
176
|
+
async function createSnapshot(options) {
|
|
177
|
+
const files = new Map();
|
|
178
|
+
for (const relPath of configFilesFor(options.agent)) {
|
|
179
|
+
const abs = (0, fs_1.safeResolveWithin)(options.root, relPath);
|
|
180
|
+
if (!(await (0, fs_1.pathExists)(abs))) {
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const raw = await promises_1.default.readFile(abs);
|
|
184
|
+
const content = options.redact
|
|
185
|
+
? Buffer.from(redactConfigText(relPath, raw.toString('utf8')), 'utf8')
|
|
186
|
+
: raw;
|
|
187
|
+
files.set(relPath, content);
|
|
188
|
+
}
|
|
189
|
+
if (files.size === 0) {
|
|
190
|
+
throw new Error(`SNAPSHOT_EMPTY: 在 ${options.root} 下未找到可快照的配置文件`);
|
|
191
|
+
}
|
|
192
|
+
const createdAt = new Date();
|
|
193
|
+
const baseId = newSnapshotId(createdAt);
|
|
194
|
+
let id = baseId;
|
|
195
|
+
let dir = node_path_1.default.join(snapshotsDir(options.root), id);
|
|
196
|
+
let suffix = 0;
|
|
197
|
+
while (await (0, fs_1.pathExists)(dir)) {
|
|
198
|
+
suffix += 1;
|
|
199
|
+
id = `${baseId}-${suffix}`;
|
|
200
|
+
dir = node_path_1.default.join(snapshotsDir(options.root), id);
|
|
201
|
+
}
|
|
202
|
+
await (0, fs_1.ensureDirectory)(node_path_1.default.join(dir, 'files'));
|
|
203
|
+
const entries = [];
|
|
204
|
+
for (const [relPath, content] of files) {
|
|
205
|
+
const target = (0, fs_1.safeResolveWithin)(node_path_1.default.join(dir, 'files'), relPath, 'snapshot file');
|
|
206
|
+
await (0, fs_1.ensureDirectory)(node_path_1.default.dirname(target));
|
|
207
|
+
await (0, fs_1.writeBinaryFile)(target, content, 0o600);
|
|
208
|
+
entries.push({
|
|
209
|
+
relPath,
|
|
210
|
+
sha256: hashBuffer(content),
|
|
211
|
+
size: content.length,
|
|
212
|
+
kind: fileKind(relPath),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const meta = {
|
|
216
|
+
id,
|
|
217
|
+
createdAt: createdAt.toISOString(),
|
|
218
|
+
agent: options.agent,
|
|
219
|
+
root: options.root,
|
|
220
|
+
toolVersion: package_json_1.default.version,
|
|
221
|
+
redacted: options.redact,
|
|
222
|
+
files: entries,
|
|
223
|
+
counts: computeCounts(files),
|
|
224
|
+
};
|
|
225
|
+
const metaPath = node_path_1.default.join(dir, 'snapshot.json');
|
|
226
|
+
await (0, fs_1.writeJsonFile)(metaPath, meta);
|
|
227
|
+
await chmodQuiet(metaPath, 0o600);
|
|
228
|
+
const index = await readIndex(options.root);
|
|
229
|
+
await writeIndex(options.root, [
|
|
230
|
+
{ id: meta.id, createdAt: meta.createdAt, agent: meta.agent, files: meta.files.length, redacted: meta.redacted },
|
|
231
|
+
...index.filter((item) => item.id !== meta.id),
|
|
232
|
+
]);
|
|
233
|
+
return meta;
|
|
234
|
+
}
|
|
235
|
+
async function chmodQuiet(target, mode) {
|
|
236
|
+
try {
|
|
237
|
+
await promises_1.default.chmod(target, mode);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// Windows 上权限位语义有限,忽略
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
async function listSnapshots(root) {
|
|
244
|
+
return readIndex(root);
|
|
245
|
+
}
|
|
246
|
+
/** 最近一次快照;agent 指定时匹配该 agent 或 `all` 采集的快照。 */
|
|
247
|
+
async function latestSnapshot(root, agent) {
|
|
248
|
+
const index = await readIndex(root);
|
|
249
|
+
const matches = agent
|
|
250
|
+
? index.filter((item) => item.agent === agent || item.agent === 'all')
|
|
251
|
+
: index;
|
|
252
|
+
if (matches.length === 0) {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
const newest = [...matches].sort((a, b) => b.id.localeCompare(a.id))[0];
|
|
256
|
+
return loadSnapshot(root, newest.id);
|
|
257
|
+
}
|
|
258
|
+
/** 解析快照 id:支持完整 id、唯一前缀、快照目录路径与 `latest`。 */
|
|
259
|
+
async function loadSnapshot(root, idOrPath) {
|
|
260
|
+
const dir = await resolveSnapshotDir(root, idOrPath);
|
|
261
|
+
try {
|
|
262
|
+
const meta = await (0, fs_1.readJsonFile)(node_path_1.default.join(dir, 'snapshot.json'));
|
|
263
|
+
return { meta, dir };
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: 无法读取快照 ${idOrPath}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
async function resolveSnapshotDir(root, idOrPath) {
|
|
270
|
+
const looksLikePath = idOrPath.includes('/') || idOrPath.includes('\\') || node_path_1.default.isAbsolute(idOrPath);
|
|
271
|
+
if (looksLikePath) {
|
|
272
|
+
const resolved = node_path_1.default.resolve(idOrPath);
|
|
273
|
+
if (await (0, fs_1.pathExists)(resolved)) {
|
|
274
|
+
return resolved;
|
|
275
|
+
}
|
|
276
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: ${idOrPath}`);
|
|
277
|
+
}
|
|
278
|
+
const base = snapshotsDir(root);
|
|
279
|
+
if (idOrPath === 'latest') {
|
|
280
|
+
const latest = await latestSnapshot(root);
|
|
281
|
+
if (!latest) {
|
|
282
|
+
throw new Error('SNAPSHOT_NOT_FOUND: 尚无任何快照');
|
|
283
|
+
}
|
|
284
|
+
return latest.dir;
|
|
285
|
+
}
|
|
286
|
+
const direct = node_path_1.default.join(base, idOrPath);
|
|
287
|
+
if (await (0, fs_1.pathExists)(node_path_1.default.join(direct, 'snapshot.json'))) {
|
|
288
|
+
return direct;
|
|
289
|
+
}
|
|
290
|
+
if (await (0, fs_1.pathExists)(base)) {
|
|
291
|
+
const names = (await promises_1.default.readdir(base)).filter((name) => name !== 'index.json' && name.startsWith(idOrPath));
|
|
292
|
+
if (names.length === 1) {
|
|
293
|
+
return node_path_1.default.join(base, names[0]);
|
|
294
|
+
}
|
|
295
|
+
if (names.length > 1) {
|
|
296
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: 前缀 ${idOrPath} 匹配到多个快照,请提供完整 id`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: ${idOrPath}`);
|
|
300
|
+
}
|
|
301
|
+
/** 读取快照中保存的配置内容(relPath → 原始字节)。 */
|
|
302
|
+
async function readSnapshotContents(snapshot) {
|
|
303
|
+
const contents = new Map();
|
|
304
|
+
for (const file of snapshot.meta.files) {
|
|
305
|
+
const source = (0, fs_1.safeResolveWithin)(node_path_1.default.join(snapshot.dir, 'files'), file.relPath, 'snapshot file');
|
|
306
|
+
try {
|
|
307
|
+
contents.set(file.relPath, await promises_1.default.readFile(source));
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
// 快照内容缺失时跳过,由调用方按"文件不存在"处理
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return contents;
|
|
314
|
+
}
|
|
315
|
+
/** 读取本机当前的关键配置文件。 */
|
|
316
|
+
async function readLiveConfig(root, agent) {
|
|
317
|
+
const contents = new Map();
|
|
318
|
+
for (const relPath of configFilesFor(agent)) {
|
|
319
|
+
const abs = (0, fs_1.safeResolveWithin)(root, relPath);
|
|
320
|
+
try {
|
|
321
|
+
contents.set(relPath, await promises_1.default.readFile(abs));
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
// 文件不存在
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return contents;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* 当前配置与最近快照完全一致时返回该快照元数据,否则返回 null。
|
|
331
|
+
* 用于 `snapshot --if-changed`:定时任务里没变化就不重复落盘。
|
|
332
|
+
*/
|
|
333
|
+
async function findUnchangedSnapshot(root, agent) {
|
|
334
|
+
const latest = await latestSnapshot(root, agent);
|
|
335
|
+
// agent 范围不同(如已有 all 快照、本次只采 claude)时视为有变化,避免漏采
|
|
336
|
+
if (!latest || latest.meta.agent !== agent) {
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const stored = await readSnapshotContents(latest);
|
|
340
|
+
const live = await readLiveConfig(root, agent);
|
|
341
|
+
if (stored.size !== live.size) {
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
for (const [relPath, current] of live) {
|
|
345
|
+
const before = stored.get(relPath);
|
|
346
|
+
if (!before) {
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
// 快照若已脱敏,比对前同样对当前内容脱敏,避免每次都判定为变化
|
|
350
|
+
const comparable = latest.meta.redacted
|
|
351
|
+
? Buffer.from(redactConfigText(relPath, current.toString('utf8')), 'utf8')
|
|
352
|
+
: current;
|
|
353
|
+
if (hashBuffer(before) !== hashBuffer(comparable)) {
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return latest.meta;
|
|
358
|
+
}
|
|
359
|
+
// ===== 快照分享(push / pull) =====
|
|
360
|
+
/** 分享目录名:目标目录下按 `<target>/.agentdock-snapshots/<id>/` 存放快照。 */
|
|
361
|
+
exports.SNAPSHOT_BUNDLE_DIR = '.agentdock-snapshots';
|
|
362
|
+
/**
|
|
363
|
+
* 把一份快照复制到目标目录(如 Git 工作副本)。
|
|
364
|
+
* 明文快照含真实密钥,默认拒绝导出,必须先 `snapshot --redact` 或显式 `--force`。
|
|
365
|
+
*/
|
|
366
|
+
async function exportSnapshot(root, targetDir, id, force) {
|
|
367
|
+
const list = await listSnapshots(root);
|
|
368
|
+
const chosenId = id ?? list[0]?.id;
|
|
369
|
+
if (!chosenId) {
|
|
370
|
+
throw new Error('SNAPSHOT_NOT_FOUND: 还没有可导出的快照');
|
|
371
|
+
}
|
|
372
|
+
const loaded = await loadSnapshot(root, chosenId);
|
|
373
|
+
if (!loaded.meta.redacted && !force) {
|
|
374
|
+
throw new Error('SNAPSHOT_NOT_REDACTED: 快照含明文敏感值,分享前请用 `agentdock snapshot --redact` 重新采集,或加 --force 强制导出');
|
|
375
|
+
}
|
|
376
|
+
const dest = node_path_1.default.join(targetDir, exports.SNAPSHOT_BUNDLE_DIR, loaded.meta.id);
|
|
377
|
+
if (await (0, fs_1.pathExists)(dest)) {
|
|
378
|
+
if (!force) {
|
|
379
|
+
throw new Error(`SNAPSHOT_EXISTS: 目标已存在:${dest}(加 --force 覆盖)`);
|
|
380
|
+
}
|
|
381
|
+
await promises_1.default.rm(dest, { recursive: true, force: true });
|
|
382
|
+
}
|
|
383
|
+
await (0, fs_1.copyDirectorySafe)(loaded.dir, dest);
|
|
384
|
+
return { id: loaded.meta.id, dest, redacted: loaded.meta.redacted };
|
|
385
|
+
}
|
|
386
|
+
async function findSnapshotDirs(base) {
|
|
387
|
+
if (await (0, fs_1.pathExists)(node_path_1.default.join(base, 'snapshot.json'))) {
|
|
388
|
+
return [base];
|
|
389
|
+
}
|
|
390
|
+
let names;
|
|
391
|
+
try {
|
|
392
|
+
names = await promises_1.default.readdir(base);
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return [];
|
|
396
|
+
}
|
|
397
|
+
const dirs = [];
|
|
398
|
+
for (const name of names) {
|
|
399
|
+
const candidate = node_path_1.default.join(base, name);
|
|
400
|
+
if (await (0, fs_1.pathExists)(node_path_1.default.join(candidate, 'snapshot.json'))) {
|
|
401
|
+
dirs.push(candidate);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return dirs;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* 从目标目录导入快照:支持直接指向某份快照目录,或指向包含
|
|
408
|
+
* `.agentdock-snapshots/<id>/` 的目录(如 Git 工作副本)。
|
|
409
|
+
*/
|
|
410
|
+
async function importSnapshots(root, sourceDir, force) {
|
|
411
|
+
const dirs = new Set([
|
|
412
|
+
...(await findSnapshotDirs(sourceDir)),
|
|
413
|
+
...(await findSnapshotDirs(node_path_1.default.join(sourceDir, exports.SNAPSHOT_BUNDLE_DIR))),
|
|
414
|
+
]);
|
|
415
|
+
if (dirs.size === 0) {
|
|
416
|
+
throw new Error(`SNAPSHOT_NOT_FOUND: 在 ${sourceDir} 下未找到快照`);
|
|
417
|
+
}
|
|
418
|
+
const imported = [];
|
|
419
|
+
const skipped = [];
|
|
420
|
+
await (0, fs_1.ensureDirectory)(snapshotsDir(root));
|
|
421
|
+
for (const dir of dirs) {
|
|
422
|
+
let meta;
|
|
423
|
+
try {
|
|
424
|
+
meta = await (0, fs_1.readJsonFile)(node_path_1.default.join(dir, 'snapshot.json'));
|
|
425
|
+
}
|
|
426
|
+
catch {
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
// id 会被拼进本地路径,只接受安全字符,避免路径穿越
|
|
430
|
+
if (!meta.id || !/^[0-9A-Za-z._-]+$/.test(meta.id)) {
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
const dest = node_path_1.default.join(snapshotsDir(root), meta.id);
|
|
434
|
+
if (await (0, fs_1.pathExists)(dest)) {
|
|
435
|
+
if (!force) {
|
|
436
|
+
skipped.push(meta.id);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
await promises_1.default.rm(dest, { recursive: true, force: true });
|
|
440
|
+
}
|
|
441
|
+
await (0, fs_1.copyDirectorySafe)(dir, dest);
|
|
442
|
+
imported.push(meta.id);
|
|
443
|
+
}
|
|
444
|
+
await writeIndex(root, await rebuildIndex(root));
|
|
445
|
+
return { imported, skipped };
|
|
446
|
+
}
|
|
447
|
+
/** 生成恢复计划(不写盘)。 */
|
|
448
|
+
async function planRestore(root, snapshot) {
|
|
449
|
+
const contents = await readSnapshotContents(snapshot);
|
|
450
|
+
const entries = [];
|
|
451
|
+
for (const [relPath, content] of contents) {
|
|
452
|
+
const target = (0, fs_1.safeResolveWithin)(root, relPath);
|
|
453
|
+
let action = 'create';
|
|
454
|
+
if (await (0, fs_1.pathExists)(target)) {
|
|
455
|
+
try {
|
|
456
|
+
const current = await promises_1.default.readFile(target);
|
|
457
|
+
action = hashBuffer(current) === hashBuffer(content) ? 'skip' : 'overwrite';
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
action = 'overwrite';
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
entries.push({ relPath, target, action });
|
|
464
|
+
}
|
|
465
|
+
return entries;
|
|
466
|
+
}
|
|
467
|
+
/** 执行恢复;调用前必须已确认 apply。写前自动生成一份 before-restore 快照。 */
|
|
468
|
+
async function applyRestore(root, snapshot, entries) {
|
|
469
|
+
const actionable = entries.filter((entry) => entry.action !== 'skip');
|
|
470
|
+
if (actionable.length === 0) {
|
|
471
|
+
return {
|
|
472
|
+
snapshotId: snapshot.meta.id,
|
|
473
|
+
applied: true,
|
|
474
|
+
entries,
|
|
475
|
+
undo: false,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
const backup = await createSnapshot({ root, agent: snapshot.meta.agent, redact: snapshot.meta.redacted });
|
|
479
|
+
const sourceRoot = node_path_1.default.join(snapshot.dir, 'files');
|
|
480
|
+
for (const entry of entries) {
|
|
481
|
+
if (entry.action === 'skip') {
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
const source = (0, fs_1.safeResolveWithin)(sourceRoot, entry.relPath, 'snapshot file');
|
|
485
|
+
await (0, fs_1.copyFileSafe)(source, entry.target);
|
|
486
|
+
await chmodQuiet(entry.target, 0o600);
|
|
487
|
+
}
|
|
488
|
+
const record = {
|
|
489
|
+
snapshotId: snapshot.meta.id,
|
|
490
|
+
backupSnapshotId: backup.id,
|
|
491
|
+
restoredAt: new Date().toISOString(),
|
|
492
|
+
};
|
|
493
|
+
await (0, fs_1.writeJsonFile)(restoreRecordPath(root), record);
|
|
494
|
+
return {
|
|
495
|
+
snapshotId: snapshot.meta.id,
|
|
496
|
+
applied: true,
|
|
497
|
+
entries,
|
|
498
|
+
backupSnapshotId: backup.id,
|
|
499
|
+
undo: false,
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
/** 恢复最近一次恢复前快照所需的上下文。 */
|
|
503
|
+
async function readRestoreRecord(root) {
|
|
504
|
+
try {
|
|
505
|
+
return await (0, fs_1.readJsonFile)(restoreRecordPath(root));
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
throw new Error('RESTORE_NO_UNDO: 没有可撤销的恢复记录(或已完成撤销)');
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/** 撤销最近一次恢复:把写前快照重新写回。 */
|
|
512
|
+
async function prepareUndo(root) {
|
|
513
|
+
const record = await readRestoreRecord(root);
|
|
514
|
+
const snapshot = await loadSnapshot(root, record.backupSnapshotId);
|
|
515
|
+
const entries = await planRestore(root, snapshot);
|
|
516
|
+
return { snapshot, entries };
|
|
517
|
+
}
|
|
518
|
+
async function applyUndo(root, snapshot, entries) {
|
|
519
|
+
const sourceRoot = node_path_1.default.join(snapshot.dir, 'files');
|
|
520
|
+
for (const entry of entries) {
|
|
521
|
+
if (entry.action === 'skip') {
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
const source = (0, fs_1.safeResolveWithin)(sourceRoot, entry.relPath, 'snapshot file');
|
|
525
|
+
await (0, fs_1.copyFileSafe)(source, entry.target);
|
|
526
|
+
await chmodQuiet(entry.target, 0o600);
|
|
527
|
+
}
|
|
528
|
+
await promises_1.default.rm(restoreRecordPath(root), { force: true });
|
|
529
|
+
return {
|
|
530
|
+
snapshotId: snapshot.meta.id,
|
|
531
|
+
applied: true,
|
|
532
|
+
entries,
|
|
533
|
+
undo: true,
|
|
534
|
+
};
|
|
535
|
+
}
|
|
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.uninstallPackage = uninstallPackage;
|
|
7
7
|
const promises_1 = __importDefault(require("node:fs/promises"));
|
|
8
8
|
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
-
const
|
|
9
|
+
const config_format_1 = require("../utils/config-format");
|
|
10
10
|
const installer_1 = require("./installer");
|
|
11
11
|
const fs_1 = require("../utils/fs");
|
|
12
12
|
function deepEqual(a, b) {
|
|
@@ -34,9 +34,13 @@ function deepEqual(a, b) {
|
|
|
34
34
|
* unmerge. Returns the keys that were removed.
|
|
35
35
|
*/
|
|
36
36
|
async function unmergeDataFile(sourcePath, toPath, mergeKeys) {
|
|
37
|
-
const parse = (filePath, content) =>
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
const parse = (filePath, content) => {
|
|
38
|
+
const kind = (0, config_format_1.kindFromPath)(filePath);
|
|
39
|
+
if (kind === 'text') {
|
|
40
|
+
throw new Error(`CONFIG_FORMAT_UNSUPPORTED: ${filePath}`);
|
|
41
|
+
}
|
|
42
|
+
return (0, config_format_1.parseStructured)(kind, content);
|
|
43
|
+
};
|
|
40
44
|
let source;
|
|
41
45
|
try {
|
|
42
46
|
source = parse(sourcePath, await promises_1.default.readFile(sourcePath, 'utf8'));
|
|
@@ -81,11 +85,12 @@ async function unmergeDataFile(sourcePath, toPath, mergeKeys) {
|
|
|
81
85
|
}
|
|
82
86
|
}
|
|
83
87
|
if (removed.length > 0) {
|
|
84
|
-
|
|
85
|
-
|
|
88
|
+
const kind = (0, config_format_1.kindFromPath)(toPath);
|
|
89
|
+
if (kind === 'json' || kind === 'text') {
|
|
90
|
+
await (0, fs_1.writeJsonFile)(toPath, target);
|
|
86
91
|
}
|
|
87
92
|
else {
|
|
88
|
-
await (0, fs_1.
|
|
93
|
+
await (0, fs_1.writeTextFile)(toPath, (0, config_format_1.stringifyStructured)(kind, target));
|
|
89
94
|
}
|
|
90
95
|
}
|
|
91
96
|
return removed;
|