@collectui/cli 0.0.0-stage → 0.2.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 +204 -2
- package/package.json +37 -4
- package/src/args.mjs +90 -0
- package/src/catalog.mjs +386 -0
- package/src/changes.mjs +311 -0
- package/src/cli.mjs +174 -0
- package/src/commands/add.mjs +186 -0
- package/src/commands/common.mjs +125 -0
- package/src/commands/configure.mjs +5 -0
- package/src/commands/dash.mjs +92 -0
- package/src/commands/doctor.mjs +155 -0
- package/src/commands/init.mjs +5 -0
- package/src/commands/libs.mjs +49 -0
- package/src/commands/login.mjs +26 -0
- package/src/commands/mcp.mjs +190 -0
- package/src/commands/setup.mjs +221 -0
- package/src/commands/skill.mjs +26 -0
- package/src/commands/whoami.mjs +17 -0
- package/src/config.mjs +94 -0
- package/src/dash.mjs +111 -0
- package/src/errors.mjs +22 -0
- package/src/http.mjs +201 -0
- package/src/login.mjs +253 -0
- package/src/mcp.mjs +389 -0
- package/src/project.mjs +258 -0
- package/src/report.mjs +222 -0
- package/src/scaffold.mjs +459 -0
- package/src/skill/SKILL.md +120 -0
- package/src/version.mjs +5 -0
package/src/config.mjs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 本地配置(~/.collectui/config.json,chmod 600)。
|
|
7
|
+
* 只存 PAT 明文和账户快照;密钥不进任何项目文件之外的地方。
|
|
8
|
+
*
|
|
9
|
+
* 环境变量覆盖(Agent / CI 用):
|
|
10
|
+
* COLLECTUI_TOKEN PAT(优先于本地配置)
|
|
11
|
+
* COLLECTUI_DASH_URL Dash 基址(默认 https://dash.collectui.pro)
|
|
12
|
+
* COLLECTUI_REGISTRY_URL Registry 基址(默认 https://registry.collectui.pro)
|
|
13
|
+
* COLLECTUI_HOME 配置目录(测试隔离用)
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_DASH_URL = "https://dash.collectui.pro";
|
|
17
|
+
export const DEFAULT_REGISTRY_URL = "https://registry.collectui.pro";
|
|
18
|
+
export const DASH_MCP_PATH = "/api/mcp";
|
|
19
|
+
|
|
20
|
+
export function configDir() {
|
|
21
|
+
return process.env.COLLECTUI_HOME || join(homedir(), ".collectui");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function configFile() {
|
|
25
|
+
return join(configDir(), "config.json");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function dashUrl() {
|
|
29
|
+
return (process.env.COLLECTUI_DASH_URL || DEFAULT_DASH_URL).replace(/\/+$/, "");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function registryUrl() {
|
|
33
|
+
return (process.env.COLLECTUI_REGISTRY_URL || DEFAULT_REGISTRY_URL).replace(/\/+$/, "");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function readConfig() {
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(readFileSync(configFile(), "utf8"));
|
|
39
|
+
} catch {
|
|
40
|
+
return {};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function writeConfig(patch) {
|
|
45
|
+
const dir = configDir();
|
|
46
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
47
|
+
const next = { ...readConfig(), ...patch };
|
|
48
|
+
writeFileSync(configFile(), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
|
49
|
+
try {
|
|
50
|
+
chmodSync(configFile(), 0o600);
|
|
51
|
+
} catch {
|
|
52
|
+
// Windows 无权限位,忽略
|
|
53
|
+
}
|
|
54
|
+
return next;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function clearConfig() {
|
|
58
|
+
const file = configFile();
|
|
59
|
+
if (!existsSync(file)) return false;
|
|
60
|
+
writeFileSync(file, "{}\n", { mode: 0o600 });
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** PAT 解析顺序:--token > COLLECTUI_TOKEN > DASH_PAT > 本地配置。 */
|
|
65
|
+
export function resolveToken(flags = {}) {
|
|
66
|
+
if (flags.token) return String(flags.token);
|
|
67
|
+
if (process.env.COLLECTUI_TOKEN) return process.env.COLLECTUI_TOKEN.trim();
|
|
68
|
+
if (process.env.DASH_PAT) return process.env.DASH_PAT.trim();
|
|
69
|
+
const token = readConfig().token;
|
|
70
|
+
return typeof token === "string" && token.trim() ? token.trim() : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function tokenSource(flags = {}) {
|
|
74
|
+
if (flags.token) return "--token";
|
|
75
|
+
if (process.env.COLLECTUI_TOKEN) return "COLLECTUI_TOKEN";
|
|
76
|
+
if (process.env.DASH_PAT) return "DASH_PAT";
|
|
77
|
+
return readConfig().token ? configFile() : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 所有已知密钥都登记给 reporter,日志里统一脱敏。 */
|
|
81
|
+
export function collectSecrets(me, token) {
|
|
82
|
+
const out = new Set();
|
|
83
|
+
if (token) out.add(token);
|
|
84
|
+
for (const k of me?.keys ?? []) {
|
|
85
|
+
if (typeof k.key === "string" && k.key.length >= 8) out.add(k.key);
|
|
86
|
+
}
|
|
87
|
+
const hp = me?.herouiHp;
|
|
88
|
+
if (hp && typeof hp === "object") {
|
|
89
|
+
for (const v of Object.values(hp)) {
|
|
90
|
+
if (typeof v === "string" && v.length >= 8) out.add(v);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return [...out];
|
|
94
|
+
}
|
package/src/dash.mjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { dashUrl } from "./config.mjs";
|
|
2
|
+
import { jsonRequest, mcpCall, toolResult } from "./http.mjs";
|
|
3
|
+
|
|
4
|
+
/** Dash REST 聚合(与 dash MCP me 工具同源,见 apps/user-dashboard/lib/agent-api.ts)。 */
|
|
5
|
+
export async function fetchMe(token, { reporter } = {}) {
|
|
6
|
+
return jsonRequest(`${dashUrl()}/api/me`, {
|
|
7
|
+
token,
|
|
8
|
+
reporter,
|
|
9
|
+
label: "dash /api/me",
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Dash MCP:stateless JSON-RPC,直接 tools/list 或 tools/call。 */
|
|
14
|
+
export async function dashMcpTools(token, { reporter } = {}) {
|
|
15
|
+
const result = await mcpCall({
|
|
16
|
+
base: dashUrl(),
|
|
17
|
+
token,
|
|
18
|
+
method: "tools/list",
|
|
19
|
+
reporter,
|
|
20
|
+
});
|
|
21
|
+
return result?.tools ?? [];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function dashMcpTool(token, name, args = {}, { reporter } = {}) {
|
|
25
|
+
const result = await mcpCall({
|
|
26
|
+
base: dashUrl(),
|
|
27
|
+
token,
|
|
28
|
+
method: "tools/call",
|
|
29
|
+
params: { name, arguments: args },
|
|
30
|
+
reporter,
|
|
31
|
+
});
|
|
32
|
+
if (result?.isError) {
|
|
33
|
+
const text = (result.content ?? []).map((c) => c.text).filter(Boolean).join("\n");
|
|
34
|
+
throw new Error(text || `Dash MCP tool ${name} failed`);
|
|
35
|
+
}
|
|
36
|
+
return toolResult(result);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function dashMe(token, { reporter } = {}) {
|
|
40
|
+
try {
|
|
41
|
+
return await dashMcpTool(token, "me", {}, { reporter });
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (/404|not enabled/i.test(error.message)) {
|
|
44
|
+
reporter?.warn("Dash MCP is not enabled; falling back to GET /api/me.");
|
|
45
|
+
return fetchMe(token, { reporter });
|
|
46
|
+
}
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 把 account aggregation 里的明文 key 登记给 reporter,确保输出脱敏。 */
|
|
52
|
+
export function addMeSecrets(reporter, me) {
|
|
53
|
+
reporter?.addSecrets?.((me?.keys ?? []).map((k) => k.key).filter(Boolean));
|
|
54
|
+
const hp = me?.herouiHp;
|
|
55
|
+
if (hp && typeof hp === "object") {
|
|
56
|
+
reporter?.addSecrets?.(Object.values(hp).filter((v) => typeof v === "string"));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function maskKey(value) {
|
|
61
|
+
if (!value || typeof value !== "string") return "—";
|
|
62
|
+
if (value.length <= 10) return `${value.slice(0, 3)}…`;
|
|
63
|
+
return `${value.slice(0, 6)}…${value.slice(-4)}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function formatMeHuman(me) {
|
|
67
|
+
if (!me) return "No account data.";
|
|
68
|
+
const lines = [];
|
|
69
|
+
const account = me.account ?? {};
|
|
70
|
+
lines.push(`Account: ${account.username ?? "(unknown)"} uid=${account.uid ?? "?"}`);
|
|
71
|
+
if (account.createdAt) lines.push(`Created: ${account.createdAt}`);
|
|
72
|
+
if (account.badges?.length) lines.push(`Badges: ${account.badges.join(", ")}`);
|
|
73
|
+
|
|
74
|
+
const sites = me.sites ?? [];
|
|
75
|
+
lines.push("");
|
|
76
|
+
lines.push(`Libraries with access (${sites.length}):`);
|
|
77
|
+
if (sites.length === 0) lines.push(" (none)");
|
|
78
|
+
for (const site of sites) {
|
|
79
|
+
const scopes = Array.isArray(site.scopes) && site.scopes.length ? site.scopes.join(", ") : "all";
|
|
80
|
+
lines.push(` - ${site.slug} (${site.name}) — ${scopes}${site.expiresAt ? ` · until ${site.expiresAt}` : ""}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const keys = me.keys ?? [];
|
|
84
|
+
lines.push("");
|
|
85
|
+
lines.push(`Bound keys (${keys.length}):`);
|
|
86
|
+
if (keys.length === 0) lines.push(" (none)");
|
|
87
|
+
for (const key of keys) {
|
|
88
|
+
lines.push(` - ${key.source} [${key.kind}] site=${key.site ?? "?"} ${maskKey(key.key)}`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const repos = me.repos ?? [];
|
|
92
|
+
lines.push("");
|
|
93
|
+
lines.push(`Downloadable repos (${repos.length}):`);
|
|
94
|
+
if (repos.length === 0) lines.push(" (none)");
|
|
95
|
+
for (const repo of repos) lines.push(` - ${repo}`);
|
|
96
|
+
|
|
97
|
+
const orders = me.orders ?? {};
|
|
98
|
+
lines.push("");
|
|
99
|
+
lines.push(`Orders: ${orders.paidCount ?? 0} paid, ${orders.pendingCount ?? 0} pending`);
|
|
100
|
+
return lines.join("\n");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function formatTools(tools) {
|
|
104
|
+
return tools
|
|
105
|
+
.map((tool) => {
|
|
106
|
+
const required = tool.inputSchema?.required ?? [];
|
|
107
|
+
const props = Object.keys(tool.inputSchema?.properties ?? {});
|
|
108
|
+
return `- ${tool.name}${required.length ? ` (required: ${required.join(", ")})` : ""}\n ${tool.description ?? ""}\n args: ${props.join(", ") || "none"}`;
|
|
109
|
+
})
|
|
110
|
+
.join("\n");
|
|
111
|
+
}
|
package/src/errors.mjs
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** CLI 统一错误:message 给用户看,code 决定退出码(1 通用 / 2 用法 / 3 认证)。 */
|
|
2
|
+
export class CliError extends Error {
|
|
3
|
+
constructor(message, { code = 1, hint } = {}) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "CliError";
|
|
6
|
+
this.exitCode = code;
|
|
7
|
+
this.hint = hint;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function usageError(message, hint) {
|
|
12
|
+
return new CliError(message, { code: 2, hint: normalizeHint(hint) });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function authError(message, hint) {
|
|
16
|
+
return new CliError(message, { code: 3, hint: normalizeHint(hint) });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function normalizeHint(hint) {
|
|
20
|
+
if (!hint) return undefined;
|
|
21
|
+
return typeof hint === "string" ? hint : hint.hint;
|
|
22
|
+
}
|
package/src/http.mjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { CliError } from "./errors.mjs";
|
|
2
|
+
|
|
3
|
+
const VERSION = "0.1.0";
|
|
4
|
+
const UA = `collectui-cli/${VERSION} (Node.js ${process.version}; +https://dash.collectui.pro)`;
|
|
5
|
+
|
|
6
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
7
|
+
|
|
8
|
+
function shouldRetry(status) {
|
|
9
|
+
return status === 408 || status === 425 || status === 429 || status >= 500;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 统一 HTTP 入口:超时、退避重试、请求/响应日志(transparency)。
|
|
14
|
+
* 只对幂等方法(GET/HEAD)自动重试;POST 由调用方决定(MCP tools/call 重试可能重复提交)。
|
|
15
|
+
*/
|
|
16
|
+
export async function httpRequest(url, options = {}) {
|
|
17
|
+
const {
|
|
18
|
+
method = "GET",
|
|
19
|
+
headers = {},
|
|
20
|
+
body,
|
|
21
|
+
token,
|
|
22
|
+
timeout = 20_000,
|
|
23
|
+
retries = 2,
|
|
24
|
+
retryUnsafe = false,
|
|
25
|
+
reporter,
|
|
26
|
+
label,
|
|
27
|
+
} = options;
|
|
28
|
+
|
|
29
|
+
const finalHeaders = {
|
|
30
|
+
"User-Agent": UA,
|
|
31
|
+
Accept: "application/json, text/event-stream, text/plain, */*",
|
|
32
|
+
...headers,
|
|
33
|
+
};
|
|
34
|
+
if (token) finalHeaders.Authorization = `Bearer ${token}`;
|
|
35
|
+
if (body !== undefined && !finalHeaders["Content-Type"]) {
|
|
36
|
+
finalHeaders["Content-Type"] = "application/json";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const canRetry = retryUnsafe || method === "GET" || method === "HEAD";
|
|
40
|
+
const attempts = canRetry ? retries + 1 : 1;
|
|
41
|
+
let lastError;
|
|
42
|
+
|
|
43
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
44
|
+
const started = Date.now();
|
|
45
|
+
reporter?.http?.({ phase: "request", method, url, label, attempt, max: attempts });
|
|
46
|
+
let res;
|
|
47
|
+
try {
|
|
48
|
+
res = await fetch(url, {
|
|
49
|
+
method,
|
|
50
|
+
headers: finalHeaders,
|
|
51
|
+
body,
|
|
52
|
+
signal: AbortSignal.timeout(timeout),
|
|
53
|
+
redirect: "follow",
|
|
54
|
+
});
|
|
55
|
+
} catch (error) {
|
|
56
|
+
const ms = Date.now() - started;
|
|
57
|
+
reporter?.http?.({ phase: "error", method, url, label, ms, error: error.message });
|
|
58
|
+
lastError = error;
|
|
59
|
+
if (attempt < attempts) {
|
|
60
|
+
await sleep(500 * attempt + Math.floor(Math.random() * 250));
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
throw new CliError(`Network request failed: ${method} ${url} — ${error.message}`, {
|
|
64
|
+
hint: "Check your network / proxy, then retry. Dash might be temporarily unreachable.",
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const text = await res.text();
|
|
69
|
+
const ms = Date.now() - started;
|
|
70
|
+
reporter?.http?.({
|
|
71
|
+
phase: "response",
|
|
72
|
+
method,
|
|
73
|
+
url,
|
|
74
|
+
label,
|
|
75
|
+
status: res.status,
|
|
76
|
+
ms,
|
|
77
|
+
bytes: text.length,
|
|
78
|
+
attempt,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
if (res.ok) return { res, text };
|
|
82
|
+
|
|
83
|
+
if (attempt < attempts && shouldRetry(res.status)) {
|
|
84
|
+
await sleep(500 * attempt + Math.floor(Math.random() * 250));
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { res, text, error: true };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
throw new CliError(`Network request failed: ${method} ${url} — ${lastError?.message ?? "unknown error"}`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function jsonRequest(url, options = {}) {
|
|
95
|
+
const out = await httpRequest(url, options);
|
|
96
|
+
let parsed = null;
|
|
97
|
+
try {
|
|
98
|
+
parsed = out.text ? JSON.parse(out.text) : null;
|
|
99
|
+
} catch {
|
|
100
|
+
parsed = null;
|
|
101
|
+
}
|
|
102
|
+
if (!out.res.ok) {
|
|
103
|
+
const message =
|
|
104
|
+
parsed?.error ||
|
|
105
|
+
parsed?.message ||
|
|
106
|
+
out.text.slice(0, 300) ||
|
|
107
|
+
`HTTP ${out.res.status}`;
|
|
108
|
+
throw new CliError(`${options.label ?? url} failed: ${message}`, {
|
|
109
|
+
code: out.res.status === 401 || out.res.status === 403 ? 3 : 1,
|
|
110
|
+
hint:
|
|
111
|
+
out.res.status === 401
|
|
112
|
+
? "Run `collectui login` again (or pass --token) — your PAT may be missing, revoked or expired."
|
|
113
|
+
: undefined,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
if (parsed === null && out.text) {
|
|
117
|
+
throw new CliError(`Expected JSON from ${url}, got: ${out.text.slice(0, 120)}`);
|
|
118
|
+
}
|
|
119
|
+
return parsed;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* MCP Streamable HTTP 单次调用(stateless,无会话)。
|
|
124
|
+
* 响应可能是 application/json,也可能是 SSE(data: {...})。
|
|
125
|
+
*/
|
|
126
|
+
export async function mcpCall({ base, token, method, params, reporter, id = 1 }) {
|
|
127
|
+
const url = `${base.replace(/\/+$/, "")}/api/mcp`;
|
|
128
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
129
|
+
const out = await httpRequest(url, {
|
|
130
|
+
method: "POST",
|
|
131
|
+
token,
|
|
132
|
+
body,
|
|
133
|
+
reporter,
|
|
134
|
+
label: `mcp:${method}`,
|
|
135
|
+
headers: { "Content-Type": "application/json" },
|
|
136
|
+
timeout: 30_000,
|
|
137
|
+
retries: 0,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
let text = out.text;
|
|
141
|
+
const ct = out.res.headers.get("content-type") || "";
|
|
142
|
+
if (ct.includes("event-stream")) {
|
|
143
|
+
const data = text
|
|
144
|
+
.split("\n")
|
|
145
|
+
.filter((line) => line.startsWith("data:"))
|
|
146
|
+
.map((line) => line.slice(5).trim())
|
|
147
|
+
.filter(Boolean)
|
|
148
|
+
.pop();
|
|
149
|
+
if (data) text = data;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let parsed;
|
|
153
|
+
try {
|
|
154
|
+
parsed = JSON.parse(text);
|
|
155
|
+
} catch {
|
|
156
|
+
if (out.res.status === 404) {
|
|
157
|
+
throw new CliError("Dash MCP is not enabled for this server/account (HTTP 404).", {
|
|
158
|
+
hint: "Ask the operator to enable dashFeatures.mcpServer, or use `collectui whoami` / the REST API instead.",
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
if (!out.res.ok) {
|
|
162
|
+
throw new CliError(`Dash MCP request failed (HTTP ${out.res.status}): ${text.slice(0, 300)}`);
|
|
163
|
+
}
|
|
164
|
+
throw new CliError(`Unexpected Dash MCP response: ${text.slice(0, 300)}`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (!out.res.ok) {
|
|
168
|
+
if (out.res.status === 404) {
|
|
169
|
+
throw new CliError("Dash MCP is not enabled for this server/account (HTTP 404).", {
|
|
170
|
+
hint: "Ask the operator to enable dashFeatures.mcpServer, or use `collectui whoami` / the REST API instead.",
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
throw new CliError(
|
|
174
|
+
parsed?.error?.message || `Dash MCP HTTP ${out.res.status}`,
|
|
175
|
+
{ code: out.res.status === 401 ? 3 : 1 }
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
if (parsed.error) {
|
|
179
|
+
throw new CliError(
|
|
180
|
+
`Dash MCP error ${parsed.error.code}: ${parsed.error.message}`,
|
|
181
|
+
{ code: parsed.error.code === -32001 ? 3 : 1 }
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
return parsed.result;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** MCP tools/call 的文本结果 → 尽量解析成结构化数据。 */
|
|
188
|
+
export function toolResult(result) {
|
|
189
|
+
if (!result) return null;
|
|
190
|
+
if (result.structuredContent !== undefined) return result.structuredContent;
|
|
191
|
+
const text = (result.content ?? [])
|
|
192
|
+
.filter((c) => c?.type === "text" && typeof c.text === "string")
|
|
193
|
+
.map((c) => c.text)
|
|
194
|
+
.join("\n");
|
|
195
|
+
if (!text) return null;
|
|
196
|
+
try {
|
|
197
|
+
return JSON.parse(text);
|
|
198
|
+
} catch {
|
|
199
|
+
return text;
|
|
200
|
+
}
|
|
201
|
+
}
|
package/src/login.mjs
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import * as p from "@clack/prompts";
|
|
5
|
+
import { clearConfig, configFile, dashUrl, writeConfig } from "./config.mjs";
|
|
6
|
+
import { authError } from "./errors.mjs";
|
|
7
|
+
import { jsonRequest } from "./http.mjs";
|
|
8
|
+
|
|
9
|
+
/** 校验 PAT 并返回 /api/me 聚合。 */
|
|
10
|
+
export async function verifyToken(token, { reporter } = {}) {
|
|
11
|
+
return jsonRequest(`${dashUrl()}/api/me`, {
|
|
12
|
+
token,
|
|
13
|
+
reporter,
|
|
14
|
+
label: "dash /api/me",
|
|
15
|
+
headers: { Accept: "application/json" },
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function saveSession(token, me, { reporter } = {}) {
|
|
20
|
+
const account = me?.account ?? null;
|
|
21
|
+
writeConfig({
|
|
22
|
+
token,
|
|
23
|
+
account,
|
|
24
|
+
dashUrl: dashUrl(),
|
|
25
|
+
savedAt: new Date().toISOString(),
|
|
26
|
+
});
|
|
27
|
+
reporter?.success(
|
|
28
|
+
account?.username
|
|
29
|
+
? `Logged in as ${account.username} (${account.uid}).`
|
|
30
|
+
: "Logged in. Token saved locally."
|
|
31
|
+
);
|
|
32
|
+
return account;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 浏览器登录:
|
|
37
|
+
* 1. 自动打开 Dash 登录页(登录后就是 dashboard,右上角「API 密钥」可建 PAT)
|
|
38
|
+
* 2. 同时启动 127.0.0.1 回调监听;Dash 后续若支持 CLI 配对可直接回传 token
|
|
39
|
+
* 3. 当前版本在浏览器里建好 PAT 后粘贴回终端(隐藏输入)
|
|
40
|
+
*
|
|
41
|
+
* 无头模式(--json / 非 TTY):从 --token / 环境变量 / stdin 取 PAT,绝不弹交互。
|
|
42
|
+
*/
|
|
43
|
+
export async function login({
|
|
44
|
+
token: providedToken,
|
|
45
|
+
noOpen = false,
|
|
46
|
+
timeout = 180_000,
|
|
47
|
+
reporter,
|
|
48
|
+
skipVerify = false,
|
|
49
|
+
}) {
|
|
50
|
+
reporter.intro("CollectUI CLI · login");
|
|
51
|
+
|
|
52
|
+
let token = providedToken || process.env.COLLECTUI_TOKEN || process.env.DASH_PAT || "";
|
|
53
|
+
token = token.trim();
|
|
54
|
+
|
|
55
|
+
if (!token) {
|
|
56
|
+
if (reporter.headless) {
|
|
57
|
+
const piped = await readStdin(3_000);
|
|
58
|
+
if (piped.trim()) token = piped.trim();
|
|
59
|
+
}
|
|
60
|
+
if (!token && reporter.headless) {
|
|
61
|
+
throw authError("No Dash PAT provided in headless mode.", {
|
|
62
|
+
hint:
|
|
63
|
+
"Pass --token dpat_... or set COLLECTUI_TOKEN. Create a PAT at " +
|
|
64
|
+
`${dashUrl()} (top-right 「API 密钥」).`,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const callback = startCallbackServer();
|
|
70
|
+
try {
|
|
71
|
+
if (!token) {
|
|
72
|
+
const loginUrl = `${dashUrl()}/login?returnTo=%2F`;
|
|
73
|
+
reporter.info("Dashboard: " + loginUrl);
|
|
74
|
+
reporter.info("Create a PAT: top-right 「API 密钥」 → 新建(label 可填 collectui-cli)→ 复制。");
|
|
75
|
+
if (!noOpen) {
|
|
76
|
+
const opened = openBrowser(loginUrl);
|
|
77
|
+
if (opened) reporter.info("Opened the Dash login page in your browser.");
|
|
78
|
+
else reporter.warn("Could not open a browser automatically; open the URL above manually.");
|
|
79
|
+
} else {
|
|
80
|
+
reporter.info("--no-open: open the URL above yourself.");
|
|
81
|
+
}
|
|
82
|
+
reporter.info(`Waiting for a token via localhost callback or terminal paste (timeout ${Math.round(timeout / 1000)}s)…`);
|
|
83
|
+
|
|
84
|
+
const started = Date.now();
|
|
85
|
+
let answer = "";
|
|
86
|
+
while (!answer) {
|
|
87
|
+
const remaining = timeout - (Date.now() - started);
|
|
88
|
+
if (remaining <= 0) throw authError("Login timed out.", { hint: "Re-run `collectui login`." });
|
|
89
|
+
answer = await Promise.race([
|
|
90
|
+
callback.waitForToken(remaining),
|
|
91
|
+
promptToken(Math.min(remaining, 120_000)),
|
|
92
|
+
]);
|
|
93
|
+
if (!answer) {
|
|
94
|
+
// 用户回车但没贴内容:继续等回调/再次提示,直到超时
|
|
95
|
+
if (!callback.pending) break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
token = tokenOrThrow(answer);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
let me = null;
|
|
102
|
+
if (!skipVerify) {
|
|
103
|
+
try {
|
|
104
|
+
me = await verifyToken(token, { reporter });
|
|
105
|
+
} catch (error) {
|
|
106
|
+
throw authError(`PAT verification failed: ${error.message}`, {
|
|
107
|
+
hint:
|
|
108
|
+
"Make sure you copied the full dpat_ token and that it is still active in " +
|
|
109
|
+
`${dashUrl()} → API 密钥.`,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
} else {
|
|
113
|
+
reporter.warn("--no-verify: token saved without checking it. Run `collectui whoami` to verify.");
|
|
114
|
+
}
|
|
115
|
+
saveSession(token, me, { reporter });
|
|
116
|
+
reporter.outro("Login complete. Try `collectui libs`.");
|
|
117
|
+
return { token, me };
|
|
118
|
+
} finally {
|
|
119
|
+
callback.close();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function tokenOrThrow(value) {
|
|
124
|
+
const token = String(value ?? "").trim();
|
|
125
|
+
if (!token) throw authError("Empty token.");
|
|
126
|
+
if (!/^[A-Za-z0-9._-]{8,}$/.test(token)) {
|
|
127
|
+
throw authError("That does not look like a token.", {
|
|
128
|
+
hint: "A Dash PAT starts with dpat_. Copy it again from the dashboard.",
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return token;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function promptToken(timeoutMs) {
|
|
135
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return "";
|
|
136
|
+
const timeout = new Promise((resolve) => setTimeout(() => resolve(""), timeoutMs));
|
|
137
|
+
const answer = await Promise.race([
|
|
138
|
+
p.password({
|
|
139
|
+
message: "Paste your Dash PAT (dpat_…, hidden input)",
|
|
140
|
+
mask: "*",
|
|
141
|
+
}).then((v) => (p.isCancel(v) ? "" : String(v ?? ""))),
|
|
142
|
+
timeout,
|
|
143
|
+
]);
|
|
144
|
+
if (answer === "") return "";
|
|
145
|
+
return answer;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 本地回调监听(Dash 配对能力的前向兼容;也可由用户手动打开)。 */
|
|
149
|
+
export function startCallbackServer() {
|
|
150
|
+
const secret = randomBytes(12).toString("hex");
|
|
151
|
+
let resolveToken;
|
|
152
|
+
const tokenPromise = new Promise((resolve) => {
|
|
153
|
+
resolveToken = resolve;
|
|
154
|
+
});
|
|
155
|
+
let pending = true;
|
|
156
|
+
|
|
157
|
+
const server = createServer((req, res) => {
|
|
158
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
159
|
+
if (url.pathname !== `/${secret}`) {
|
|
160
|
+
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
161
|
+
res.end("Not found");
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const token = url.searchParams.get("token") ?? "";
|
|
165
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
166
|
+
res.end("<!doctype html><meta charset=utf-8><title>CollectUI</title><p>Token received. You can close this window.</p>");
|
|
167
|
+
if (token) {
|
|
168
|
+
pending = false;
|
|
169
|
+
resolveToken(token);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
const listening = new Promise((resolve, reject) => {
|
|
174
|
+
server.once("error", reject);
|
|
175
|
+
server.listen(0, "127.0.0.1", () => {
|
|
176
|
+
const address = server.address();
|
|
177
|
+
resolve(`http://127.0.0.1:${address.port}/${secret}`);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
get pending() {
|
|
183
|
+
return pending;
|
|
184
|
+
},
|
|
185
|
+
waitForToken(timeoutMs) {
|
|
186
|
+
return Promise.race([
|
|
187
|
+
tokenPromise,
|
|
188
|
+
new Promise((resolve) => setTimeout(() => resolve(""), timeoutMs)),
|
|
189
|
+
]);
|
|
190
|
+
},
|
|
191
|
+
async url() {
|
|
192
|
+
return listening;
|
|
193
|
+
},
|
|
194
|
+
close() {
|
|
195
|
+
try {
|
|
196
|
+
server.close();
|
|
197
|
+
} catch {
|
|
198
|
+
// already closed
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function openBrowser(url) {
|
|
205
|
+
const platform = process.platform;
|
|
206
|
+
const command =
|
|
207
|
+
platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
|
|
208
|
+
const args = platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
209
|
+
try {
|
|
210
|
+
const child = spawn(command, args, { detached: true, stdio: "ignore" });
|
|
211
|
+
// 命令不存在/无桌面环境时不要炸掉整个 login(用户仍可手动打开 URL)
|
|
212
|
+
child.on("error", () => {});
|
|
213
|
+
child.unref();
|
|
214
|
+
return true;
|
|
215
|
+
} catch {
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export async function readStdin(timeoutMs = 3000) {
|
|
221
|
+
if (process.stdin.isTTY) return "";
|
|
222
|
+
return new Promise((resolve) => {
|
|
223
|
+
let data = "";
|
|
224
|
+
let done = false;
|
|
225
|
+
const finish = () => {
|
|
226
|
+
if (done) return;
|
|
227
|
+
done = true;
|
|
228
|
+
resolve(data);
|
|
229
|
+
};
|
|
230
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
231
|
+
process.stdin.setEncoding("utf8");
|
|
232
|
+
process.stdin.on("data", (chunk) => {
|
|
233
|
+
data += chunk;
|
|
234
|
+
if (data.length > 5000) {
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
finish();
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
process.stdin.on("end", () => {
|
|
240
|
+
clearTimeout(timer);
|
|
241
|
+
finish();
|
|
242
|
+
});
|
|
243
|
+
process.stdin.on("error", () => {
|
|
244
|
+
clearTimeout(timer);
|
|
245
|
+
finish();
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function logout({ reporter } = {}) {
|
|
251
|
+
const had = clearConfig();
|
|
252
|
+
reporter?.info(had ? `Removed credentials from ${configFile()}.` : "No saved credentials.");
|
|
253
|
+
}
|