agentdock-cli 1.2.0 → 1.4.1

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.
@@ -15,6 +15,7 @@ const sensitive_1 = require("../scanners/sensitive");
15
15
  const supply_chain_1 = require("./supply-chain");
16
16
  const snapshot_1 = require("./snapshot");
17
17
  const snapshot_diff_1 = require("./snapshot-diff");
18
+ const registry_1 = require("../agents/registry");
18
19
  const smol_toml_1 = require("smol-toml");
19
20
  const fs_1 = require("../utils/fs");
20
21
  // ===== helpers =====
@@ -27,8 +28,8 @@ function supplyRiskFinding(risk) {
27
28
  * 供应链风险检查:未固定版本的 npx -y / uvx 远程拉取(doctor live 复用
28
29
  * attest 的共享检测;风险统一为 warn 级,`unpinned-npx` 在 attest 中才是 high)。
29
30
  */
30
- function supplyChainCheck(findings) {
31
- return makeCheck('supply-chain', '供应链风险', findings, '未发现未固定版本的 npx -y / uvx 远程拉取命令', SUPPLY_CHAIN_REMEDIATION);
31
+ function supplyChainCheck(findings, checkId = 'supply-chain', label = '供应链风险') {
32
+ return makeCheck(checkId, label, findings, '未发现未固定版本的 npx -y / uvx 远程拉取命令', SUPPLY_CHAIN_REMEDIATION);
32
33
  }
33
34
  /** 从 JSON/TOML 结构化配置里收集未固定版本的 npx / uvx 拉取。 */
34
35
  function supplyFindingsFromStructured(file, parsed, findings) {
@@ -65,14 +66,6 @@ function makeCheck(id, label, findings, passDetail, remediation) {
65
66
  }
66
67
  return check;
67
68
  }
68
- const BASELINE_FILES = {
69
- claude: ['.claude.json', '.claude/settings.json', '.claude/settings.local.json'],
70
- codex: ['.codex/config.toml'],
71
- };
72
- const BASELINE_CRITICAL_KEYS = {
73
- claude: ['model', 'modelPicker', 'mcpServers', 'env'],
74
- codex: ['model', 'model_providers', 'mcp_servers'],
75
- };
76
69
  /** 稳定序列化(键排序),避免对象键顺序不同造成"假不一致"。 */
77
70
  function stableValue(value) {
78
71
  if (Array.isArray(value)) {
@@ -85,80 +78,107 @@ function stableValue(value) {
85
78
  }
86
79
  return JSON.stringify(value) ?? 'null';
87
80
  }
88
- /** 收集 Claude 各配置文件中根级 mcpServers(项目级定义不参与跨文件比对)。 */
89
- async function collectClaudeMcpSources(root) {
81
+ /** 收集某个工具各配置文件中根级 MCP 定义(项目级定义不参与跨文件比对)。 */
82
+ async function collectMcpSources(root, agentId) {
83
+ const adapter = (0, registry_1.resolveAgentAdapter)(agentId);
84
+ if (!adapter) {
85
+ return [];
86
+ }
90
87
  const sources = [];
91
- for (const relPath of ['.claude.json', '.claude/settings.json', '.claude/settings.local.json']) {
92
- const abs = node_path_1.default.join(root, ...relPath.split('/'));
93
- if (!(await fileExists(abs))) {
88
+ const seen = new Set();
89
+ for (const file of adapter.configFiles()) {
90
+ if (file.kind === 'text') {
94
91
  continue;
95
92
  }
93
+ const abs = node_path_1.default.join(root, ...file.relPath.split('/'));
94
+ let text;
96
95
  try {
97
- const parsed = JSON.parse(await promises_1.default.readFile(abs, 'utf8'));
98
- const servers = parsed?.mcpServers;
99
- if (servers && typeof servers === 'object' && !Array.isArray(servers)) {
100
- sources.push({ file: abs, servers: servers });
101
- }
96
+ text = await promises_1.default.readFile(abs, 'utf8');
102
97
  }
103
98
  catch {
104
- // 解析失败已由 config-valid 检查报告
99
+ continue;
100
+ }
101
+ const parsed = (0, snapshot_diff_1.parseConfigObject)(file.relPath, text);
102
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
103
+ continue;
104
+ }
105
+ const obj = parsed;
106
+ for (const key of adapter.mcpKeys) {
107
+ const servers = obj[key];
108
+ if (servers && typeof servers === 'object' && !Array.isArray(servers)) {
109
+ const sourceKey = `${abs}#${key}`;
110
+ if (seen.has(sourceKey)) {
111
+ continue;
112
+ }
113
+ seen.add(sourceKey);
114
+ sources.push({ agent: adapter.id, file: abs, servers: servers });
115
+ }
105
116
  }
106
117
  }
107
118
  return sources;
108
119
  }
109
- /** 同一 MCP id 在多个配置文件中重复定义:值不一致 → warn,值一致 → info。 */
110
- async function mcpDuplicateCheck(root) {
111
- const sources = await collectClaudeMcpSources(root);
120
+ /**
121
+ * 同一 MCP id 在多个配置文件中重复定义:值不一致 → warn,值一致 → info。
122
+ * 按工具分组,避免把不同工具里的同名 MCP 误判为重复。
123
+ */
124
+ async function mcpDuplicateCheck(root, agentIds, checkId = 'mcp-duplicate') {
125
+ const sources = (await Promise.all(agentIds.map((agentId) => collectMcpSources(root, agentId)))).flat();
112
126
  const byId = new Map();
113
127
  for (const source of sources) {
114
128
  for (const [id, value] of Object.entries(source.servers)) {
115
- const list = byId.get(id) ?? [];
116
- list.push({ file: source.file, value });
117
- byId.set(id, list);
129
+ const key = `${source.agent}\u0000${id}`;
130
+ const list = byId.get(key) ?? [];
131
+ list.push({ agent: source.agent, file: source.file, value });
132
+ byId.set(key, list);
118
133
  }
119
134
  }
135
+ const multiAgent = agentIds.length > 1;
120
136
  const findings = [];
121
- for (const [id, defs] of [...byId.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
137
+ for (const [key, defs] of [...byId.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
122
138
  if (defs.length < 2) {
123
139
  continue;
124
140
  }
141
+ const id = key.split('\u0000')[1];
142
+ const agent = defs[0].agent;
143
+ const adapter = (0, registry_1.resolveAgentAdapter)(agent);
144
+ const prefix = multiAgent && adapter ? `[${adapter.displayName}] ` : '';
125
145
  const files = defs.map((def) => node_path_1.default.basename(def.file));
126
146
  const distinct = new Set(defs.map((def) => stableValue(def.value)));
127
147
  if (distinct.size > 1) {
128
148
  findings.push({
129
149
  severity: 'warn',
130
- message: `MCP "${id}" 在 ${files.join('、')} 中重复定义且值不一致;重启后 /mcp 可能出现重复项`,
150
+ message: `${prefix}MCP "${id}" 在 ${files.join('、')} 中重复定义且值不一致;重启后可能出现重复项`,
131
151
  path: defs.map((def) => def.file).join(', '),
132
152
  });
133
153
  }
134
154
  else {
135
155
  findings.push({
136
156
  severity: 'info',
137
- message: `MCP "${id}" 在 ${files.join('、')} 中重复定义(值一致,可清理冗余)`,
157
+ message: `${prefix}MCP "${id}" 在 ${files.join('、')} 中重复定义(值一致,可清理冗余)`,
138
158
  path: defs.map((def) => def.file).join(', '),
139
159
  });
140
160
  }
141
161
  }
142
- return makeCheck('mcp-duplicate', 'MCP 重复定义', findings, '未发现同一 MCP 在多个配置文件中重复定义', '同一 MCP id 在多处定义时,Claude Code 可能加载出重复项(`/mcp` 出现两次)或按加载顺序覆盖。保留一处(推荐 `.claude.json` 的全局 `mcpServers`),删除 `.claude/settings*.json` 中的重复定义后重启。');
162
+ return makeCheck(checkId, 'MCP 重复定义', findings, '未发现同一 MCP 在多个配置文件中重复定义', '同一 MCP id 在多处定义时,工具可能加载出重复项(如 Claude Code 的 `/mcp` 出现两次)或按加载顺序覆盖。保留一处(推荐全局配置),删除其他文件中的重复定义后重启。');
143
163
  }
144
164
  /**
145
- * 配置基线:与本 agent 最近一次快照比对,发现大面积顶层键减少或关键项消失时判失败。
165
+ * 配置基线:与本工具最近一次快照比对,发现大面积顶层键减少或关键项消失时判失败。
146
166
  * 无快照时保持 pass,仅提示先建立基线(避免升级后首次体检即报警)。
147
167
  */
148
- async function configBaselineCheck(root, agent) {
168
+ async function configBaselineCheck(root, agent, files, criticalKeys, checkId = 'config-baseline', label = '配置基线') {
149
169
  const latest = await (0, snapshot_1.latestSnapshot)(root, agent).catch(() => null);
150
170
  if (!latest) {
151
171
  return {
152
- id: 'config-baseline',
153
- label: '配置基线',
172
+ id: checkId,
173
+ label,
154
174
  status: 'pass',
155
- detail: '尚无配置快照,无法比对;建议运行 `agentdock snapshot` 建立基线',
175
+ detail: `尚无配置快照,无法比对;建议运行 \`agentdock snapshot --agent ${agent}\` 建立基线`,
156
176
  findings: [],
157
177
  };
158
178
  }
159
179
  const before = await (0, snapshot_1.readSnapshotContents)(latest);
160
180
  const findings = [];
161
- for (const relPath of BASELINE_FILES[agent]) {
181
+ for (const relPath of files) {
162
182
  const beforeBuffer = before.get(relPath);
163
183
  if (!beforeBuffer) {
164
184
  continue;
@@ -194,14 +214,14 @@ async function configBaselineCheck(root, agent) {
194
214
  });
195
215
  }
196
216
  }
197
- for (const key of BASELINE_CRITICAL_KEYS[agent]) {
217
+ for (const key of criticalKeys) {
198
218
  if (Object.prototype.hasOwnProperty.call(beforeObj, key)
199
219
  && !Object.prototype.hasOwnProperty.call(afterObj, key)) {
200
220
  findings.push({ severity: 'error', message: `关键配置项消失:${key}`, path: abs });
201
221
  }
202
222
  }
203
223
  }
204
- return makeCheck('config-baseline', '配置基线', findings, `当前配置与最近快照 ${latest.meta.id} 一致`, '配置相对最近快照出现大面积缺失或关键项消失。先运行 `agentdock diff --since-last` 查看逐项差异;确认需要回滚后运行 `agentdock restore --snapshot <id> --apply`。');
224
+ return makeCheck(checkId, label, findings, `当前配置与最近快照 ${latest.meta.id} 一致`, '配置相对最近快照出现大面积缺失或关键项消失。先运行 `agentdock diff --since-last` 查看逐项差异;确认需要回滚后运行 `agentdock restore --snapshot <id> --apply`。');
205
225
  }
206
226
  /** 取差异路径中 `#` 后的首层键,如 `.claude.json#mcpServers.github` → `mcpServers`。 */
207
227
  function topLevelKeyOf(changePath) {
@@ -230,7 +250,7 @@ async function teamBaselineCheck(root, baselineRef) {
230
250
  }
231
251
  const before = await (0, snapshot_1.readSnapshotContents)(baseline);
232
252
  const after = new Map();
233
- for (const relPath of (0, snapshot_1.configFilesFor)(baseline.meta.agent)) {
253
+ for (const relPath of (0, registry_1.agentConfigFiles)(baseline.meta.agent).map((file) => file.relPath)) {
234
254
  try {
235
255
  after.set(relPath, await promises_1.default.readFile(node_path_1.default.join(root, ...relPath.split('/'))));
236
256
  }
@@ -244,9 +264,7 @@ async function teamBaselineCheck(root, baselineRef) {
244
264
  const changes = baseline.meta.redacted
245
265
  ? diff.changes.filter((change) => change.change !== 'modified')
246
266
  : diff.changes;
247
- const critical = new Set(baseline.meta.agent === 'all'
248
- ? [...BASELINE_CRITICAL_KEYS.claude, ...BASELINE_CRITICAL_KEYS.codex]
249
- : BASELINE_CRITICAL_KEYS[baseline.meta.agent]);
267
+ const critical = new Set((0, registry_1.agentCriticalKeys)(baseline.meta.agent));
250
268
  const findings = [];
251
269
  for (const change of changes) {
252
270
  if (change.change === 'removed' && critical.has(topLevelKeyOf(change.path))) {
@@ -515,9 +533,9 @@ async function doctorLiveClaude(root) {
515
533
  }
516
534
  checks.push(supplyChainCheck(supplyFindings));
517
535
  // 6. MCP 重复定义:同一 id 在多个配置文件中重复
518
- checks.push(await mcpDuplicateCheck(root));
536
+ checks.push(await mcpDuplicateCheck(root, ['claude']));
519
537
  // 7. 配置基线:与最近快照比对,识别大面积改写
520
- checks.push(await configBaselineCheck(root, 'claude'));
538
+ checks.push(await configBaselineCheck(root, 'claude', (0, registry_1.agentConfigFiles)('claude').map((file) => file.relPath), (0, registry_1.agentCriticalKeys)('claude')));
521
539
  return checks;
522
540
  }
523
541
  async function doctorLiveCodex(root) {
@@ -640,22 +658,105 @@ async function doctorLiveCodex(root) {
640
658
  }
641
659
  checks.push(supplyChainCheck(supplyFindings));
642
660
  // 6. 配置基线:与最近快照比对,识别大面积改写
643
- checks.push(await configBaselineCheck(root, 'codex'));
661
+ checks.push(await configBaselineCheck(root, 'codex', (0, registry_1.agentConfigFiles)('codex').map((file) => file.relPath), (0, registry_1.agentCriticalKeys)('codex')));
662
+ return checks;
663
+ }
664
+ /**
665
+ * 通用适配器体检(v1.3):配置存在性、可解析性、供应链风险、MCP 重复、配置基线。
666
+ * Claude / Codex 走上面的专属检查;其余工具走这条通用路径。
667
+ */
668
+ async function doctorLiveAdapter(adapter, root) {
669
+ const checks = [];
670
+ const configs = adapter.configFiles();
671
+ const existing = [];
672
+ for (const file of configs) {
673
+ const abs = node_path_1.default.join(root, ...file.relPath.split('/'));
674
+ if (await fileExists(abs)) {
675
+ existing.push({ relPath: file.relPath, abs });
676
+ }
677
+ }
678
+ if (existing.length === 0) {
679
+ checks.push({
680
+ id: `config-present:${adapter.id}`,
681
+ label: `${adapter.displayName} 配置存在`,
682
+ status: 'warn',
683
+ detail: `未找到 ${adapter.displayName} 的配置文件`,
684
+ findings: [],
685
+ remediation: `若已安装 ${adapter.displayName},确认 --root 指向正确的用户主目录;否则可忽略${adapter.experimental ? `(该工具路径仍属实验性:${adapter.note ?? '待核实'})` : ''}。`,
686
+ });
687
+ return checks;
688
+ }
689
+ // 1. 配置合法性
690
+ const parseFindings = [];
691
+ const parsedByFile = new Map();
692
+ for (const { relPath, abs } of existing) {
693
+ const file = configs.find((item) => item.relPath === relPath);
694
+ if (!file || file.kind === 'text') {
695
+ continue;
696
+ }
697
+ let text;
698
+ try {
699
+ text = await promises_1.default.readFile(abs, 'utf8');
700
+ }
701
+ catch {
702
+ parseFindings.push({ severity: 'error', message: '配置文件无法读取', path: abs });
703
+ continue;
704
+ }
705
+ if (text.trim().length === 0) {
706
+ continue;
707
+ }
708
+ const parsed = (0, snapshot_diff_1.parseConfigObject)(relPath, text);
709
+ if (parsed === null) {
710
+ parseFindings.push({ severity: 'error', message: `${file.kind.toUpperCase()} 解析失败`, path: abs });
711
+ continue;
712
+ }
713
+ parsedByFile.set(abs, parsed);
714
+ }
715
+ checks.push(makeCheck(`config-valid:${adapter.id}`, `${adapter.displayName} 配置文件合法`, parseFindings, `${adapter.displayName} 配置文件均可解析`, `修复 ${adapter.displayName} 配置文件的语法后重试(见上方路径与报错)。`));
716
+ // 2. 供应链风险
717
+ const supplyFindings = [];
718
+ for (const [abs, parsed] of parsedByFile) {
719
+ supplyFindingsFromStructured(abs, parsed, supplyFindings);
720
+ }
721
+ checks.push(supplyChainCheck(supplyFindings, `supply-chain:${adapter.id}`, `${adapter.displayName} 供应链风险`));
722
+ // 3. MCP 重复定义(仅同一工具内比较)
723
+ checks.push(await mcpDuplicateCheck(root, [adapter.id], `mcp-duplicate:${adapter.id}`));
724
+ // 4. 配置基线
725
+ checks.push(await configBaselineCheck(root, adapter.id, configs.map((file) => file.relPath), adapter.criticalKeys, `config-baseline:${adapter.id}`, `${adapter.displayName} 配置基线`));
644
726
  return checks;
645
727
  }
646
728
  async function doctorLive(options) {
647
729
  const root = options.root ?? node_os_1.default.homedir();
730
+ const requested = (0, registry_1.normalizeAgentId)(options.agent ?? 'all');
648
731
  const checks = [];
649
- if (options.agent === 'claude' || options.agent === 'all') {
732
+ if (requested === 'all') {
733
+ checks.push(...await doctorLiveClaude(root));
734
+ checks.push(...await doctorLiveCodex(root));
735
+ // 其余工具只在检测到配置时展开,避免空环境被十几条"未安装"警告淹没
736
+ const installed = new Set(await (0, registry_1.detectInstalledAgents)(root));
737
+ for (const adapter of (0, registry_1.listAgentAdapters)()) {
738
+ if (adapter.id === 'claude' || adapter.id === 'codex' || !installed.has(adapter.id)) {
739
+ continue;
740
+ }
741
+ checks.push(...await doctorLiveAdapter(adapter, root));
742
+ }
743
+ }
744
+ else if (requested === 'claude') {
650
745
  checks.push(...await doctorLiveClaude(root));
651
746
  }
652
- if (options.agent === 'codex' || options.agent === 'all') {
747
+ else if (requested === 'codex') {
653
748
  checks.push(...await doctorLiveCodex(root));
654
749
  }
750
+ else {
751
+ const adapter = (0, registry_1.resolveAgentAdapter)(requested);
752
+ if (adapter) {
753
+ checks.push(...await doctorLiveAdapter(adapter, root));
754
+ }
755
+ }
655
756
  if (options.baseline) {
656
757
  checks.push(await teamBaselineCheck(root, options.baseline));
657
758
  }
658
- return finalize('live', options.agent, root, checks);
759
+ return finalize('live', requested, root, checks);
659
760
  }
660
761
  async function doctorScan(options) {
661
762
  const scanPath = options.fromScan;
@@ -675,7 +776,7 @@ async function doctorScan(options) {
675
776
  const manifest = yaml_1.default.parse(await promises_1.default.readFile(scanPath, 'utf8'));
676
777
  // 1. 引用完整性:manifest 记录的源文件是否仍存在
677
778
  const missing = [];
678
- const domains = [manifest.agents.claude, manifest.agents.codex].filter(Boolean);
779
+ const domains = Object.values(manifest.agents).filter(Boolean);
679
780
  for (const dom of domains) {
680
781
  for (const entries of Object.values(dom)) {
681
782
  for (const entry of entries) {
@@ -7,12 +7,25 @@ exports.planInstall = planInstall;
7
7
  exports.installPackage = installPackage;
8
8
  const promises_1 = __importDefault(require("node:fs/promises"));
9
9
  const node_path_1 = __importDefault(require("node:path"));
10
- const smol_toml_1 = require("smol-toml");
10
+ const config_format_1 = require("../utils/config-format");
11
11
  const format_versions_1 = require("../constants/format-versions");
12
12
  const fs_1 = require("../utils/fs");
13
- /** Parse a data file by its extension (TOML or JSON). */
13
+ /** 按扩展名解析结构化配置(JSON / JSONC / YAML / TOML)。 */
14
14
  function parseByExt(filePath, content) {
15
- return node_path_1.default.extname(filePath).toLowerCase() === '.toml' ? (0, smol_toml_1.parse)(content) : JSON.parse(content);
15
+ const kind = (0, config_format_1.kindFromPath)(filePath);
16
+ if (kind === 'text') {
17
+ throw new Error(`CONFIG_FORMAT_UNSUPPORTED: ${filePath}`);
18
+ }
19
+ return (0, config_format_1.parseStructured)(kind, content);
20
+ }
21
+ /** 按扩展名写回结构化配置,保持目标文件格式。 */
22
+ async function writeByExt(filePath, data) {
23
+ const kind = (0, config_format_1.kindFromPath)(filePath);
24
+ if (kind === 'json' || kind === 'text') {
25
+ await (0, fs_1.writeJsonFile)(filePath, data);
26
+ return;
27
+ }
28
+ await (0, fs_1.writeTextFile)(filePath, (0, config_format_1.stringifyStructured)(kind, data));
16
29
  }
17
30
  async function isIdenticalFile(targetPath, sourcePath) {
18
31
  try {
@@ -109,12 +122,7 @@ async function mergeDataFile(from, to, mergeKeys) {
109
122
  }
110
123
  // Fresh target: restore the entire payload (in the target's format).
111
124
  if (!(await (0, fs_1.pathExists)(to))) {
112
- if (node_path_1.default.extname(to).toLowerCase() === '.toml') {
113
- await (0, fs_1.writeTextFile)(to, (0, smol_toml_1.stringify)(source));
114
- }
115
- else {
116
- await (0, fs_1.writeJsonFile)(to, source);
117
- }
125
+ await writeByExt(to, source);
118
126
  return;
119
127
  }
120
128
  // planInstall 已确保可合并目标要么不存在、要么可解析;此处解析失败说明目标刚被外部改动,
@@ -123,12 +131,7 @@ async function mergeDataFile(from, to, mergeKeys) {
123
131
  const merged = mergeKeys && mergeKeys.length > 0
124
132
  ? mergeOnlyKeys(target, source, mergeKeys)
125
133
  : deepMerge(target, source);
126
- if (node_path_1.default.extname(to).toLowerCase() === '.toml') {
127
- await (0, fs_1.writeTextFile)(to, (0, smol_toml_1.stringify)(merged));
128
- }
129
- else {
130
- await (0, fs_1.writeJsonFile)(to, merged);
131
- }
134
+ await writeByExt(to, merged);
132
135
  }
133
136
  /**
134
137
  * 校验包元数据里的 `formatVersion`:
@@ -25,6 +25,12 @@ function displayName(entry) {
25
25
  let name = entry.ref ?? entry.path;
26
26
  // strip a leading "<file>#" prefix (e.g. .claude.json#, config.toml#)
27
27
  name = name.replace(/^[^#]*#/, '');
28
+ if (entry.kind === 'mcp') {
29
+ // 取最后一个点号后的 server 名,兼容 mcpServers / mcp / context_servers /
30
+ // extensions / amp.mcpServers 等不同容器键。
31
+ const segments = name.split('.');
32
+ name = segments[segments.length - 1] ?? name;
33
+ }
28
34
  name = name.replace(/^mcpServers\./, '');
29
35
  name = name.replace(/^[a-z]+\//, '');
30
36
  name = name.replace(/\.(md|json|toml|sh|ts|js|txt)$/i, '');
@@ -14,6 +14,9 @@ const doctor_1 = require("./doctor");
14
14
  const report_html_1 = require("./report-html");
15
15
  const claude_scanner_1 = require("../scanners/claude-scanner");
16
16
  const codex_scanner_1 = require("../scanners/codex-scanner");
17
+ const semantic_scanner_1 = require("../scanners/semantic-scanner");
18
+ const registry_1 = require("../agents/registry");
19
+ const semantic_1 = require("../agents/semantic");
17
20
  const fs_1 = require("../utils/fs");
18
21
  // ===== inventory =====
19
22
  function countDomain(agent, domain) {
@@ -46,14 +49,32 @@ function makeInventory(agents, secretsCount) {
46
49
  async function inventoryLive(agentFilter, root) {
47
50
  const agents = [];
48
51
  let secretsCount = 0;
49
- if (agentFilter === 'claude' || agentFilter === 'all') {
50
- const scan = await (0, claude_scanner_1.scanClaude)(root);
51
- agents.push(countDomain('claude', scan.domain));
52
- secretsCount += scan.secrets.length;
53
- }
54
- if (agentFilter === 'codex' || agentFilter === 'all') {
55
- const scan = await (0, codex_scanner_1.scanCodex)(root);
56
- agents.push(countDomain('codex', scan.domain));
52
+ const agentIds = agentFilter === 'all'
53
+ ? registry_1.AGENT_ADAPTERS.map((adapter) => adapter.id)
54
+ : [agentFilter];
55
+ for (const agentId of agentIds) {
56
+ let scan;
57
+ if (agentId === 'claude') {
58
+ scan = await (0, claude_scanner_1.scanClaude)(root);
59
+ }
60
+ else if (agentId === 'codex') {
61
+ scan = await (0, codex_scanner_1.scanCodex)(root);
62
+ }
63
+ else {
64
+ const profile = (0, semantic_1.agentSemanticProfile)(agentId);
65
+ if (profile) {
66
+ scan = await (0, semantic_scanner_1.scanAgentSemantic)(root, profile, agentId);
67
+ }
68
+ }
69
+ if (!scan) {
70
+ continue;
71
+ }
72
+ const total = Object.values(scan.domain).reduce((sum, entries) => sum + entries.length, 0);
73
+ // `all` 模式下跳过本机未安装 / 无定义的工具。
74
+ if (agentFilter === 'all' && total === 0) {
75
+ continue;
76
+ }
77
+ agents.push(countDomain(agentId, scan.domain));
57
78
  secretsCount += scan.secrets.length;
58
79
  }
59
80
  return makeInventory(agents, secretsCount);
@@ -8,9 +8,9 @@ const promises_1 = __importDefault(require("node:fs/promises"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const yaml_1 = __importDefault(require("yaml"));
10
10
  const sensitive_1 = require("../scanners/sensitive");
11
- const smol_toml_1 = require("smol-toml");
12
11
  const fs_1 = require("../utils/fs");
13
12
  const format_versions_1 = require("../constants/format-versions");
13
+ const config_format_1 = require("../utils/config-format");
14
14
  function* iterEntries(domain) {
15
15
  yield* domain.mcp;
16
16
  yield* domain.skills;
@@ -54,6 +54,11 @@ function deriveScanRoot(manifest) {
54
54
  continue;
55
55
  }
56
56
  for (const entry of iterEntries(domain)) {
57
+ // 有新版本 manifest 直接记录的主目录则优先使用;
58
+ // 空环境(没有任何条目)仍然报错,避免产出一个无内容的空包。
59
+ if (manifest.scanRoot) {
60
+ return manifest.scanRoot;
61
+ }
57
62
  const parts = entry.path.split(node_path_1.default.sep);
58
63
  const idxClaude = parts.indexOf('.claude');
59
64
  if (idxClaude >= 0) {
@@ -150,8 +155,10 @@ async function exportFromScan(options) {
150
155
  continue;
151
156
  }
152
157
  const agent = agentName;
153
- // --- MCP: aggregate all captured servers into one .claude.json payload ---
154
- if (domain.mcp.length > 0) {
158
+ const legacy = agent === 'claude' || agent === 'codex';
159
+ // --- Claude MCP: aggregate all captured servers into one .claude.json payload ---
160
+ // 其余工具的 MCP 已包含在其 settings 配置文件里(整文件合并),无需单独聚合。
161
+ if (agent === 'claude' && domain.mcp.length > 0) {
155
162
  const claudeJsonPath = domain.mcp[0].path;
156
163
  if (!(await (0, fs_1.pathExists)(claudeJsonPath))) {
157
164
  throw new Error(`SCAN_EXPORT_MISSING_SOURCE: ${claudeJsonPath} (scanned but no longer present)`);
@@ -183,7 +190,7 @@ async function exportFromScan(options) {
183
190
  // --- Everything else ---
184
191
  for (const entry of iterEntries(domain)) {
185
192
  if (entry.kind === 'mcp') {
186
- continue; // handled above
193
+ continue; // Claude 已在上方聚合;其他工具随 settings 配置文件迁移
187
194
  }
188
195
  if (!(await (0, fs_1.pathExists)(entry.path))) {
189
196
  throw new Error(`SCAN_EXPORT_MISSING_SOURCE: ${entry.path} (scanned but no longer present)`);
@@ -192,6 +199,8 @@ async function exportFromScan(options) {
192
199
  const stat = await promises_1.default.stat(entry.path);
193
200
  const kind = stat.isDirectory() ? 'directory' : 'file';
194
201
  const targetDisk = node_path_1.default.join(payloadSourcesRoot, rel);
202
+ let merge;
203
+ let mergeKeys;
195
204
  if (kind === 'directory') {
196
205
  // recursive copy (skill dirs), then mask/inject any leaked
197
206
  // tokens inside the copied text files (prevents plaintext riding into the package)
@@ -199,32 +208,32 @@ async function exportFromScan(options) {
199
208
  await processDirectoryTexts(targetDisk, agent);
200
209
  }
201
210
  else if (entry.kind === 'settings') {
202
- if (node_path_1.default.extname(entry.path) === '.toml') {
203
- // Codex config.toml: parse as TOML, mask secrets at the object
204
- // level (same detectors as JSON), re-emit as TOML so the restore
205
- // lands back as a valid .codex/config.toml.
211
+ const format = (0, config_format_1.kindFromPath)(entry.path);
212
+ if (format === 'text') {
213
+ await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
214
+ }
215
+ else {
206
216
  try {
207
- const parsed = (0, smol_toml_1.parse)(await promises_1.default.readFile(entry.path, 'utf8'));
217
+ const parsed = (0, config_format_1.parseStructured)(format, await promises_1.default.readFile(entry.path, 'utf8'));
208
218
  recordAllocated((0, sensitive_1.maskSecretsInPlace)(parsed, entry.path, agent, env, undefined, secretKeyRegistry));
209
- await (0, fs_1.writeTextFile)(targetDisk, (0, smol_toml_1.stringify)(parsed));
219
+ await (0, fs_1.writeTextFile)(targetDisk, (0, config_format_1.stringifyStructured)(format, parsed));
210
220
  }
211
221
  catch (parseErr) {
212
- // Malformed TOML: fall back to a verbatim copy so export never
213
- // crashes. Secrets in such a file are NOT masked here; `doctor`
214
- // still flags leaked tokens in the resulting package.
222
+ // 解析失败:按原样复制,export 不崩溃;doctor 仍会检查机密泄露。
215
223
  await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
216
224
  console.warn(`[agentdock] 警告:无法解析 ${entry.path}(${String(parseErr.message)}),已按原样复制(机密未脱敏,请用 doctor 检查)`);
217
225
  }
218
- }
219
- else {
220
- try {
221
- const obj = JSON.parse(await promises_1.default.readFile(entry.path, 'utf8'));
222
- recordAllocated((0, sensitive_1.maskSecretsInPlace)(obj, entry.path, agent, env, undefined, secretKeyRegistry));
223
- await (0, fs_1.writeTextFile)(targetDisk, JSON.stringify(obj, null, 2));
226
+ if (legacy) {
227
+ // Codex config.toml 只合并 mcp_servers,保留目标机自己的 model/provider。
228
+ if (format === 'toml') {
229
+ merge = true;
230
+ mergeKeys = ['mcp_servers'];
231
+ }
224
232
  }
225
- catch (parseErr) {
226
- await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
227
- console.warn(`[agentdock] 警告:无法解析 ${entry.path}(${String(parseErr.message)}),已按原样复制(机密未脱敏,请用 doctor 检查)`);
233
+ else {
234
+ // 其他工具:整个配置文件深合并(目标已有键保留,本机配置覆盖同名键),
235
+ // 这样 MCP 与模型 / 供应商设置一起迁移,且不破坏目标机原有配置。
236
+ merge = true;
228
237
  }
229
238
  }
230
239
  }
@@ -253,14 +262,6 @@ async function exportFromScan(options) {
253
262
  await (0, fs_1.writeTextFile)(targetDisk, out);
254
263
  }
255
264
  }
256
- // Codex `config.toml` (and any TOML settings entry) is merged rather
257
- // than overwritten, so installing onto a machine that already has a
258
- // config.toml keeps its own model/provider settings and only adds the
259
- // package's `mcp_servers` — mirroring the Claude `.claude.json` merge
260
- // behavior (which scopes to `mcpServers`) and closing the Codex parity
261
- // gap. On a fresh target the whole file is restored.
262
- const merge = entry.kind === 'settings' && node_path_1.default.extname(entry.path) === '.toml' ? true : undefined;
263
- const mergeKeys = merge ? ['mcp_servers'] : undefined;
264
265
  sources.push({ id: entry.id, kind, from: toFrom(rel), to: rel, merge, mergeKeys });
265
266
  }
266
267
  }