@collectui/cli 0.2.22 → 0.2.26

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.
@@ -2,18 +2,9 @@ import { resolve } from "node:path";
2
2
  import { ChangeSet } from "../changes.mjs";
3
3
  import { dashUrl, registryUrl } from "../config.mjs";
4
4
  import { usageError } from "../errors.mjs";
5
- import {
6
- addMeSecrets,
7
- dashMcpTool,
8
- dashMcpTools,
9
- dashMe,
10
- fetchAccount,
11
- formatMeHuman,
12
- formatTools,
13
- } from "../dash.mjs";
5
+ import { fetchAccount } from "../dash.mjs";
14
6
  import { buildMcpEntries, describeEntries, planMcpConfig, renderEntry } from "../mcp.mjs";
15
- import { requireToken, selectLibs } from "./common.mjs";
16
- import { resolveClients } from "./setup.mjs";
7
+ import { chooseClients, detectClientApp, requireToken, selectLibs } from "./common.mjs";
17
8
 
18
9
  export async function mcpCmd(flags, rest, reporter) {
19
10
  const sub = rest[0] ?? "show";
@@ -22,10 +13,6 @@ export async function mcpCmd(flags, rest, reporter) {
22
13
  return;
23
14
  }
24
15
 
25
- if (["tools", "call", "me", "repos", "download", "feedback"].includes(sub)) {
26
- return dashMcpCommand(sub, flags, rest.slice(1), reporter);
27
- }
28
-
29
16
  if (sub === "show" || sub === "init" || sub === "configure") {
30
17
  return mcpConfigCommand(sub, flags, rest.slice(1), reporter);
31
18
  }
@@ -38,7 +25,8 @@ async function mcpConfigCommand(sub, flags, rest, reporter) {
38
25
  const me = await fetchAccount(token, { reporter });
39
26
  reporter.addSecrets((me.keys ?? []).map((k) => k.key).filter(Boolean));
40
27
  const { units } = await selectLibs({ flags, me, reporter });
41
- const clients = resolveClients(flags);
28
+ // show 是只读命令:不弹多选,按默认集打印(init/configure 才交互挑 Agent)
29
+ const clients = await chooseClients(flags, me, reporter, { interactive: sub !== "show" });
42
30
  const target = resolve(flags.cwd || rest[0] || process.cwd());
43
31
 
44
32
  const entries = buildMcpEntries({
@@ -96,103 +84,25 @@ async function mcpConfigCommand(sub, flags, rest, reporter) {
96
84
  files: applied.files?.length ?? 0,
97
85
  dryRun: Boolean(flags["dry-run"]),
98
86
  });
99
- reporter.outro(flags["dry-run"] ? "Dry run complete." : "MCP configuration updated.");
100
- }
101
-
102
- async function dashMcpCommand(sub, flags, rest, reporter) {
103
- const token = requireToken(flags, reporter);
104
-
105
- if (sub === "tools") {
106
- const tools = await dashMcpTools(token, { reporter });
107
- if (reporter.json) reporter.result({ tools });
108
- else reporter.note("Dash MCP tools", formatTools(tools));
109
- return;
110
- }
111
-
112
- if (sub === "call") {
113
- const name = rest[0];
114
- if (!name) throw usageError("Usage: cui mcp call <tool> [--args '<json>']");
115
- let args = {};
116
- if (flags.args) {
117
- try {
118
- args = JSON.parse(String(flags.args));
119
- } catch (error) {
120
- throw usageError(`--args is not valid JSON: ${error.message}`);
121
- }
122
- }
123
- const result = await dashMcpTool(token, name, args, { reporter });
124
- if (result?.keys) addMeSecrets(reporter, result);
125
- if (reporter.json) reporter.result({ tool: name, result });
126
- else reporter.note(`mcp:${name}`, typeof result === "string" ? result : JSON.stringify(result, null, 2));
127
- return;
128
- }
129
-
130
- if (sub === "me") {
131
- const me = await dashMe(token, { reporter });
132
- addMeSecrets(reporter, me);
133
- if (reporter.json) reporter.result(me);
134
- else reporter.note("Dash account", formatMeHuman(me));
135
- return;
136
- }
137
-
138
- if (sub === "repos") {
139
- const result = await dashMcpTool(token, "list_repos", {}, { reporter });
140
- if (reporter.json) reporter.result(result);
141
- else {
142
- const lines = (result?.releases ?? []).map(
143
- (r) => `- ${r.repo} v${r.version} ${r.size ?? "?"} bytes ${r.releasedAt}${r.brief ? `\n ${r.brief}` : ""}`
144
- );
145
- reporter.note("Downloadable repos", lines.join("\n") || "(none)");
146
- }
147
- return;
148
- }
149
-
150
- if (sub === "download") {
151
- const repo = rest[0];
152
- if (!repo) throw usageError("Usage: cui mcp download <owner/repo>");
153
- const result = await dashMcpTool(token, "download_repo", { repo }, { reporter });
154
- if (reporter.json) reporter.result(result);
155
- else {
156
- reporter.note(
157
- "Download",
158
- [
159
- `- repo: ${result?.repo ?? repo}`,
160
- `- version: ${result?.version ?? "?"}`,
161
- `- url: ${result?.url ?? "(no url)"}`,
162
- result?.gitUrl ? `- git: ${result.gitUrl}` : null,
163
- result?.expiresAt ? `- expires: ${result.expiresAt}` : null,
164
- ]
165
- .filter(Boolean)
166
- .join("\n")
87
+ if (!reporter.headless) {
88
+ const undetected = clients.filter((c) => !detectClientApp(c));
89
+ if (undetected.length) {
90
+ reporter.info(
91
+ `MCP config written for ${undetected.join(", ")} — app not detected on this machine; it picks the config up once installed.`
167
92
  );
168
93
  }
169
- return;
170
94
  }
95
+ reporter.outro(flags["dry-run"] ? "Dry run complete." : "MCP configuration updated.");
96
+ }
171
97
 
172
- if (sub === "feedback") {
173
- const message = rest.join(" ").trim();
174
- if (!message) throw usageError("Usage: cui mcp feedback <message> [--site reui,arc]");
175
- const result = await dashMcpTool(
176
- token,
177
- "submit_feedback",
178
- { message, ...(flags.site ? { site: String(flags.site) } : {}) },
179
- { reporter }
180
- );
181
- if (reporter.json) reporter.result(result);
182
- else reporter.note("Feedback", JSON.stringify(result, null, 2));
183
- return;
184
- }
98
+ const MCP_HELP = `Usage: cui mcp <show|init|configure>
185
99
 
186
- throw usageError(`Unknown mcp subcommand "${sub}".`, { hint: MCP_HELP });
187
- }
100
+ MCP servers are the agent's entry point; this command manages them for you:
188
101
 
189
- const MCP_HELP = `Usage: cui mcp <show|init|tools|call|me|repos|download|feedback>
102
+ show Print MCP server config (collectui + library servers) for each client
103
+ init Write/merge MCP configs into .mcp.json / .cursor / .vscode / codex
104
+ configure Same as init
190
105
 
191
- show Print MCP server config for the selected libraries and clients
192
- init Write/merge MCP configs (same as configure's MCP step)
193
- tools List tools on the CollectUI Dash MCP
194
- call <tool> Call a Dash MCP tool (--args '<json>')
195
- me Account aggregation via Dash MCP
196
- repos Downloadable snapshot repos via Dash MCP
197
- download <repo> Fresh download URL for a repo
198
- feedback <message> Submit feedback through Dash MCP (--site reui,arc)`;
106
+ The CollectUI MCP server itself is agent-only — call it from your MCP client
107
+ (it is already in .mcp.json), not through this CLI. People inspect their
108
+ account with \`cui whoami\`; the Dash site shows repos, feedback and orders.`;
@@ -1,37 +1,21 @@
1
+ import { protectGit } from "../git-privacy.mjs";
1
2
  import { existsSync, readdirSync, statSync } from "node:fs";
2
3
  import { tmpdir } from "node:os";
3
4
  import { basename, join, resolve } from "node:path";
4
- import { ChangeSet } from "../changes.mjs";
5
+ import { ChangeSet, displayPath } from "../changes.mjs";
5
6
  import { CLI_VERSION } from "../version.mjs";
6
7
  import { dashUrl, registryUrl, resolveToken } from "../config.mjs";
7
8
  import { CliError } from "../errors.mjs";
8
- import { login } from "../login.mjs";
9
+ import { login, saveSession } from "../login.mjs";
9
10
  import { fetchAccount } from "../dash.mjs";
10
11
  import { planMcpConfig, describeEntries } from "../mcp.mjs";
11
12
  import { detectPackageManager, planProjectConfig } from "../project.mjs";
12
13
  import { planManifest, planScaffold } from "../scaffold.mjs";
13
- import { selectLibs } from "./common.mjs";
14
-
15
- const DEFAULT_CLIENTS = ["claude", "cursor", "vscode"];
16
- const ALL_CLIENTS = ["claude", "cursor", "codex", "vscode"];
17
-
18
- export function resolveClients(flags) {
19
- const raw = flags.clients;
20
- if (!raw) return DEFAULT_CLIENTS;
21
- const list = String(raw)
22
- .split(/[,\s]+/)
23
- .map((s) => s.trim().toLowerCase())
24
- .filter(Boolean);
25
- if (list.includes("all")) return ALL_CLIENTS;
26
- const unknown = list.filter((c) => !ALL_CLIENTS.includes(c));
27
- if (unknown.length) {
28
- throw new CliError(`Unknown MCP client(s): ${unknown.join(", ")}`, {
29
- code: 2,
30
- hint: `Supported: ${ALL_CLIENTS.join(", ")}, all`,
31
- });
32
- }
33
- return [...new Set(list)];
34
- }
14
+ import { chooseClients, detectClientApp, selectLibs } from "./common.mjs";
15
+
16
+ // client 集/选项面已迁 common.mjs(mcp 命令与 setup 共用决策链);
17
+ // 此处 re-export 兼容既有 import
18
+ export { resolveClients, CLIENT_OPTIONS, ALL_CLIENTS } from "./common.mjs";
35
19
 
36
20
  export function resolveTarget({ flags, rest, mode }) {
37
21
  const explicit = flags.cwd || rest[0];
@@ -61,30 +45,31 @@ function isNonEmptyDir(dir) {
61
45
  export async function runSetup({ flags, rest = [], reporter, mode }) {
62
46
  reporter.intro(`CollectUI CLI · ${mode}`);
63
47
 
48
+ let pendingSession;
64
49
  let token = resolveToken(flags);
65
50
  if (!token) {
66
- if (reporter.headless) {
67
- throw new CliError("Not logged in (headless).", {
51
+ if (reporter.headless || flags["dry-run"]) {
52
+ throw new CliError("Not logged in.", {
68
53
  code: 3,
69
54
  hint: "Pass --token dpat_... or set COLLECTUI_TOKEN. `cui login` opens Dash for you in a terminal.",
70
55
  });
71
56
  }
72
57
  reporter.info("No saved session — starting login first.");
73
- const session = await login({ reporter });
74
- token = session.token;
58
+ pendingSession = await login({ reporter, persist: false });
59
+ token = pendingSession.token;
75
60
  }
76
61
  reporter.addSecrets([token]);
77
62
 
78
63
  let me;
79
64
  try {
80
- me = await fetchAccount(token, { reporter });
65
+ me = pendingSession?.me ?? (await fetchAccount(token, { reporter }));
81
66
  } catch (error) {
82
- if (error?.exitCode === 3 && !reporter.headless) {
67
+ if (error?.exitCode === 3 && !reporter.headless && !flags["dry-run"]) {
83
68
  reporter.warn("Saved PAT was rejected — starting login again.");
84
- const session = await login({ reporter });
85
- token = session.token;
69
+ pendingSession = await login({ reporter, persist: false });
70
+ token = pendingSession.token;
86
71
  reporter.addSecrets([token]);
87
- me = session.me ?? (await fetchAccount(token, { reporter }));
72
+ me = pendingSession.me ?? (await fetchAccount(token, { reporter }));
88
73
  } else {
89
74
  throw error;
90
75
  }
@@ -103,16 +88,16 @@ export async function runSetup({ flags, rest = [], reporter, mode }) {
103
88
  const template = flags.template ? String(flags.template) : "vite";
104
89
 
105
90
  if (mode === "configure" && !hasComponents) {
106
- throw new CliError(`${target} has no components.json.`, {
91
+ throw new CliError(`${displayPath(target)} has no components.json.`, {
107
92
  hint: "Point at a shadcn project, or run `cui init` to create one.",
108
93
  });
109
94
  }
110
95
  if (mode === "init" && hasComponents) {
111
- reporter.info(`${target} already has components.json — switching to configure mode (no scaffold).`);
96
+ reporter.info(`${displayPath(target)} already has components.json — switching to configure mode (no scaffold).`);
112
97
  mode = "configure";
113
98
  }
114
99
  if (mode === "init" && !hasComponents && nonEmpty && !flags.force) {
115
- throw new CliError(`Target directory is not empty: ${target}`, {
100
+ throw new CliError(`Target directory is not empty: ${displayPath(target)}`, {
116
101
  hint: "Pick an empty/new directory, or pass --force to add missing files without overwriting existing ones.",
117
102
  });
118
103
  }
@@ -128,7 +113,7 @@ export async function runSetup({ flags, rest = [], reporter, mode }) {
128
113
  !hasComponents &&
129
114
  flags.install !== false &&
130
115
  !flags["no-install"];
131
- const clients = resolveClients(flags);
116
+ const clients = await chooseClients(flags, me, reporter);
132
117
  const projectName = flags.name ? String(flags.name) : basename(target) || "collectui-app";
133
118
 
134
119
  const cs = new ChangeSet({
@@ -139,10 +124,10 @@ export async function runSetup({ flags, rest = [], reporter, mode }) {
139
124
  });
140
125
 
141
126
  if (mode === "init" && !hasComponents) {
142
- reporter.step(1, 5, `Scaffold ${template} project in ${target}`);
127
+ reporter.step(1, 5, `Scaffold ${template} project in ${displayPath(target)}`);
143
128
  planScaffold(cs, { target, name: projectName, template, pm, install });
144
129
  } else {
145
- reporter.step(1, 5, `Use existing project ${target}`);
130
+ reporter.step(1, 5, `Use existing project ${displayPath(target)}`);
146
131
  }
147
132
 
148
133
  reporter.step(2, 5, "Configure shadcn registries and license keys");
@@ -157,7 +142,7 @@ export async function runSetup({ flags, rest = [], reporter, mode }) {
157
142
 
158
143
  let mcpEntries = [];
159
144
  if (!flags["no-mcp"]) {
160
- reporter.step(3, 5, "Configure MCP servers (library + CollectUI Dash)");
145
+ reporter.step(3, 5, "Configure MCP servers (library + CollectUI MCP)");
161
146
  const mcp = planMcpConfig(cs, {
162
147
  projectDir: target,
163
148
  units,
@@ -194,6 +179,33 @@ export async function runSetup({ flags, rest = [], reporter, mode }) {
194
179
  reporter.step(5, 5, "Apply changes");
195
180
  const applied = await cs.apply();
196
181
 
182
+ // 确认框选了 No:一行都没写。不装「已配置」、不给下一步指引(cd 过去什么都没有)
183
+ if (applied.aborted) {
184
+ reporter.outro("Aborted — nothing was written. Re-run when you are ready.");
185
+ return { target, mode, libraries: libs.map((lib) => lib.site), aborted: true };
186
+ }
187
+
188
+ // dry-run 同理只看过了:指引就是「去掉 --dry-run 再跑」,cd/install/add 全不成立
189
+ if (applied.dryRun) {
190
+ if (reporter.headless) {
191
+ reporter.result({
192
+ target,
193
+ mode,
194
+ libraries: libs.map((lib) => lib.site),
195
+ units: units.map((u) => u.site),
196
+ files: applied.files?.length ?? 0,
197
+ mcpClients: clients,
198
+ mcpServers: mcpEntries.map((e) => e.serverName),
199
+ dryRun: true,
200
+ });
201
+ }
202
+ reporter.outro("Dry run complete. Re-run without --dry-run to apply.");
203
+ return { target, mode, libraries: libs.map((lib) => lib.site), dryRun: true };
204
+ }
205
+
206
+ await protectGit(target, reporter, flags);
207
+ if (pendingSession) saveSession(token, me, { reporter });
208
+
197
209
  const summary = {
198
210
  target,
199
211
  mode,
@@ -202,12 +214,13 @@ export async function runSetup({ flags, rest = [], reporter, mode }) {
202
214
  files: applied.files?.length ?? 0,
203
215
  mcpClients: clients,
204
216
  mcpServers: mcpEntries.map((e) => e.serverName),
205
- dryRun: Boolean(flags["dry-run"]),
206
217
  next: [
207
- mode === "init" && !hasComponents ? `cd ${target}` : null,
208
- install ? `dependencies installing via ${pm}` : "npm install (if dependencies are missing)",
209
- `cui add ${units[0]?.site ?? "<site>"} <component>`,
210
- "cui doctor",
218
+ mode === "init" && !hasComponents ? `cd ${cs.show(target)}` : null,
219
+ // 只有 CLI 没自动装(--no-install / configure 模式)才提示安装;
220
+ // 自动装过的场景不再出现——装完了还叫人装是语义矛盾(2026-12-06 用户反馈)
221
+ install ? null : `${pm} install`,
222
+ // 按实际选的库逐个给 add 示例——用户配了几个库就列几行
223
+ ...units.slice(0, 3).map((u) => `cui add ${u.site} <component>`),
211
224
  ].filter(Boolean),
212
225
  };
213
226
  if (reporter.headless) {
@@ -215,11 +228,17 @@ export async function runSetup({ flags, rest = [], reporter, mode }) {
215
228
  } else {
216
229
  // TTY 下不画 Result 大框;下一步行动指引是 summary 里唯一对人有用的
217
230
  reporter.note("Next steps", summary.next.join("\n"));
231
+ // dash 固定了 / 用户选了某 Agent 但本机还没装:写入不依赖安装,提示一句
232
+ // 「装好后打开项目即生效」,消除「配了却好像没用上」的困惑
233
+ const undetected = clients.filter((c) => !detectClientApp(c));
234
+ if (undetected.length) {
235
+ reporter.info(
236
+ `MCP config written for ${undetected.join(", ")} — app not detected on this machine; it picks the config up once installed.`
237
+ );
238
+ }
218
239
  }
219
240
  reporter.outro(
220
- flags["dry-run"]
221
- ? "Dry run complete. Re-run without --dry-run to apply."
222
- : `Done — ${libs.length} librar${libs.length === 1 ? "y" : "ies"} configured in ${target}.`
241
+ `Done — ${libs.length} librar${libs.length === 1 ? "y" : "ies"} configured in ${cs.show(target)}.`
223
242
  );
224
243
  return summary;
225
244
  }
@@ -5,7 +5,7 @@ import {
5
5
  resolveLibKeys,
6
6
  retiredSlugs,
7
7
  } from "../catalog.mjs";
8
- import { formatAccountHuman, maskKey } from "../dash.mjs";
8
+ import { accountBadge, formatAccountHuman, maskKey } from "../dash.mjs";
9
9
  import { resolveToken } from "../config.mjs";
10
10
  import { formatTable } from "../report.mjs";
11
11
  import { loadMe, requireToken } from "./common.mjs";
@@ -73,11 +73,28 @@ export async function whoamiCmd(flags, rest, reporter, { invokedAs } = {}) {
73
73
  rows.push({
74
74
  site: lib.site,
75
75
  cli: isOwned === false ? "-" : keys.cli ? "bound" : "-",
76
- mcp: isOwned === false ? "-" : keys.mcp ? "bound" : lib.mcp ? "-" : "generic",
76
+ // 未绑专属 MCP key:有 shadcn 通用 MCP 备选(boardui / reactbits 这类
77
+ // 「专属 + 备选」双通道库)照样可用 → generic;纯专属库无备选才落 "-"
78
+ mcp:
79
+ isOwned === false
80
+ ? "-"
81
+ : keys.mcp
82
+ ? "bound"
83
+ : lib.mcp
84
+ ? lib.shadcnUiMcp
85
+ ? "generic"
86
+ : "-"
87
+ : "generic",
77
88
  name: lib.siteName,
78
89
  owned: isOwned === null ? "?" : isOwned ? "yes" : "no",
79
90
  registries: (lib.registries ?? []).map((r) => r.scope).join(", ") || "-",
80
- mcpServer: lib.mcp ?? (lib.shadcnUiMcp ? "shadcn (generic)" : "-"),
91
+ mcpServer: lib.mcp
92
+ ? lib.shadcnUiMcp
93
+ ? `${lib.mcp} / shadcn (generic)`
94
+ : lib.mcp
95
+ : lib.shadcnUiMcp
96
+ ? "shadcn (generic)"
97
+ : "-",
81
98
  });
82
99
  }
83
100
 
@@ -112,7 +129,8 @@ export async function whoamiCmd(flags, rest, reporter, { invokedAs } = {}) {
112
129
  );
113
130
  reporter.note(
114
131
  me ? "Account" : "Catalog (not logged in)",
115
- [me ? formatAccountHuman(me.account) : null, table].filter(Boolean).join("\n\n")
132
+ [me ? formatAccountHuman(me.account) : null, table].filter(Boolean).join("\n\n"),
133
+ me ? { badge: accountBadge(me.account) } : undefined
116
134
  );
117
135
  if (extraOwned.length) {
118
136
  reporter.info(
package/src/dash.mjs CHANGED
@@ -1,44 +1,37 @@
1
+ import { CliError } from "./errors.mjs";
1
2
  import { dashUrl } from "./config.mjs";
2
- import { jsonRequest, mcpCall, toolResult } from "./http.mjs";
3
+ import { jsonRequest, mcpCall } from "./http.mjs";
3
4
 
4
5
  /**
5
6
  * CLI 专用数据面 GET /api/account(2026-12-01):{ account, sites, keys }——账户本体 +
6
7
  * 按站授权 + 绑定 key。CLI 全部命令(whoami / init / configure / add / mcp / doctor /
7
8
  * login)要的只有这些;可下仓库、订单、HP 凭据一个都用不到。
8
- * 兼容旧版 Dash:没有该路由(404),或只有首版形状(仅 account)→ 退回 /api/me 取同名切片。
9
- * (/api/me 这个 HTTP 端点 2026-12-02 已从 Dash 移除,回退只对回滚到更早版本时有意义。)
10
9
  */
11
10
  export async function fetchAccount(token, { reporter } = {}) {
12
- const request = (path) =>
13
- jsonRequest(`${dashUrl()}${path}`, {
14
- token,
15
- reporter,
16
- label: `dash ${path}`,
17
- spinner: "Loading your account from Dash…",
18
- });
19
- let data = null;
20
- try {
21
- const light = await request("/api/account");
22
- if (Array.isArray(light?.sites) && Array.isArray(light?.keys)) data = light;
23
- } catch (error) {
24
- if (error?.status !== 404) throw error;
25
- }
26
- if (!data) {
27
- const me = await request("/api/me");
28
- data = { account: me?.account ?? null, sites: me?.sites ?? [], keys: me?.keys ?? [] };
11
+ const data = await jsonRequest(`${dashUrl()}/api/account`, {
12
+ token, reporter, label: "dash /api/account", spinner: "Loading your account from Dash…",
13
+ });
14
+ if (!data?.account || !Array.isArray(data.sites) || !Array.isArray(data.keys)) {
15
+ throw new CliError("Invalid /api/account response: expected account, sites and keys.");
29
16
  }
30
17
  return data;
31
18
  }
32
19
 
33
- /** `cui whoami` 的账户段:账户名 + uid、注册时间、徽章——最基本的账户信息,到此为止。 */
20
+ /** `cui whoami` 的账户段:uid、注册时间、徽章——最基本的账户信息,到此为止。
21
+ * 账户名不进正文(上移到面板标题栏右侧徽标,见 reporter.note 的 badge)。 */
34
22
  export function formatAccountHuman(account) {
35
23
  if (!account) return "No account data.";
36
- const lines = [`Account: ${account.username ?? "(unknown)"} uid=${account.uid ?? "?"}`];
24
+ const lines = [`Uid: ${account.uid ?? "?"}`];
37
25
  if (account.createdAt) lines.push(`Created: ${account.createdAt}`);
38
26
  if (account.badges?.length) lines.push(`Badges: ${account.badges.join(", ")}`);
39
27
  return lines.join("\n");
40
28
  }
41
29
 
30
+ /** 面板标题栏徽标:账户名(正文第一行让位给 Uid)。 */
31
+ export function accountBadge(account) {
32
+ return account?.username ?? "(unknown)";
33
+ }
34
+
42
35
  /** Dash MCP:stateless JSON-RPC,直接 tools/list 或 tools/call。 */
43
36
  export async function dashMcpTools(token, { reporter } = {}) {
44
37
  const result = await mcpCall({
@@ -50,34 +43,6 @@ export async function dashMcpTools(token, { reporter } = {}) {
50
43
  return result?.tools ?? [];
51
44
  }
52
45
 
53
- export async function dashMcpTool(token, name, args = {}, { reporter } = {}) {
54
- const result = await mcpCall({
55
- base: dashUrl(),
56
- token,
57
- method: "tools/call",
58
- params: { name, arguments: args },
59
- reporter,
60
- });
61
- if (result?.isError) {
62
- const text = (result.content ?? []).map((c) => c.text).filter(Boolean).join("\n");
63
- throw new Error(text || `Dash MCP tool ${name} failed`);
64
- }
65
- return toolResult(result);
66
- }
67
-
68
- /** 账户全量聚合(可下仓库、HP 凭据、订单)只有 Dash MCP 的 me 工具给——REST 端点 /api/me 已于 2026-12-02 移除。 */
69
- export async function dashMe(token, { reporter } = {}) {
70
- return dashMcpTool(token, "me", {}, { reporter });
71
- }
72
-
73
- /** 把 account aggregation 里的明文 key 登记给 reporter,确保输出脱敏。 */
74
- export function addMeSecrets(reporter, me) {
75
- reporter?.addSecrets?.((me?.keys ?? []).map((k) => k.key).filter(Boolean));
76
- const hp = me?.herouiHp;
77
- if (hp && typeof hp === "object") {
78
- reporter?.addSecrets?.(Object.values(hp).filter((v) => typeof v === "string"));
79
- }
80
- }
81
46
 
82
47
  export function maskKey(value) {
83
48
  if (!value || typeof value !== "string") return "—";
@@ -85,49 +50,3 @@ export function maskKey(value) {
85
50
  return `${value.slice(0, 6)}…${value.slice(-4)}`;
86
51
  }
87
52
 
88
- export function formatMeHuman(me) {
89
- if (!me) return "No account data.";
90
- const lines = [];
91
- const account = me.account ?? {};
92
- lines.push(`Account: ${account.username ?? "(unknown)"} uid=${account.uid ?? "?"}`);
93
- if (account.createdAt) lines.push(`Created: ${account.createdAt}`);
94
- if (account.badges?.length) lines.push(`Badges: ${account.badges.join(", ")}`);
95
-
96
- const sites = me.sites ?? [];
97
- lines.push("");
98
- lines.push(`Libraries with access (${sites.length}):`);
99
- if (sites.length === 0) lines.push(" (none)");
100
- for (const site of sites) {
101
- const scopes = Array.isArray(site.scopes) && site.scopes.length ? site.scopes.join(", ") : "all";
102
- lines.push(` - ${site.slug} (${site.name}) — ${scopes}${site.expiresAt ? ` · until ${site.expiresAt}` : ""}`);
103
- }
104
-
105
- const keys = me.keys ?? [];
106
- lines.push("");
107
- lines.push(`Bound keys (${keys.length}):`);
108
- if (keys.length === 0) lines.push(" (none)");
109
- for (const key of keys) {
110
- lines.push(` - ${key.source} [${key.kind}] site=${key.site ?? "?"} ${maskKey(key.key)}`);
111
- }
112
-
113
- const repos = me.repos ?? [];
114
- lines.push("");
115
- lines.push(`Downloadable repos (${repos.length}):`);
116
- if (repos.length === 0) lines.push(" (none)");
117
- for (const repo of repos) lines.push(` - ${repo}`);
118
-
119
- const orders = me.orders ?? {};
120
- lines.push("");
121
- lines.push(`Orders: ${orders.paidCount ?? 0} paid, ${orders.pendingCount ?? 0} pending`);
122
- return lines.join("\n");
123
- }
124
-
125
- export function formatTools(tools) {
126
- return tools
127
- .map((tool) => {
128
- const required = tool.inputSchema?.required ?? [];
129
- const props = Object.keys(tool.inputSchema?.properties ?? {});
130
- return `- ${tool.name}${required.length ? ` (required: ${required.join(", ")})` : ""}\n ${tool.description ?? ""}\n args: ${props.join(", ") || "none"}`;
131
- })
132
- .join("\n");
133
- }
@@ -0,0 +1,77 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+
5
+ const local = ['.env.local', '.mcp.json', '.cursor/mcp.json', '.vscode/mcp.json', '.collectui'];
6
+ const component = 'components.json';
7
+ function git(cwd, ...args) {
8
+ return spawnSync('git', ['--literal-pathspecs', '-C', cwd, ...args], {encoding:'utf8', timeout:5000, env:{...process.env,GIT_OPTIONAL_LOCKS:'0',GIT_NO_LAZY_FETCH:'1',GIT_TERMINAL_PROMPT:'0'}});
9
+ }
10
+ const entries = s => s.split('\0').filter(Boolean);
11
+ export function auditGit(cwd) {
12
+ const result = {messages:[], tracked:[], uncertain:false};
13
+ const root = git(cwd, 'rev-parse','--show-toplevel');
14
+ if (root.status !== 0) return result;
15
+ const read = (...args) => {
16
+ const r = git(cwd,...args);
17
+ if (r.status !== 0) { result.uncertain = true; return ''; }
18
+ return r.stdout;
19
+ };
20
+ const prefix = read('rev-parse','--show-prefix').trimEnd();
21
+ result.exclude = read('rev-parse','--path-format=absolute','--git-path','info/exclude').trimEnd();
22
+ result.prefix = prefix;
23
+ result.tracked = entries(read('ls-files','-z','--',...local));
24
+ if (result.tracked.length) result.messages.push(`索引中有本地专用配置(可能含凭据):${result.tracked.map(p=>JSON.stringify(p)).join('、')}。忽略规则不能取消跟踪。`);
25
+ if (entries(read('ls-files','-z','--',component)).length) {
26
+ const attr = entries(read('check-attr','-z','filter','--',component))[2];
27
+ if (attr !== 'collectui') result.messages.push('components.json:此路径未匹配 CollectUI Git filter;忽略规则不保护它,请核对索引并按需设置 Guard。');
28
+ try {
29
+ const data = JSON.parse(read('show',`:${prefix}${component}`));
30
+ if (Object.values(data.registries ?? {}).some(e => /registry\.collectui\.pro/i.test(typeof e==='string'?e:e?.url) || (e && typeof e==='object' && (Object.keys(e.headers??{}).length || Object.keys(e.params??{}).length)))) result.messages.push('components.json:索引版含镜像或鉴权配置。请配置 Guard,重新暂存并复核;不要取消跟踪此文件。');
31
+ } catch { result.uncertain=true; }
32
+ }
33
+ const hasHead = git(cwd,'rev-parse','--verify','HEAD').status===0;
34
+ if (hasHead) {
35
+ const files=entries(read('ls-tree','-r','-z','--name-only','HEAD','--',...local));
36
+ if(files.length) result.messages.push(`当前提交包含本地专用配置:${files.map(p=>JSON.stringify(p)).join('、')}。`);
37
+ }
38
+ for (const remote of [false,true]) {
39
+ const refs=remote?['--remotes']:['--branches','--tags',...(hasHead?['HEAD']:[])];
40
+ const files=entries(read('log',...refs,'--format=','--name-only','-z','--no-renames','--',...local));
41
+ const marker=read('log',...refs,'-1','--format=%h','--no-ext-diff','--no-textconv','-G','registry[.]collectui[.]pro|"(headers|params)"','--',component).trim();
42
+ if (remote && (files.length || marker)) result.remoteHit = true;
43
+ if(files.length || marker) result.messages.push(`${remote?'本机远端跟踪引用的历史':'本地提交历史'}中发现潜在敏感配置:${[...new Set([...files,...(marker?[prefix+component]:[])])].map(p=>JSON.stringify(p)).join('、')}。${remote?'按已外发处理:先撤销或轮换相关凭据,核查访问记录;停止跟踪不会清除旧提交。':'取消跟踪不影响旧提交。'}`);
44
+ }
45
+ // 不确定态只对「有历史可查却查不全」的仓库报:全新仓库(还没有任何提交)
46
+ // 没有历史可言,谈不上外发风险——cui init 刚 git init 完的场景不该弹这条。
47
+ // 文案保持通俗(2026-12-06 用户反馈:术语化的「远端跟踪引用/浅克隆」看不懂)。
48
+ const hasRemotes = read('for-each-ref','--count=1','--format=%(objectname)','refs/remotes').trim();
49
+ const shallow = read('rev-parse','--is-shallow-repository').trim()==='true';
50
+ if (hasHead && (!hasRemotes || shallow)) result.uncertain=true;
51
+ if(result.uncertain) result.messages.push('git 历史无法完整检查(仓库没有远端,或是浅克隆),不能确认这些文件从未推送出去过。');
52
+ return result;
53
+ }
54
+
55
+ export async function protectGit(cwd, reporter, flags) {
56
+ const audit=auditGit(cwd);
57
+ if (flags["dry-run"] || !audit.exclude) return;
58
+ for(const message of audit.messages) reporter.warn?.(message);
59
+ // 将规则锚定在实际项目目录,兼容 monorepo 与 linked worktree。
60
+ const escape = s => s.replace(/[\\*?\[\] ]/g,'\\$&');
61
+ const rules=local.filter(p=>existsSync(join(cwd,p))).map(p=>'/'+escape(audit.prefix+p)+(p==='.collectui'?'/':''));
62
+ let text='';
63
+ try {text=readFileSync(audit.exclude,'utf8');} catch(e){if(e.code!=='ENOENT') throw e;}
64
+ const missing=rules.filter(p=>!text.split(/\r?\n/).includes(p));
65
+ if(missing.length){ mkdirSync(dirname(audit.exclude),{recursive:true}); writeFileSync(audit.exclude,text+(text&&!text.endsWith('\n')?'\n':'')+missing.join('\n')+'\n'); }
66
+ if (flags.yes || reporter.headless || !reporter.confirmCleanup) return;
67
+ if (audit.remoteHit && await reporter.confirmCleanup('是否查看已推送历史的清理步骤?不会修改仓库或远端。')) {
68
+ reporter.info('先轮换凭据,保存安全备份;与协作者确认受影响分支、标签及重写窗口。在隔离副本清理并复核所有引用,再由管理员单独批准更新远端。通知成员重新克隆,联系托管方处理 PR 引用和缓存,fork 和已下载副本无法保证收回。');
69
+ }
70
+ if (!audit.tracked.length) return;
71
+ if (!await reporter.confirmCleanup('是否仅从 Git 索引移除上述本地专用配置?保留磁盘文件,不清理历史,也不推送。')) return;
72
+ if(audit.tracked.some(p=>!lstatSync(join(cwd,p),{throwIfNoEntry:false})?.isFile()) || git(cwd,'diff','--quiet','--',...audit.tracked).status!==0 || git(cwd,'ls-files','--unmerged','--',...audit.tracked).stdout?.length) {
73
+ reporter.warn('文件缺失、有冲突或索引与工作区不同,未取消跟踪。请先人工核对。'); return;
74
+ }
75
+ const removed=git(cwd,'rm','--cached','--',...audit.tracked);
76
+ reporter[removed.status===0?'info':'warn'](removed.status===0?'已停止跟踪,文件仍在磁盘。请检查暂存差异后自行提交。':'Git 未能安全取消跟踪,请人工核对。');
77
+ }