@worktool/dsh-config-sync 0.0.0-stage → 1.1.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/LICENSE +21 -0
- package/README.md +92 -2
- package/assets/icon.svg +14 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +27 -0
- package/lib/client.js +377 -0
- package/lib/index.js +1027 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +61 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,1027 @@
|
|
|
1
|
+
import { readFile, writeFile, mkdir, readdir, rm, cp, copyFile, access, stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
const execFileP = promisify(execFile);
|
|
9
|
+
|
|
10
|
+
export const name = "config-sync";
|
|
11
|
+
export const inject = ["connection", "pluginManager", "tools"];
|
|
12
|
+
|
|
13
|
+
const TOOL_ID = "@worktool/dsh-config-sync";
|
|
14
|
+
const PKG_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
15
|
+
async function toolVersion() {
|
|
16
|
+
const j = await readJson(path.join(PKG_ROOT, "package.json"), null);
|
|
17
|
+
return j && typeof j.version === "string" ? j.version : "0.0.0";
|
|
18
|
+
}
|
|
19
|
+
const API_PREFIX = "/api/worktool/dsh-config-sync";
|
|
20
|
+
const MARKER_HEADER = "x-dsh-config-sync";
|
|
21
|
+
const OFFICIAL_REGISTRY = "https://registry.npmjs.org/";
|
|
22
|
+
|
|
23
|
+
const HOME = os.homedir();
|
|
24
|
+
const DSH_HOME = process.env.DSH_HOME || path.join(HOME, ".dsh");
|
|
25
|
+
const PROFILE = process.env.DSH_PROFILE || "desktop";
|
|
26
|
+
const PROFILE_DIR = path.join(DSH_HOME, "profiles", PROFILE);
|
|
27
|
+
const STATE_DIR = path.join(DSH_HOME, "config-sync");
|
|
28
|
+
const REPO_DIR = path.join(STATE_DIR, "repo");
|
|
29
|
+
const BACKUP_DIR = path.join(STATE_DIR, "backups");
|
|
30
|
+
const STATE_FILE = path.join(STATE_DIR, "state.json");
|
|
31
|
+
|
|
32
|
+
// 只把「密钥类」键名视为敏感。注意排除 maxTokens / contextWindow 这类普通参数:
|
|
33
|
+
// 用「整词等于/前缀/后缀」判断,maxTokens → "maxtokens" 不以 token 结尾、也不以之开头,故不会被误清空。
|
|
34
|
+
const SECRET_WORDS = ["apikey", "secret", "token", "password", "passwd", "authorization", "bearer", "privatekey", "accesskey", "credential"];
|
|
35
|
+
function isSecretKey(key) {
|
|
36
|
+
const k = String(key).toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
37
|
+
if (!k) return false;
|
|
38
|
+
return SECRET_WORDS.some((w) => k === w || k.startsWith(w) || k.endsWith(w));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const DEFAULT_INCLUDE = {
|
|
42
|
+
settings: true,
|
|
43
|
+
agents: true,
|
|
44
|
+
presets: true,
|
|
45
|
+
skills: true,
|
|
46
|
+
plugins: true,
|
|
47
|
+
optional: false,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const ALWAYS_EXCLUDED = [
|
|
51
|
+
".credentials.yaml",
|
|
52
|
+
".env",
|
|
53
|
+
"mcp_connector_grants/",
|
|
54
|
+
"storages/ (运行时状态)",
|
|
55
|
+
"sessions/",
|
|
56
|
+
"cache/",
|
|
57
|
+
"attachments/",
|
|
58
|
+
"node_modules/",
|
|
59
|
+
"pnpm-lock.yaml",
|
|
60
|
+
"*.log",
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
/* ------------------------------------------------------------------ utils */
|
|
64
|
+
|
|
65
|
+
async function exists(p) {
|
|
66
|
+
try {
|
|
67
|
+
await access(p);
|
|
68
|
+
return true;
|
|
69
|
+
} catch {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function readJson(file, fallback) {
|
|
75
|
+
try {
|
|
76
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
77
|
+
} catch {
|
|
78
|
+
return fallback;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function writeJson(file, obj) {
|
|
83
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
84
|
+
await writeFile(file, JSON.stringify(obj, null, 2) + "\n", "utf8");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function loadState() {
|
|
88
|
+
const s = await readJson(STATE_FILE, {});
|
|
89
|
+
return {
|
|
90
|
+
repoUrl: s.repoUrl || "",
|
|
91
|
+
branch: s.branch || "main",
|
|
92
|
+
include: { ...DEFAULT_INCLUDE, ...(s.include || {}) },
|
|
93
|
+
lastSync: s.lastSync || null,
|
|
94
|
+
lastBackup: s.lastBackup || null,
|
|
95
|
+
// 已成功推送过的仓库地址:{ "<url>": { at, branch } },命中则跳过公开性探测
|
|
96
|
+
trustedRepos: s.trustedRepos && typeof s.trustedRepos === "object" ? s.trustedRepos : {},
|
|
97
|
+
// 严格模式:公开性无法判定(网络受限等)时也要求确认
|
|
98
|
+
strictPublic: !!s.strictPublic,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function saveState(patch) {
|
|
103
|
+
const cur = await loadState();
|
|
104
|
+
const next = { ...cur, ...patch };
|
|
105
|
+
await writeJson(STATE_FILE, next);
|
|
106
|
+
return next;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function copyDir(src, dst, skip = ["node_modules", ".git"]) {
|
|
110
|
+
if (!(await exists(src))) return 0;
|
|
111
|
+
let count = 0;
|
|
112
|
+
await mkdir(dst, { recursive: true });
|
|
113
|
+
const entries = await readdir(src, { withFileTypes: true });
|
|
114
|
+
for (const e of entries) {
|
|
115
|
+
if (skip.includes(e.name)) continue;
|
|
116
|
+
const s = path.join(src, e.name);
|
|
117
|
+
const d = path.join(dst, e.name);
|
|
118
|
+
if (e.isDirectory()) {
|
|
119
|
+
count += await copyDir(s, d, skip);
|
|
120
|
+
} else if (e.isFile()) {
|
|
121
|
+
await mkdir(path.dirname(d), { recursive: true });
|
|
122
|
+
await copyFile(s, d);
|
|
123
|
+
count += 1;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return count;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function countFiles(dir) {
|
|
130
|
+
if (!(await exists(dir))) return 0;
|
|
131
|
+
let n = 0;
|
|
132
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
133
|
+
for (const e of entries) {
|
|
134
|
+
if (e.isDirectory()) n += await countFiles(path.join(dir, e.name));
|
|
135
|
+
else if (e.isFile()) n += 1;
|
|
136
|
+
}
|
|
137
|
+
return n;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* 从 AGENTS.md 提取被引用的本地文件(如 ~/.dsh/drawio-rules.md),供导出/备份/还原 */
|
|
141
|
+
// 始终排除的目录(有专门导出逻辑或属运行时,不适合走引用复制)
|
|
142
|
+
const LINKED_SKIP_BASE = new Set([
|
|
143
|
+
"profiles", "storages", "sessions", "cache", "attachments",
|
|
144
|
+
"node_modules", "config-sync", "mcp_connector_grants",
|
|
145
|
+
]);
|
|
146
|
+
const LINKED_BLOCK_BASENAME = new Set([".credentials.yaml", ".env", "settings.yaml", "AGENTS.md", "pnpm-lock.yaml"]);
|
|
147
|
+
function extractLinkedFiles(text, opts = {}) {
|
|
148
|
+
// skills / agent-presets 只在「对应专门导出开着」时才跳过(避免重复);
|
|
149
|
+
// 关掉那些开关时不再跳过,用 config/linked/ 兜底带上被引用的文件。
|
|
150
|
+
const skip = new Set(LINKED_SKIP_BASE);
|
|
151
|
+
if (opts.skipSkills !== false) skip.add("skills");
|
|
152
|
+
if (opts.skipPresets !== false) skip.add(".agent-presets");
|
|
153
|
+
const found = new Set();
|
|
154
|
+
const add = (rel) => {
|
|
155
|
+
if (!rel) return;
|
|
156
|
+
rel = String(rel).trim().replace(/[?#].*$/, "");
|
|
157
|
+
if (!rel || rel.startsWith("/") || rel.startsWith("~")) return;
|
|
158
|
+
if (rel.split("/").some((s) => s === ".." || s === "" || s === ".")) return;
|
|
159
|
+
const top = rel.split("/")[0];
|
|
160
|
+
if (skip.has(top)) return;
|
|
161
|
+
if (LINKED_BLOCK_BASENAME.has(path.basename(rel))) return;
|
|
162
|
+
found.add(rel);
|
|
163
|
+
};
|
|
164
|
+
let m;
|
|
165
|
+
// 形式一:~/.dsh/<path>
|
|
166
|
+
const reTilde = /~\/\.dsh\/([A-Za-z0-9_][A-Za-z0-9_./-]*)/g;
|
|
167
|
+
while ((m = reTilde.exec(text))) add(m[1].replace(/[.,;:)\]}'"`]+$/, ""));
|
|
168
|
+
// 形式二:Markdown 相对链接(非 http / # / 绝对路径)
|
|
169
|
+
const reLink = /\]\(([^)\s]+)\)/g;
|
|
170
|
+
while ((m = reLink.exec(text))) {
|
|
171
|
+
const u = m[1];
|
|
172
|
+
if (/^(?:https?:|mailto:|#|\/)/i.test(u)) continue;
|
|
173
|
+
if (/\.[A-Za-z0-9]{1,8}$/.test(u)) add(u);
|
|
174
|
+
}
|
|
175
|
+
return [...found];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function sanitizeYaml(text) {
|
|
179
|
+
let redactions = 0;
|
|
180
|
+
const out = text.split(/\r?\n/).map((line) => {
|
|
181
|
+
const m = line.match(/^(\s*)([A-Za-z0-9_.\-]+)\s*:\s*(.*)$/);
|
|
182
|
+
if (!m) return line;
|
|
183
|
+
const key = m[2];
|
|
184
|
+
if (/env$/i.test(key)) return line; // e.g. apiKeyEnv — 只是环境变量名
|
|
185
|
+
if (!isSecretKey(key)) return line;
|
|
186
|
+
const val = m[3].trim();
|
|
187
|
+
if (isBlankYamlValue(val)) return line;
|
|
188
|
+
redactions += 1;
|
|
189
|
+
return `${m[1]}${m[2]}: ""`;
|
|
190
|
+
}).join("\n");
|
|
191
|
+
return { text: out, redactions };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/* 导入时:把导出包里被脱敏成空串的密钥字段,用本机已有值补回,避免覆盖丢密钥 */
|
|
195
|
+
function isBlankYamlValue(v) {
|
|
196
|
+
const t = String(v == null ? "" : v).trim();
|
|
197
|
+
return t === "" || t === '""' || t === "''" || t === "~" || t === "null";
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function extractSecretValues(text) {
|
|
201
|
+
const map = new Map();
|
|
202
|
+
for (const line of text.split(/\r?\n/)) {
|
|
203
|
+
const m = line.match(/^(\s*)([A-Za-z0-9_.\-]+)\s*:\s*(.*)$/);
|
|
204
|
+
if (!m) continue;
|
|
205
|
+
if (/env$/i.test(m[2])) continue;
|
|
206
|
+
if (!isSecretKey(m[2])) continue;
|
|
207
|
+
const val = m[3].trim();
|
|
208
|
+
if (!isBlankYamlValue(val)) map.set(m[2], val);
|
|
209
|
+
}
|
|
210
|
+
return map;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function mergeSettingsPreservingSecrets(existingText, incomingText) {
|
|
214
|
+
if (!existingText) return { text: incomingText, preserved: 0 };
|
|
215
|
+
const existing = extractSecretValues(existingText);
|
|
216
|
+
let preserved = 0;
|
|
217
|
+
const out = incomingText.split(/\r?\n/).map((line) => {
|
|
218
|
+
const m = line.match(/^(\s*)([A-Za-z0-9_.\-]+)\s*:\s*(.*)$/);
|
|
219
|
+
if (!m) return line;
|
|
220
|
+
if (/env$/i.test(m[2])) return line;
|
|
221
|
+
if (!isSecretKey(m[2])) return line;
|
|
222
|
+
const val = m[3].trim();
|
|
223
|
+
if (!isBlankYamlValue(val)) return line; // 导出包带了真实值,保留它的
|
|
224
|
+
const prev = existing.get(m[2]);
|
|
225
|
+
if (!prev) return line;
|
|
226
|
+
preserved += 1;
|
|
227
|
+
return `${m[1]}${m[2]}: ${prev}`;
|
|
228
|
+
}).join("\n");
|
|
229
|
+
return { text: out, preserved };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function installedVersion(pkgName) {
|
|
233
|
+
const p = path.join(PROFILE_DIR, "node_modules", pkgName, "package.json");
|
|
234
|
+
const j = await readJson(p, null);
|
|
235
|
+
return j && typeof j.version === "string" ? j.version : null;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function profilePlugins() {
|
|
239
|
+
const pkg = await readJson(path.join(PROFILE_DIR, "package.json"), {});
|
|
240
|
+
const bundles = (pkg && pkg.dsh && pkg.dsh.profile && pkg.dsh.profile.bundles) || [];
|
|
241
|
+
const deps = pkg.dependencies || {};
|
|
242
|
+
const list = [];
|
|
243
|
+
for (const name of bundles) {
|
|
244
|
+
const spec = typeof deps[name] === "string" ? deps[name] : null;
|
|
245
|
+
const local = !!(spec && (spec.startsWith("link:") || spec.startsWith("file:")));
|
|
246
|
+
const version = (await installedVersion(name)) || (spec && !local ? spec.replace(/^[^\d]*/, "") : null) || "unknown";
|
|
247
|
+
list.push({
|
|
248
|
+
name,
|
|
249
|
+
version,
|
|
250
|
+
spec,
|
|
251
|
+
local,
|
|
252
|
+
builtin: name.startsWith("@deepseek-ai/") || name.startsWith("dsh-"),
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return { pkg, deps, list };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function dshVersion() {
|
|
259
|
+
const candidates = [
|
|
260
|
+
process.env.DSH_VERSION,
|
|
261
|
+
path.join(DSH_HOME, "..", "package.json"),
|
|
262
|
+
].filter(Boolean);
|
|
263
|
+
for (const c of candidates) {
|
|
264
|
+
const j = await readJson(c, null);
|
|
265
|
+
if (j && typeof j.version === "string" && j.name && j.name.includes("dsh")) return j.version;
|
|
266
|
+
}
|
|
267
|
+
return "unknown";
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/* --------------------------------------------------------------- export */
|
|
271
|
+
|
|
272
|
+
async function buildExport(includeIn) {
|
|
273
|
+
const include = { ...DEFAULT_INCLUDE, ...(includeIn || {}) };
|
|
274
|
+
await mkdir(REPO_DIR, { recursive: true });
|
|
275
|
+
// 清掉上一次的包内容(保留 .git)
|
|
276
|
+
for (const p of ["manifest.json", "plugins.json", "redactions.json", "excluded.json", "config", "skills"]) {
|
|
277
|
+
await rm(path.join(REPO_DIR, p), { recursive: true, force: true });
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const counts = { files: 0, skills: 0, plugins: 0, redactions: 0, linked: 0 };
|
|
281
|
+
const redactionsList = [];
|
|
282
|
+
|
|
283
|
+
// settings.yaml(脱敏)
|
|
284
|
+
if (include.settings) {
|
|
285
|
+
const f = path.join(DSH_HOME, "settings.yaml");
|
|
286
|
+
if (await exists(f)) {
|
|
287
|
+
const raw = await readFile(f, "utf8");
|
|
288
|
+
const { text, redactions } = sanitizeYaml(raw);
|
|
289
|
+
await mkdir(path.join(REPO_DIR, "config"), { recursive: true });
|
|
290
|
+
await writeFile(path.join(REPO_DIR, "config", "settings.yaml"), text, "utf8");
|
|
291
|
+
counts.files += 1;
|
|
292
|
+
counts.redactions += redactions;
|
|
293
|
+
if (redactions) redactionsList.push({ file: "settings.yaml", fields: redactions });
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// 全局 AGENTS.md + 它引用的本地文件(如 ~/.dsh/drawio-rules.md)
|
|
298
|
+
let linkedCopied = [];
|
|
299
|
+
if (include.agents) {
|
|
300
|
+
const f = path.join(DSH_HOME, "AGENTS.md");
|
|
301
|
+
if (await exists(f)) {
|
|
302
|
+
await mkdir(path.join(REPO_DIR, "config"), { recursive: true });
|
|
303
|
+
await copyFile(f, path.join(REPO_DIR, "config", "AGENTS.md"));
|
|
304
|
+
counts.files += 1;
|
|
305
|
+
const text = await readFile(f, "utf8");
|
|
306
|
+
for (const rel of extractLinkedFiles(text, { skipSkills: include.skills, skipPresets: include.presets })) {
|
|
307
|
+
const src = path.join(DSH_HOME, rel);
|
|
308
|
+
if (!(await exists(src))) continue;
|
|
309
|
+
const st = await stat(src);
|
|
310
|
+
if (!st.isFile() || st.size > 2 * 1024 * 1024) continue;
|
|
311
|
+
const dst = path.join(REPO_DIR, "config", "linked", rel);
|
|
312
|
+
await mkdir(path.dirname(dst), { recursive: true });
|
|
313
|
+
await copyFile(src, dst);
|
|
314
|
+
linkedCopied.push(rel);
|
|
315
|
+
counts.files += 1;
|
|
316
|
+
}
|
|
317
|
+
counts.linked = linkedCopied.length;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// agent-presets
|
|
322
|
+
if (include.presets) {
|
|
323
|
+
const n = await copyDir(path.join(DSH_HOME, ".agent-presets"), path.join(REPO_DIR, "config", "agent-presets"));
|
|
324
|
+
counts.files += n;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// profile cordis 配置
|
|
328
|
+
for (const rel of ["cordis.patch.yml", "cordis.yml"]) {
|
|
329
|
+
const f = path.join(PROFILE_DIR, rel);
|
|
330
|
+
if (await exists(f)) {
|
|
331
|
+
const dst = path.join(REPO_DIR, "config", "profile", rel);
|
|
332
|
+
await mkdir(path.dirname(dst), { recursive: true });
|
|
333
|
+
await copyFile(f, dst);
|
|
334
|
+
counts.files += 1;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// skills
|
|
339
|
+
if (include.skills) {
|
|
340
|
+
const n = await copyDir(path.join(DSH_HOME, "skills"), path.join(REPO_DIR, "skills"));
|
|
341
|
+
counts.skills = n;
|
|
342
|
+
counts.files += n;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// 插件清单
|
|
346
|
+
if (include.plugins) {
|
|
347
|
+
const info = await profilePlugins();
|
|
348
|
+
const payload = {
|
|
349
|
+
generatedAt: new Date().toISOString(),
|
|
350
|
+
profile: PROFILE,
|
|
351
|
+
bundles: info.list,
|
|
352
|
+
local: info.list.filter((p) => p.local).map((p) => p.name),
|
|
353
|
+
};
|
|
354
|
+
await writeJson(path.join(REPO_DIR, "plugins.json"), payload);
|
|
355
|
+
counts.plugins = info.list.length;
|
|
356
|
+
counts.files += 1;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// 可选:环境/主题类
|
|
360
|
+
if (include.optional) {
|
|
361
|
+
const f = path.join(DSH_HOME, "dream-skin.json");
|
|
362
|
+
if (await exists(f)) {
|
|
363
|
+
await copyFile(f, path.join(REPO_DIR, "config", "dream-skin.json"));
|
|
364
|
+
counts.files += 1;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// 脱敏与被排除清单
|
|
369
|
+
await writeJson(path.join(REPO_DIR, "redactions.json"), { generatedAt: new Date().toISOString(), entries: redactionsList });
|
|
370
|
+
await writeJson(path.join(REPO_DIR, "excluded.json"), { note: "以下内容永不进入同步包", patterns: ALWAYS_EXCLUDED });
|
|
371
|
+
counts.files += 2;
|
|
372
|
+
|
|
373
|
+
// manifest
|
|
374
|
+
const manifest = {
|
|
375
|
+
schema: 1,
|
|
376
|
+
exportedAt: new Date().toISOString(),
|
|
377
|
+
dshVersion: await dshVersion(),
|
|
378
|
+
tool: TOOL_ID,
|
|
379
|
+
toolVersion: await toolVersion(),
|
|
380
|
+
profile: PROFILE,
|
|
381
|
+
include,
|
|
382
|
+
counts,
|
|
383
|
+
linked: linkedCopied,
|
|
384
|
+
};
|
|
385
|
+
await writeJson(path.join(REPO_DIR, "manifest.json"), manifest);
|
|
386
|
+
counts.files += 1;
|
|
387
|
+
|
|
388
|
+
return { dir: REPO_DIR, manifest, counts };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/* --------------------------------------------------------------- import */
|
|
392
|
+
|
|
393
|
+
async function backupCurrent() {
|
|
394
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
395
|
+
const dir = path.join(BACKUP_DIR, stamp);
|
|
396
|
+
await mkdir(dir, { recursive: true });
|
|
397
|
+
const files = ["settings.yaml", "AGENTS.md"];
|
|
398
|
+
for (const f of files) {
|
|
399
|
+
const src = path.join(DSH_HOME, f);
|
|
400
|
+
if (await exists(src)) await copyFile(src, path.join(dir, f));
|
|
401
|
+
}
|
|
402
|
+
await copyDir(path.join(DSH_HOME, ".agent-presets"), path.join(dir, ".agent-presets"));
|
|
403
|
+
await copyDir(path.join(DSH_HOME, "skills"), path.join(dir, "skills"));
|
|
404
|
+
for (const rel of ["cordis.patch.yml", "cordis.yml", "package.json"]) {
|
|
405
|
+
const src = path.join(PROFILE_DIR, rel);
|
|
406
|
+
if (await exists(src)) await copyFile(src, path.join(dir, "profile-" + rel));
|
|
407
|
+
}
|
|
408
|
+
// 备份 AGENTS.md 当前引用的本地文件(如 drawio-rules.md),防止导入覆盖丢失
|
|
409
|
+
const agentsFile = path.join(DSH_HOME, "AGENTS.md");
|
|
410
|
+
if (await exists(agentsFile)) {
|
|
411
|
+
const t = await readFile(agentsFile, "utf8");
|
|
412
|
+
for (const rel of extractLinkedFiles(t, { skipSkills: false, skipPresets: false })) {
|
|
413
|
+
const src = path.join(DSH_HOME, rel);
|
|
414
|
+
try {
|
|
415
|
+
if ((await stat(src)).isFile()) {
|
|
416
|
+
const dst = path.join(dir, "linked", rel);
|
|
417
|
+
await mkdir(path.dirname(dst), { recursive: true });
|
|
418
|
+
await copyFile(src, dst);
|
|
419
|
+
}
|
|
420
|
+
} catch { /* ignore */ }
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return dir;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function importPackage(dirIn, opts, ctx) {
|
|
427
|
+
const srcDir = dirIn || REPO_DIR;
|
|
428
|
+
const manifest = await readJson(path.join(srcDir, "manifest.json"), null);
|
|
429
|
+
if (!manifest || manifest.schema !== 1) {
|
|
430
|
+
throw Object.assign(new Error("非法或缺失的 manifest.json(需要 schema:1)"), { statusCode: 400, code: "error.badManifest" });
|
|
431
|
+
}
|
|
432
|
+
const backup = await backupCurrent();
|
|
433
|
+
await saveState({ lastBackup: backup });
|
|
434
|
+
|
|
435
|
+
const report = {
|
|
436
|
+
backup,
|
|
437
|
+
plugins: { installed: [], updated: [], skipped: [], failed: [] },
|
|
438
|
+
config: [],
|
|
439
|
+
skills: [],
|
|
440
|
+
needsRestart: false,
|
|
441
|
+
conflicts: [],
|
|
442
|
+
secretsPreserved: 0,
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
// 1) 插件
|
|
446
|
+
if (manifest.include ? manifest.include.plugins !== false : true) {
|
|
447
|
+
const pj = await readJson(path.join(srcDir, "plugins.json"), { bundles: [] });
|
|
448
|
+
for (const p of pj.bundles || []) {
|
|
449
|
+
if (p.builtin) {
|
|
450
|
+
report.plugins.skipped.push({ name: p.name, reason: "builtin" });
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
if (p.local) {
|
|
454
|
+
report.plugins.skipped.push({ name: p.name, reason: "local/link 插件需手动安装" });
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
const want = p.version && p.version !== "unknown" ? p.version : null;
|
|
458
|
+
const have = await installedVersion(p.name);
|
|
459
|
+
if (want && have === want) {
|
|
460
|
+
report.plugins.skipped.push({ name: p.name, reason: "already " + want });
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
const spec = want ? `${p.name}@${want}` : p.name;
|
|
464
|
+
try {
|
|
465
|
+
if (have && want && ctx.pluginManager) {
|
|
466
|
+
await ctx.pluginManager.updateBundle(p.name, want, { registry: OFFICIAL_REGISTRY });
|
|
467
|
+
report.plugins.updated.push({ name: p.name, from: have, to: want });
|
|
468
|
+
} else if (ctx.pluginManager) {
|
|
469
|
+
await ctx.pluginManager.installBundle(spec, { registry: OFFICIAL_REGISTRY });
|
|
470
|
+
report.plugins.installed.push({ name: p.name, version: want || "latest" });
|
|
471
|
+
} else {
|
|
472
|
+
report.plugins.failed.push({ name: p.name, error: "pluginManager 服务不可用" });
|
|
473
|
+
}
|
|
474
|
+
report.needsRestart = true;
|
|
475
|
+
} catch (e1) {
|
|
476
|
+
try {
|
|
477
|
+
await ctx.pluginManager.installBundle(spec);
|
|
478
|
+
report.plugins.installed.push({ name: p.name, version: want || "latest", note: "fallback registry" });
|
|
479
|
+
report.needsRestart = true;
|
|
480
|
+
} catch (e2) {
|
|
481
|
+
report.plugins.failed.push({ name: p.name, error: String((e2 && e2.message) || e1) });
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// 2) 配置
|
|
488
|
+
const cfgDir = path.join(srcDir, "config");
|
|
489
|
+
if (await exists(path.join(cfgDir, "settings.yaml"))) {
|
|
490
|
+
const incoming = await readFile(path.join(cfgDir, "settings.yaml"), "utf8");
|
|
491
|
+
const target = path.join(DSH_HOME, "settings.yaml");
|
|
492
|
+
let text = incoming;
|
|
493
|
+
if (await exists(target)) {
|
|
494
|
+
const merged = mergeSettingsPreservingSecrets(await readFile(target, "utf8"), incoming);
|
|
495
|
+
text = merged.text;
|
|
496
|
+
report.secretsPreserved = merged.preserved;
|
|
497
|
+
}
|
|
498
|
+
await writeFile(target, text, "utf8");
|
|
499
|
+
report.config.push("settings.yaml" + (report.secretsPreserved ? `(保留本机密钥 ${report.secretsPreserved} 项)` : ""));
|
|
500
|
+
report.needsRestart = true;
|
|
501
|
+
}
|
|
502
|
+
if (await exists(path.join(cfgDir, "AGENTS.md"))) {
|
|
503
|
+
await copyFile(path.join(cfgDir, "AGENTS.md"), path.join(DSH_HOME, "AGENTS.md"));
|
|
504
|
+
report.config.push("AGENTS.md");
|
|
505
|
+
}
|
|
506
|
+
// AGENTS.md 引用的本地文件(drawio-rules.md 等)
|
|
507
|
+
if (await exists(path.join(cfgDir, "linked"))) {
|
|
508
|
+
const n = await copyDir(path.join(cfgDir, "linked"), DSH_HOME);
|
|
509
|
+
if (n) report.config.push(`AGENTS 引用文件 (${n})`);
|
|
510
|
+
}
|
|
511
|
+
if (await exists(path.join(cfgDir, "agent-presets"))) {
|
|
512
|
+
const n = await copyDir(path.join(cfgDir, "agent-presets"), path.join(DSH_HOME, ".agent-presets"));
|
|
513
|
+
report.config.push(`agent-presets (${n} files)`);
|
|
514
|
+
}
|
|
515
|
+
const profSrc = path.join(cfgDir, "profile");
|
|
516
|
+
for (const rel of ["cordis.patch.yml", "cordis.yml"]) {
|
|
517
|
+
const s = path.join(profSrc, rel);
|
|
518
|
+
if (await exists(s)) {
|
|
519
|
+
await copyFile(s, path.join(PROFILE_DIR, rel));
|
|
520
|
+
report.config.push("profile/" + rel);
|
|
521
|
+
report.needsRestart = true;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
if (await exists(path.join(cfgDir, "dream-skin.json"))) {
|
|
525
|
+
await copyFile(path.join(cfgDir, "dream-skin.json"), path.join(DSH_HOME, "dream-skin.json"));
|
|
526
|
+
report.config.push("dream-skin.json");
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// 3) skills
|
|
530
|
+
const skillsSrc = path.join(srcDir, "skills");
|
|
531
|
+
if (await exists(skillsSrc)) {
|
|
532
|
+
const entries = await readdir(skillsSrc, { withFileTypes: true });
|
|
533
|
+
for (const e of entries) {
|
|
534
|
+
if (!e.isDirectory()) continue;
|
|
535
|
+
const dst = path.join(DSH_HOME, "skills", e.name);
|
|
536
|
+
if (await exists(dst)) report.conflicts.push({ skill: e.name, action: "overwritten" });
|
|
537
|
+
await copyDir(path.join(skillsSrc, e.name), dst);
|
|
538
|
+
report.skills.push(e.name);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
report.needsRestart = report.needsRestart || report.config.length > 0 || report.skills.length > 0;
|
|
543
|
+
return report;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/* ------------------------------------------------------------------ git */
|
|
547
|
+
|
|
548
|
+
function gitEnv() {
|
|
549
|
+
return {
|
|
550
|
+
...process.env,
|
|
551
|
+
GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND || "ssh -o StrictHostKeyChecking=no -o BatchMode=yes",
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
async function runGit(args) {
|
|
556
|
+
return execFileP("git", args, { cwd: REPO_DIR, env: gitEnv(), maxBuffer: 1024 * 1024 * 32 });
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** 从各种 Git 地址推导出「可匿名探测」的候选地址。
|
|
560
|
+
* - http(s)/git://:直接探测;
|
|
561
|
+
* - ssh:// 与非标准 scp 形式:仅在能可靠映射为 https 时才探测(ssh 非 22 端口不盲目转换);
|
|
562
|
+
* - 探测前一律剥离地址中的 user:pass@,避免带着凭据把私有仓库误判成公开。 */
|
|
563
|
+
export function probeCandidates(repoUrl) {
|
|
564
|
+
const out = [];
|
|
565
|
+
const u = String(repoUrl || "").trim();
|
|
566
|
+
if (!u) return out;
|
|
567
|
+
const add = (url) => { if (url) out.push({ url }); };
|
|
568
|
+
if (/^https?:\/\//i.test(u)) {
|
|
569
|
+
try {
|
|
570
|
+
const x = new URL(u);
|
|
571
|
+
add(`${x.protocol}//${x.host}${x.pathname}${x.search}`);
|
|
572
|
+
} catch {
|
|
573
|
+
add(u.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]*@/i, "$1"));
|
|
574
|
+
}
|
|
575
|
+
return out;
|
|
576
|
+
}
|
|
577
|
+
if (/^git:\/\//i.test(u)) { add(u); return out; }
|
|
578
|
+
if (/^ssh:\/\//i.test(u)) {
|
|
579
|
+
try {
|
|
580
|
+
const x = new URL(u);
|
|
581
|
+
const port = x.port ? Number(x.port) : 22;
|
|
582
|
+
if (port === 22) add(`https://${x.hostname}${x.pathname}`);
|
|
583
|
+
} catch {
|
|
584
|
+
const m = u.match(/^ssh:\/\/(?:[^@\/]+@)?([^\/:]+)(?::(\d+))?\/(.+)$/i);
|
|
585
|
+
if (m) {
|
|
586
|
+
const port = m[2] ? Number(m[2]) : 22;
|
|
587
|
+
if (port === 22) add(`https://${m[1]}/${m[3]}`);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
return out;
|
|
591
|
+
}
|
|
592
|
+
let m = u.match(/^[A-Za-z0-9._-]+@([^:\/]+):(.+)$/);
|
|
593
|
+
if (m) { add(`https://${m[1]}/${m[2]}`); return out; }
|
|
594
|
+
return out;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** 归类 git 失败信息:auth=需要凭据/不存在;network=网络/可达性;other=其他。 */
|
|
598
|
+
export function classifyGitFailure(stderr) {
|
|
599
|
+
const s = String(stderr || "").toLowerCase();
|
|
600
|
+
if (/authentication failed|could not read (username|password)|permission denied|access denied|invalid username|terminal prompts disabled|\b401\b|\b403\b|repository not found|not found|does not appear to be a git repository/.test(s)) {
|
|
601
|
+
return "auth";
|
|
602
|
+
}
|
|
603
|
+
if (/could not resolve|name or service not known|temporary failure in name resolution|network is unreachable|connection timed out|timed out|connection refused|unable to access|ssl|tls|proxy/.test(s)) {
|
|
604
|
+
return "network";
|
|
605
|
+
}
|
|
606
|
+
return "other";
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** 匿名探测仓库是否可公开读取(不带任何凭据):
|
|
610
|
+
* - 匿名 ls-remote 成功 → public:true, checked:true
|
|
611
|
+
* - 明确需要凭据/不存在 → public:false, checked:true(可信为私有)
|
|
612
|
+
* - 网络受限/无法判定 → public:false, checked:false(严格模式下会被要求确认) */
|
|
613
|
+
export async function probePublicRepo(repoUrl) {
|
|
614
|
+
const u = String(repoUrl || "").trim();
|
|
615
|
+
if (!u) return { public: false, checked: false, reason: "empty" };
|
|
616
|
+
const cands = probeCandidates(u);
|
|
617
|
+
if (!cands.length) {
|
|
618
|
+
const reason = /^ssh:\/\//i.test(u)
|
|
619
|
+
? "ssh 非标准端口/路径,无法自动转换探测"
|
|
620
|
+
: "非 http/git/标准 ssh 地址,无法匿名探测";
|
|
621
|
+
return { public: false, checked: false, reason };
|
|
622
|
+
}
|
|
623
|
+
let sawAuth = false;
|
|
624
|
+
let lastErr = "";
|
|
625
|
+
for (const c of cands) {
|
|
626
|
+
try {
|
|
627
|
+
await execFileP("git", ["-c", "credential.helper=", "ls-remote", "--heads", c.url], {
|
|
628
|
+
timeout: 8000,
|
|
629
|
+
env: {
|
|
630
|
+
...process.env,
|
|
631
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
632
|
+
GIT_ASKPASS: "/usr/bin/true",
|
|
633
|
+
GIT_SSH_COMMAND: "ssh -o BatchMode=yes -o StrictHostKeyChecking=no",
|
|
634
|
+
},
|
|
635
|
+
});
|
|
636
|
+
return { public: true, checked: true, via: c.url, method: "ls-remote" };
|
|
637
|
+
} catch (e) {
|
|
638
|
+
lastErr = String((e && e.stderr) || (e && e.message) || "");
|
|
639
|
+
if (classifyGitFailure(lastErr) === "auth") sawAuth = true;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
if (sawAuth) return { public: false, checked: true, reason: "需凭据访问(私有或不存在)", detail: lastErr.slice(0, 200) };
|
|
643
|
+
return { public: false, checked: false, reason: "无法匿名探测(网络受限或地址不可达)", detail: lastErr.slice(0, 200) };
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async function ensureRepo(repoUrl, branch) {
|
|
647
|
+
await mkdir(REPO_DIR, { recursive: true });
|
|
648
|
+
if (!(await exists(path.join(REPO_DIR, ".git")))) {
|
|
649
|
+
try {
|
|
650
|
+
await runGit(["init", "-b", branch || "main"]);
|
|
651
|
+
} catch {
|
|
652
|
+
await runGit(["init"]);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
// 确保有提交身份(仅在本仓库缺省时补,不覆盖全局配置)
|
|
656
|
+
try {
|
|
657
|
+
await runGit(["config", "user.email"]);
|
|
658
|
+
} catch {
|
|
659
|
+
await runGit(["config", "user.email", "dsh-config-sync@localhost"]).catch(() => {});
|
|
660
|
+
await runGit(["config", "user.name", "dsh-config-sync"]).catch(() => {});
|
|
661
|
+
}
|
|
662
|
+
if (repoUrl) {
|
|
663
|
+
try {
|
|
664
|
+
await runGit(["remote", "remove", "origin"]);
|
|
665
|
+
} catch {
|
|
666
|
+
/* no remote */
|
|
667
|
+
}
|
|
668
|
+
try {
|
|
669
|
+
await runGit(["remote", "add", "origin", repoUrl]);
|
|
670
|
+
} catch (e) {
|
|
671
|
+
throw Object.assign(new Error("设置远端仓库失败: " + String((e && e.stderr) || e)), { statusCode: 400 });
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
async function pushRepo(repoUrl, branch, includeIn, opts = {}) {
|
|
677
|
+
const br = branch || "main";
|
|
678
|
+
const st0 = await loadState();
|
|
679
|
+
const effectiveUrl = String(repoUrl || st0.repoUrl || "").trim();
|
|
680
|
+
const trusted = st0.trustedRepos || {};
|
|
681
|
+
const strict = !!st0.strictPublic;
|
|
682
|
+
// 只对「从未成功推送过的地址」做公开性探测;同一地址首次成功后不再探测
|
|
683
|
+
if (effectiveUrl && !trusted[effectiveUrl]) {
|
|
684
|
+
const probe = await probePublicRepo(effectiveUrl).catch(() => ({ public: false, checked: false }));
|
|
685
|
+
// 严格模式:无法判定(checked=false,如网络受限)也视为需确认,避免把未知当成私有直接外泄
|
|
686
|
+
const confirmNeeded = !!probe.public || (strict && probe.checked === false);
|
|
687
|
+
if (confirmNeeded && !opts.allowPublic) {
|
|
688
|
+
throw Object.assign(
|
|
689
|
+
new Error(probe.public ? "目标仓库可被公开匿名访问,需确认后才能推送" : "无法确认仓库是否公开(严格模式),需确认后才能推送"),
|
|
690
|
+
{
|
|
691
|
+
statusCode: 409,
|
|
692
|
+
code: "error.publicRepoConfirm",
|
|
693
|
+
data: { public: !!probe.public, unknown: probe.checked === false, checked: !!probe.checked, url: effectiveUrl, via: probe.via, reason: probe.reason },
|
|
694
|
+
}
|
|
695
|
+
);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
await ensureRepo(effectiveUrl, br);
|
|
699
|
+
const exp = await buildExport(includeIn);
|
|
700
|
+
await runGit(["add", "-A"]);
|
|
701
|
+
let committed = true;
|
|
702
|
+
try {
|
|
703
|
+
await runGit(["commit", "-m", `config-sync: ${new Date().toISOString()}`]);
|
|
704
|
+
} catch (e) {
|
|
705
|
+
committed = false; // nothing to commit
|
|
706
|
+
}
|
|
707
|
+
try {
|
|
708
|
+
await runGit(["branch", "-M", br]);
|
|
709
|
+
} catch {
|
|
710
|
+
/* ignore */
|
|
711
|
+
}
|
|
712
|
+
try {
|
|
713
|
+
const out = await runGit(["push", "-u", "origin", br]);
|
|
714
|
+
const now = new Date().toISOString();
|
|
715
|
+
const trusted2 = { ...(st0.trustedRepos || {}) };
|
|
716
|
+
if (effectiveUrl) trusted2[effectiveUrl] = { at: now, branch: br };
|
|
717
|
+
await saveState({ repoUrl: effectiveUrl, branch: br, lastSync: now, trustedRepos: trusted2 });
|
|
718
|
+
return { ok: true, counts: exp.counts, committed, push: (out.stderr || out.stdout || "").trim(), at: now };
|
|
719
|
+
} catch (e) {
|
|
720
|
+
throw Object.assign(new Error("git push 失败: " + String((e && e.stderr) || e)), { statusCode: 502, stage: "push" });
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
async function pullRepo(repoUrl, branch, ctx) {
|
|
725
|
+
const br = branch || "main";
|
|
726
|
+
await ensureRepo(repoUrl, br);
|
|
727
|
+
try {
|
|
728
|
+
await runGit(["fetch", "origin", br]);
|
|
729
|
+
await runGit(["reset", "--hard", `origin/${br}`]);
|
|
730
|
+
} catch (e) {
|
|
731
|
+
throw Object.assign(new Error("git 拉取失败: " + String((e && e.stderr) || e)), { statusCode: 502, stage: "pull" });
|
|
732
|
+
}
|
|
733
|
+
const imp = await importPackage(REPO_DIR, {}, ctx);
|
|
734
|
+
await saveState({ repoUrl: repoUrl || (await loadState()).repoUrl, branch: br, lastSync: new Date().toISOString() });
|
|
735
|
+
return { ok: true, import: imp };
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/* --------------------------------------------------------------- status */
|
|
739
|
+
|
|
740
|
+
async function getStatus() {
|
|
741
|
+
const st = await loadState();
|
|
742
|
+
const info = await profilePlugins().catch(() => ({ list: [] }));
|
|
743
|
+
return {
|
|
744
|
+
dshHome: DSH_HOME,
|
|
745
|
+
profile: PROFILE,
|
|
746
|
+
profileDir: PROFILE_DIR,
|
|
747
|
+
repoDir: REPO_DIR,
|
|
748
|
+
repoUrl: st.repoUrl,
|
|
749
|
+
branch: st.branch,
|
|
750
|
+
include: st.include,
|
|
751
|
+
lastSync: st.lastSync,
|
|
752
|
+
lastBackup: st.lastBackup,
|
|
753
|
+
strictPublic: !!st.strictPublic,
|
|
754
|
+
pluginCount: info.list.length,
|
|
755
|
+
skillsCount: await countFiles(path.join(DSH_HOME, "skills")),
|
|
756
|
+
excluded: ALWAYS_EXCLUDED,
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/* -------------------------------------------------------------- http api */
|
|
761
|
+
|
|
762
|
+
function jsonResponse(code, payload) {
|
|
763
|
+
const body = JSON.stringify(payload);
|
|
764
|
+
return new Response(body, {
|
|
765
|
+
status: code,
|
|
766
|
+
headers: {
|
|
767
|
+
"content-type": "application/json; charset=utf-8",
|
|
768
|
+
"cache-control": "no-store",
|
|
769
|
+
"content-length": String(Buffer.byteLength(body)),
|
|
770
|
+
},
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
async function readBody(req) {
|
|
775
|
+
const t = await req.text();
|
|
776
|
+
if (!t.trim()) return {};
|
|
777
|
+
try {
|
|
778
|
+
return JSON.parse(t);
|
|
779
|
+
} catch {
|
|
780
|
+
return {};
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function mutationGuard(req) {
|
|
785
|
+
if (req.headers.get(MARKER_HEADER) !== "1") {
|
|
786
|
+
return { statusCode: 403, error: "缺少 " + MARKER_HEADER + " 头" };
|
|
787
|
+
}
|
|
788
|
+
return null;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function registerRoutes(ctx) {
|
|
792
|
+
if (!ctx.connection || !ctx.connection.fetch || typeof ctx.connection.fetch.register !== "function") {
|
|
793
|
+
ctx.logger?.warn?.("config-sync: 需要 connection.fetch 才能注册路由");
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const routes = [
|
|
797
|
+
{
|
|
798
|
+
path: `${API_PREFIX}/state`,
|
|
799
|
+
methods: ["GET"],
|
|
800
|
+
fetch: async () => {
|
|
801
|
+
try {
|
|
802
|
+
return jsonResponse(200, { ok: true, data: await getStatus() });
|
|
803
|
+
} catch (e) {
|
|
804
|
+
return jsonResponse(500, { ok: false, error: String(e && e.message) });
|
|
805
|
+
}
|
|
806
|
+
},
|
|
807
|
+
},
|
|
808
|
+
{
|
|
809
|
+
path: `${API_PREFIX}/export`,
|
|
810
|
+
methods: ["POST"],
|
|
811
|
+
fetch: async (req) => {
|
|
812
|
+
const g = mutationGuard(req);
|
|
813
|
+
if (g) return jsonResponse(g.statusCode, { ok: false, error: g.error });
|
|
814
|
+
try {
|
|
815
|
+
const body = await readBody(req);
|
|
816
|
+
const r = await buildExport(body.include);
|
|
817
|
+
return jsonResponse(200, { ok: true, data: r });
|
|
818
|
+
} catch (e) {
|
|
819
|
+
return jsonResponse(500, { ok: false, error: String(e && e.message) });
|
|
820
|
+
}
|
|
821
|
+
},
|
|
822
|
+
},
|
|
823
|
+
{
|
|
824
|
+
path: `${API_PREFIX}/import`,
|
|
825
|
+
methods: ["POST"],
|
|
826
|
+
fetch: async (req) => {
|
|
827
|
+
const g = mutationGuard(req);
|
|
828
|
+
if (g) return jsonResponse(g.statusCode, { ok: false, error: g.error });
|
|
829
|
+
try {
|
|
830
|
+
const body = await readBody(req);
|
|
831
|
+
const r = await importPackage(body.dir, body, ctx);
|
|
832
|
+
return jsonResponse(200, { ok: true, data: r });
|
|
833
|
+
} catch (e) {
|
|
834
|
+
return jsonResponse(e && e.statusCode ? e.statusCode : 500, { ok: false, error: String(e && e.message) });
|
|
835
|
+
}
|
|
836
|
+
},
|
|
837
|
+
},
|
|
838
|
+
{
|
|
839
|
+
path: `${API_PREFIX}/probe`,
|
|
840
|
+
methods: ["POST"],
|
|
841
|
+
fetch: async (req) => {
|
|
842
|
+
const g = mutationGuard(req);
|
|
843
|
+
if (g) return jsonResponse(g.statusCode, { ok: false, error: g.error });
|
|
844
|
+
try {
|
|
845
|
+
const body = await readBody(req);
|
|
846
|
+
const st = await loadState();
|
|
847
|
+
const strict = !!st.strictPublic;
|
|
848
|
+
const url = String(body.repoUrl || st.repoUrl || "").trim();
|
|
849
|
+
const trusted = st.trustedRepos || {};
|
|
850
|
+
// 「重新检测」:先忘掉该地址的信任,再强制探测一次
|
|
851
|
+
if (body.force && url && trusted[url]) {
|
|
852
|
+
const t2 = { ...trusted };
|
|
853
|
+
delete t2[url];
|
|
854
|
+
await saveState({ trustedRepos: t2 });
|
|
855
|
+
} else if (url && trusted[url]) {
|
|
856
|
+
// 已成功推送过的同一地址:直接信任,不再发起 ls-remote
|
|
857
|
+
return jsonResponse(200, { ok: true, data: { trusted: true, public: false, checked: false, strict, confirmNeeded: false, at: trusted[url].at } });
|
|
858
|
+
}
|
|
859
|
+
const r = await probePublicRepo(url);
|
|
860
|
+
const confirmNeeded = !!r.public || (strict && r.checked === false);
|
|
861
|
+
return jsonResponse(200, { ok: true, data: { ...r, strict, confirmNeeded } });
|
|
862
|
+
} catch (e) {
|
|
863
|
+
return jsonResponse(500, { ok: false, error: String(e && e.message) });
|
|
864
|
+
}
|
|
865
|
+
},
|
|
866
|
+
},
|
|
867
|
+
{
|
|
868
|
+
path: `${API_PREFIX}/settings`,
|
|
869
|
+
methods: ["POST"],
|
|
870
|
+
fetch: async (req) => {
|
|
871
|
+
const g = mutationGuard(req);
|
|
872
|
+
if (g) return jsonResponse(g.statusCode, { ok: false, error: g.error });
|
|
873
|
+
try {
|
|
874
|
+
const body = await readBody(req);
|
|
875
|
+
const patch = {};
|
|
876
|
+
if ("strictPublic" in body) patch.strictPublic = !!body.strictPublic;
|
|
877
|
+
await saveState(patch);
|
|
878
|
+
return jsonResponse(200, { ok: true, data: await getStatus() });
|
|
879
|
+
} catch (e) {
|
|
880
|
+
return jsonResponse(500, { ok: false, error: String(e && e.message) });
|
|
881
|
+
}
|
|
882
|
+
},
|
|
883
|
+
},
|
|
884
|
+
{
|
|
885
|
+
path: `${API_PREFIX}/push`,
|
|
886
|
+
methods: ["POST"],
|
|
887
|
+
fetch: async (req) => {
|
|
888
|
+
const g = mutationGuard(req);
|
|
889
|
+
if (g) return jsonResponse(g.statusCode, { ok: false, error: g.error });
|
|
890
|
+
try {
|
|
891
|
+
const body = await readBody(req);
|
|
892
|
+
const r = await pushRepo(body.repoUrl, body.branch, body.include, { allowPublic: !!body.allowPublic });
|
|
893
|
+
return jsonResponse(200, { ok: true, data: r });
|
|
894
|
+
} catch (e) {
|
|
895
|
+
return jsonResponse(e && e.statusCode ? e.statusCode : 500, { ok: false, error: String(e && e.message), code: e && e.code, data: e && e.data });
|
|
896
|
+
}
|
|
897
|
+
},
|
|
898
|
+
},
|
|
899
|
+
{
|
|
900
|
+
path: `${API_PREFIX}/pull`,
|
|
901
|
+
methods: ["POST"],
|
|
902
|
+
fetch: async (req) => {
|
|
903
|
+
const g = mutationGuard(req);
|
|
904
|
+
if (g) return jsonResponse(g.statusCode, { ok: false, error: g.error });
|
|
905
|
+
try {
|
|
906
|
+
const body = await readBody(req);
|
|
907
|
+
const r = await pullRepo(body.repoUrl, body.branch, ctx);
|
|
908
|
+
return jsonResponse(200, { ok: true, data: r });
|
|
909
|
+
} catch (e) {
|
|
910
|
+
return jsonResponse(e && e.statusCode ? e.statusCode : 500, { ok: false, error: String(e && e.message) });
|
|
911
|
+
}
|
|
912
|
+
},
|
|
913
|
+
},
|
|
914
|
+
];
|
|
915
|
+
|
|
916
|
+
ctx.effect(() => {
|
|
917
|
+
const disposers = routes.map((r) =>
|
|
918
|
+
ctx.connection.fetch.register({
|
|
919
|
+
path: r.path,
|
|
920
|
+
methods: r.methods,
|
|
921
|
+
requestBody: "buffered",
|
|
922
|
+
fetch: r.fetch,
|
|
923
|
+
})
|
|
924
|
+
);
|
|
925
|
+
return () => {
|
|
926
|
+
for (const d of disposers) {
|
|
927
|
+
try {
|
|
928
|
+
d();
|
|
929
|
+
} catch {
|
|
930
|
+
/* ignore */
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
}, "config-sync: API routes");
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/* ---------------------------------------------------------------- tools */
|
|
938
|
+
|
|
939
|
+
function registerTools(ctx) {
|
|
940
|
+
if (!ctx.tools || typeof ctx.tools.register !== "function") return;
|
|
941
|
+
const reg = (def) => ctx.effect(() => ctx.tools.register(def), `config-sync: tool ${def.name}`);
|
|
942
|
+
|
|
943
|
+
reg({
|
|
944
|
+
name: "config_sync_status",
|
|
945
|
+
description: "查看 DSH 配置同步的当前状态(同步仓路径、仓库地址、脚本计数、上次同步时间)。",
|
|
946
|
+
parameters: { type: "object", properties: {}, additionalProperties: false },
|
|
947
|
+
output: { schema: { type: "object" }, render: (_a, v) => [{ type: "text", text: `配置同步:插件 ${v.pluginCount},skills 文件 ${v.skillsCount},仓库 ${v.repoUrl || "(未配置)"},上次同步 ${v.lastSync || "无"}` }] },
|
|
948
|
+
async execute() {
|
|
949
|
+
return getStatus();
|
|
950
|
+
},
|
|
951
|
+
});
|
|
952
|
+
|
|
953
|
+
reg({
|
|
954
|
+
name: "config_sync_export",
|
|
955
|
+
description: "把 DSH 全局配置(脱敏)、全局 skills、已安装插件清单导出到本地同步仓(~/.dsh/config-sync/repo)。",
|
|
956
|
+
parameters: {
|
|
957
|
+
type: "object",
|
|
958
|
+
properties: {
|
|
959
|
+
settings: { type: "boolean", description: "导出 settings.yaml(脱敏)" },
|
|
960
|
+
agents: { type: "boolean", description: "导出 AGENTS.md" },
|
|
961
|
+
presets: { type: "boolean", description: "导出 agent-presets" },
|
|
962
|
+
skills: { type: "boolean", description: "导出全局 skills" },
|
|
963
|
+
plugins: { type: "boolean", description: "导出插件清单" },
|
|
964
|
+
optional: { type: "boolean", description: "导出主题/环境类(可选)" },
|
|
965
|
+
},
|
|
966
|
+
additionalProperties: false,
|
|
967
|
+
},
|
|
968
|
+
output: { schema: { type: "object" }, render: (_a, v) => [{ type: "text", text: `已导出到 ${v.dir}:${JSON.stringify(v.counts)}` }] },
|
|
969
|
+
async execute(args) {
|
|
970
|
+
return buildExport(args);
|
|
971
|
+
},
|
|
972
|
+
});
|
|
973
|
+
|
|
974
|
+
reg({
|
|
975
|
+
name: "config_sync_import",
|
|
976
|
+
description: "从本地同步仓(或指定目录)导入配置、skills 与插件(自动安装 name@version,优先官方 registry)。导入前会自动备份当前配置。",
|
|
977
|
+
parameters: { type: "object", properties: { dir: { type: "string", description: "包目录,默认 ~/.dsh/config-sync/repo" } }, additionalProperties: false },
|
|
978
|
+
output: { schema: { type: "object" }, render: (_a, v) => [{ type: "text", text: `导入完成:插件装 ${v.plugins.installed.length}、更新 ${v.plugins.updated.length}、失败 ${v.plugins.failed.length};skills ${v.skills.length};备份 ${v.backup}${v.needsRestart ? "(需重启生效)" : ""}` }] },
|
|
979
|
+
async execute(args) {
|
|
980
|
+
return importPackage(args && args.dir, {}, ctx);
|
|
981
|
+
},
|
|
982
|
+
});
|
|
983
|
+
|
|
984
|
+
reg({
|
|
985
|
+
name: "config_sync_push",
|
|
986
|
+
description: "导出并把配置推送到已配置的 Git 仓库(SSH)。可传 repoUrl 覆盖。推送前会用无凭据匿名 ls-remote 探测是否公开;若可被公开匿名访问(或严格模式下无法判定),必须显式传 allowPublic:true(已获用户确认)才会推送。",
|
|
987
|
+
parameters: {
|
|
988
|
+
type: "object",
|
|
989
|
+
properties: {
|
|
990
|
+
repoUrl: { type: "string", description: "Git 仓库地址(SSH,例如 git@gitee.com:you/dsh-config.git)" },
|
|
991
|
+
branch: { type: "string", description: "分支,默认 main" },
|
|
992
|
+
allowPublic: { type: "boolean", description: "已征得用户同意同步到公开仓库时设为 true" },
|
|
993
|
+
},
|
|
994
|
+
additionalProperties: false,
|
|
995
|
+
},
|
|
996
|
+
output: { schema: { type: "object" }, render: (_a, v) => [{ type: "text", text: `推送完成:${v.committed ? "已提交" : "无变更"}${v.push ? ";" + v.push : ""}` }] },
|
|
997
|
+
async execute(args) {
|
|
998
|
+
const st = await loadState();
|
|
999
|
+
return pushRepo((args && args.repoUrl) || st.repoUrl, (args && args.branch) || st.branch, (args && args.include) || st.include, { allowPublic: !!(args && args.allowPublic) });
|
|
1000
|
+
},
|
|
1001
|
+
});
|
|
1002
|
+
|
|
1003
|
+
reg({
|
|
1004
|
+
name: "config_sync_pull",
|
|
1005
|
+
description: "从 Git 仓库拉取最新配置并导入(自动装插件)。",
|
|
1006
|
+
parameters: {
|
|
1007
|
+
type: "object",
|
|
1008
|
+
properties: {
|
|
1009
|
+
repoUrl: { type: "string", description: "Git 仓库地址(SSH)" },
|
|
1010
|
+
branch: { type: "string", description: "分支,默认 main" },
|
|
1011
|
+
},
|
|
1012
|
+
additionalProperties: false,
|
|
1013
|
+
},
|
|
1014
|
+
output: { schema: { type: "object" }, render: (_a, v) => [{ type: "text", text: `拉取导入完成:插件装 ${v.import.plugins.installed.length}、失败 ${v.import.plugins.failed.length};skills ${v.import.skills.length}${v.import.needsRestart ? "(需重启生效)" : ""}` }] },
|
|
1015
|
+
async execute(args) {
|
|
1016
|
+
const st = await loadState();
|
|
1017
|
+
return pullRepo((args && args.repoUrl) || st.repoUrl, (args && args.branch) || st.branch, ctx);
|
|
1018
|
+
},
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/* ---------------------------------------------------------------- apply */
|
|
1023
|
+
|
|
1024
|
+
export function apply(ctx) {
|
|
1025
|
+
registerRoutes(ctx);
|
|
1026
|
+
registerTools(ctx);
|
|
1027
|
+
}
|