diff --git a/AGENTS.md b/AGENTS.md index aab631d..1d526b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,54 +1,29 @@ -# ekb-mcp 项目上下文(AGENTS.md) +# hose-serve-tool 项目上下文(AGENTS.md) 本文件是根目录总纲,面向 AI 智能体说明项目目标、分层规则和文档索引。 -子域细节不要继续堆在这里,优先引用下级文档。 -## 文件定位 +## 项目定位 -- 面向业务人员的使用说明:见 [README.md](./README.md) -- 面向智能体的根规则:以本文件为准 -- 面向通用 Agent 的入口别名:见 [CLAUDE.md](./CLAUDE.md) -- 具体子域细节:进入对应目录下的 `README*.md` +合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 适配能力): -## 项目目标 - -为快报(ekuaibao)企业费控 SaaS 提供一套 MCP Server,面向 AI Agent 结构化调用: - -- **MCP Server**:给 AI Agent、脚本或服务通过 Model Context Protocol 调用 -- **目标站点**:`https://app.ekuaibao.com/web/app.html` - -## 认证机制 - -快报主站使用三 Header 认证,不依赖 Cookie: - -- `accesstoken` -- `corpid` -- `staffid` - -认证信息保存在: - -- `enterprises/*.json` — 企业级静态配置 -- `~/.cache/ekb-mcp/tokens.json` — 动态 Token 缓存(自动刷新) - -Platform 子域使用 EASO / Piper 独立认证,详细流程见: - -- [src/domains/platform/README.platform.md](./src/domains/platform/README.platform.md) +- **CLI 工具 (`hose`)**:面向运维/实施/开发者的高性能交互与自动化命令行 +- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务 API 与换票能力 +- **MCP Server (`src/server.ts`)**:精简核心适配器(保留核心切换与扫描能力) ## 架构总览 ```text -AI Agent (MCP Client) - │ - ▼ -server.ts ──→ domains/ ──→ core/ - │ │ │ - │ │ ├── auth/ Token 获取与缓存 - │ │ ├── config/ 企业配置管理 - │ │ └── http/ HTTP 客户端工厂 - │ │ - │ └── platform/ Platform 域 - │ - └── core/errors.ts 统一异常语义 +CLI (src/cli.ts) / MCP (src/server.ts) + │ │ + └──────────┬─────────┘ + ▼ + domains/ (业务编排与平台引擎) + │ + ▼ + core/ (认证、配置与 HTTP 基础设施) + ├── auth/ Token 登录、换票与缓存 + ├── config/ 多账号与企业配置管理 + └── http/ HTTP 客户端工厂 ``` 核心原则: diff --git a/README.md b/README.md index 9fdef38..49f4843 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,52 @@ -# ekb-mcp +# hose-serve-tool -易快报(ekuaibao)MCP Server,面向 AI Agent 设计。 +合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK。 -## 安装 +## 安装与快速开始 ```bash bun install ``` -## 配置 - -在 `enterprises/` 目录下创建企业配置: - -```json -{ - "id": "corp-id", - "name": "企业名称", - "credentials": { - "accessToken": "your-access-token", - "corpId": "your-corp-id", - "staffId": "your-staff-id" - }, - "auth": { - "refreshTtl": 300 - } -} -``` - -## 运行 +### CLI 命令行工具 (`hose`) ```bash -bun run dev # 开发模式(热重载) -bun run start # 生产模式 -bun run typecheck # TypeScript 类型检查 -bun run login # 交互式登录 / 企业配置生成 -bun run export:workflow-schema # 导出工作流 JSON Schema -``` +# 1. 认证与登录 (支持账密、短信、F12抓包导入、浏览器同步) +bun run cli auth login --phone=17718556446 --password=... +bun run cli auth status # 查看当前登录状态与有效性 +bun run cli auth refresh # 批量刷新账号名下全部企业 Token -### 登录授权方式 +# 2. 多企业租户管理 +bun run cli corps list # 列出名下所有已配置企业 +bun run cli corps switch # 切换工作企业 +bun run cli corps current # 查看当前激活企业 -```bash -bun run login # 1. 交互式账号密码登录 -bun run login --phone=138... --password=... # 2. 命令行参数静默登录 -bun run login --sms # 3. 短信验证码登录 -bun run login --sync # 4. 从当前运行的浏览器一键同步 +# 3. 平台与工作流管理 (跨应用聚合) +bun run cli workflow list # 汇总查看全部工作流列表 +bun run cli workflow get # 获取工作流详情与节点结构 +bun run cli workflow find --task=code-js2 # 搜索包含特定节点类型的工作流 +bun run cli workflow toggle --state=1 # 启用/停用工作流 +bun run cli platform list # 查看企业下所有启用的自建应用 + +# 4. 连通性诊断与 MCP Server +bun run probe # 诊断当前企业鉴权与接口连通性 +bun run start # 启动精简版 MCP Server (stdio) ``` ## 架构 -``` +```text src/ -├── core/ # 基础设施 -│ ├── config/ # 企业配置管理 -│ ├── auth/ # 认证(Token 缓存/刷新) -│ │ ├── easo.ts # EASO 四步认证 -│ │ └── piper.ts # Piper 三步认证 -│ └── http/ # HTTP 客户端工厂 -├── domains/ # 业务域 -│ └── platform/ # 自建应用/工作流域 -│ ├── types.ts -│ ├── api.ts -│ └── tools.ts -└── server.ts # MCP Server 入口 +├── cli.ts # CLI 入口 (bin: hose) +├── cli/ # CLI 核心引擎 (runner, parser, printer, commands) +├── core/ # 基础设施与底层 SDK +│ ├── auth/ # 认证与换票 (RSA 账密, TokenStore, AccountStore) +│ ├── config/ # 多账号与企业配置管理 +│ ├── http/ # HTTP 客户端工厂 +│ └── errors.ts # 统一异常语义 +├── domains/ # 业务域 SDK +│ └── platform/ # 自建应用与 EASO/Piper 工作流引擎 +└── server.ts # 精简核心 MCP 协议适配 ``` ## 已迁移功能 diff --git a/package.json b/package.json index 8d2b9c5..c0dc10c 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,17 @@ { - "name": "ekb-mcp", + "name": "hose-serve-tool", "version": "0.1.0", "module": "src/server.ts", "type": "module", + "bin": { + "hose": "src/cli.ts" + }, "scripts": { + "cli": "bun run src/cli.ts", + "probe": "bun run src/cli.ts probe", "dev": "bun run --watch src/server.ts", "start": "bun run src/server.ts", "typecheck": "tsc --noEmit", - "login": "bun run scripts/login.ts", "export:workflow-schema": "bun run scripts/export-workflow-schema.ts" }, "dependencies": { diff --git a/scripts/login.ts b/scripts/login.ts deleted file mode 100644 index fa85a51..0000000 --- a/scripts/login.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { - fullPasswordLogin, - fullSmsLogin, - fullBrowserSyncLogin, - sendSmsVerificationCode, - importF12Credentials, - parseHeadersOrCurl, - refreshAccountCorporations, -} from "../src/core/auth/login.js"; -import { listAccounts, getActiveAccount } from "../src/core/auth/account-store.js"; -import { loadCorpConfigs } from "../src/core/config/loader.js"; -import readline from "readline"; - -function prompt(question: string): Promise { - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - }); - return new Promise((resolve) => { - rl.question(question, (answer) => { - rl.close(); - resolve(answer.trim()); - }); - }); -} - -async function handleMenu() { - console.log("请选择登录或凭证导入方式:"); - console.log(" [1] 账号密码登录 (RSA 自动加密,自动拉取名下全部企业)"); - console.log(" [2] 手机短信验证码登录"); - console.log(" [3] F12 抓包导入 (粘贴 accessToken/corpId/staffId 或 cURL / Headers)"); - console.log(" [4] 浏览器会话一键同步 (WebBridge)"); - console.log(" [5] 刷新账号名下的所有企业 Token (批量保活)"); - console.log(" [6] 查看当前已配置的账号与企业列表\n"); - - const choice = await prompt("请输入选项序号 [1-6] (默认 1): ") || "1"; - - switch (choice) { - case "1": - return doPasswordLogin(); - case "2": - return doSmsLogin(); - case "3": - return doF12Import(); - case "4": - return doBrowserSync(); - case "5": - return doRefreshAccounts(); - case "6": - return doShowStatus(); - default: - console.error("无效选项"); - } -} - -async function doPasswordLogin(phoneInput?: string, pwdInput?: string) { - const phone = phoneInput || (await prompt("请输入手机号: ")); - const password = pwdInput || (await prompt("请输入密码: ")); - - if (!phone || !password) { - console.error("手机号和密码不能为空"); - return; - } - - console.log("\n正在进行全自动 RSA 账密登录..."); - const result = await fullPasswordLogin({ - phone, - password, - saveAll: true, - }); - - console.log("\n[SUCCESS] 账密登录成功!"); - console.log(`账号标识: ${result.accountId}`); - console.log(`当前激活企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); - console.log(`共保存企业配置: ${result.allCorps.length} 家`); - result.allCorps.forEach((c, idx) => { - console.log(` ${idx + 1}. [${c.id}] ${c.name} (${c.credentials.staffId})`); - }); -} - -async function doSmsLogin() { - const phone = await prompt("请输入手机号: "); - if (!phone) { - console.error("手机号不能为空"); - return; - } - - console.log(`\n正在向 ${phone} 请求发送短信验证码...`); - let codeId: string | undefined; - try { - const sendRes = await sendSmsVerificationCode({ phone }); - codeId = sendRes.codeId; - console.log("短信验证码已成功发送!"); - } catch (e) { - console.warn("直接发送提示:", e instanceof Error ? e.message : String(e)); - console.log("如果网页端触发了人机验证,请在浏览器中点击获取验证码后在下方输入。"); - } - - const code = await prompt("请输入收到的 6 位短信验证码: "); - if (!code) { - console.error("验证码不能为空"); - return; - } - - console.log("\n正在验证短信验证码并拉取企业..."); - const result = await fullSmsLogin({ - phone, - code, - codeId, - saveAll: true, - }); - - console.log("\n[SUCCESS] 短信验证码登录成功!"); - console.log(`账号标识: ${result.accountId}`); - console.log(`当前激活企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); - console.log(`共保存企业配置: ${result.allCorps.length} 家`); -} - -async function doF12Import() { - console.log("\n提示:您可以直接粘贴从 F12 Network 复制的 Request Headers、cURL 文本,或手动输入三要素。"); - const raw = await prompt("请粘贴 F12 抓包文本 (直接回车则手动逐项输入): "); - - let accessToken = ""; - let corpId = ""; - let staffId = ""; - let name = ""; - - if (raw) { - const parsed = parseHeadersOrCurl(raw); - accessToken = parsed.accessToken || ""; - corpId = parsed.corpId || ""; - staffId = parsed.staffId || ""; - } - - if (!accessToken) accessToken = await prompt("请输入 accessToken: "); - if (!corpId) corpId = await prompt("请输入 corpId: "); - if (!staffId) staffId = await prompt("请输入 staffId: "); - name = await prompt("请输入企业名称(选填): "); - - if (!accessToken || !corpId || !staffId) { - console.error("accessToken, corpId, staffId 均为必填!"); - return; - } - - console.log("\n正在校验凭证并保存企业配置..."); - const imported = await importF12Credentials({ - accessToken, - corpId, - staffId, - name: name || undefined, - }); - - console.log("\n[SUCCESS] 成功导入并保存企业凭证!"); - console.log(`企业名称: ${imported.name}`); - console.log(`企业 ID: ${imported.id}`); - console.log(`员工工号: ${imported.credentials.staffId}`); - console.log(`保存路径: enterprises/${imported.id}.json`); -} - -async function doBrowserSync() { - console.log("\n正在从本地运行的浏览器会话中同步登录态..."); - const result = await fullBrowserSyncLogin({ saveAll: true }); - console.log("\n[SUCCESS] 成功从浏览器同步企业凭证!"); - console.log(`当前激活企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); - console.log(`共保存企业配置: ${result.allCorps.length} 家`); -} - -async function doRefreshAccounts() { - console.log("\n正在使用主账号登录态刷新所有关联企业的 AccessToken..."); - const result = await refreshAccountCorporations(undefined, { saveAll: true }); - console.log("\n[SUCCESS] 成功批量刷新并更新企业配置!"); - console.log(`账号标识: ${result.accountId}`); - console.log(`共刷新企业: ${result.allCorps.length} 家`); - result.allCorps.forEach((c, idx) => { - console.log(` ${idx + 1}. [${c.id}] ${c.name}`); - }); -} - -async function doShowStatus() { - const accounts = listAccounts(); - const activeAccount = getActiveAccount(); - const corps = loadCorpConfigs(); - - console.log("\n====== 账号与企业状态概览 ======"); - console.log(`总账号数: ${accounts.length},当前激活账号: ${activeAccount?.accountId || "无"}`); - accounts.forEach((acc, i) => { - console.log(`\n账号 [${i + 1}]: ${acc.accountId} (用户 ID: ${acc.userId || "未知"})`); - console.log(`关联企业数: ${acc.corporations.length}`); - }); - - console.log(`\n总加载本地企业配置: ${corps.length} 个`); - corps.forEach((c, i) => { - console.log(` ${i + 1}. [${c.id}] ${c.name} (来源: ${c.source || "manual"}, 账号: ${c.accountId || "无"})`); - }); - console.log("================================"); -} - -async function main() { - const args = process.argv.slice(2); - const isSync = args.includes("--sync"); - const isSms = args.includes("--sms"); - const isRefresh = args.includes("--refresh"); - const isStatus = args.includes("--status"); - const phoneArg = args.find((a) => a.startsWith("--phone="))?.split("=")[1]; - const pwdArg = args.find((a) => a.startsWith("--password="))?.split("=")[1]; - - console.log("=========================================="); - console.log(" 合思 (ekb-mcp) 认证与凭证管理 "); - console.log("==========================================\n"); - - try { - if (phoneArg && pwdArg) { - return await doPasswordLogin(phoneArg, pwdArg); - } - if (isSync) { - return await doBrowserSync(); - } - if (isSms) { - return await doSmsLogin(); - } - if (isRefresh) { - return await doRefreshAccounts(); - } - if (isStatus) { - return await doShowStatus(); - } - - await handleMenu(); - } catch (error) { - console.error("\n[ERROR] 操作失败:", error instanceof Error ? error.message : String(error)); - process.exit(1); - } -} - -main(); diff --git a/src/cli.ts b/src/cli.ts new file mode 100755 index 0000000..bc5a6aa --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,36 @@ +#!/usr/bin/env bun + +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +import { runCli } from "./cli/runner.js"; + +process.stdout.on("error", (err: any) => { + if (err?.code === "EPIPE") process.exit(0); +}); +process.stderr.on("error", (err: any) => { + if (err?.code === "EPIPE") process.exit(0); +}); + +const entryFile = fileURLToPath(import.meta.url); +const appRoot = dirname(dirname(entryFile)); + +const result = await runCli(process.argv.slice(2), { + appRoot, + entryFile, +}); + +try { + if (result.stdout) process.stdout.write(result.stdout); +} catch (err: any) { + if (err?.code !== "EPIPE") throw err; +} + +try { + if (result.stderr) { + process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`); + } +} catch (err: any) { + if (err?.code !== "EPIPE") throw err; +} + +process.exitCode = result.exitCode; diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts new file mode 100644 index 0000000..5cc5c19 --- /dev/null +++ b/src/cli/commands/auth.ts @@ -0,0 +1,292 @@ +import { + fullPasswordLogin, + fullSmsLogin, + fullBrowserSyncLogin, + sendSmsVerificationCode, + importF12Credentials, + parseHeadersOrCurl, + refreshAccountCorporations, +} from "../../core/auth/login.js"; +import { + listAccounts, + getActiveAccount, + setActiveAccount, +} from "../../core/auth/account-store.js"; +import { createEkbClient } from "../../core/auth/ekb.js"; +import { stringOption, booleanOption } from "../parser.js"; +import { printJson, printKeyValue, printTable } from "../printer.js"; +import { prompt } from "../helpers.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; + +export async function handleAuthCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const action = parsed.action || "status"; + + switch (action) { + case "login": + return handleLogin(parsed, runtime); + case "status": + case "whoami": + return handleStatus(parsed, runtime); + case "refresh": + return handleRefresh(parsed, runtime); + case "import": + return handleImport(parsed, runtime); + case "accounts": + return handleAccounts(parsed, runtime); + case "switch-account": + return handleSwitchAccount(parsed, runtime); + default: + return { + stdout: "", + stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, accounts, switch-account\n`, + exitCode: 1, + }; + } +} + +async function handleLogin(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const phone = stringOption(parsed.options, ["phone", "p"]); + const password = stringOption(parsed.options, ["password", "pwd"]); + const isSms = booleanOption(parsed.options, ["sms"]); + const isSync = booleanOption(parsed.options, ["sync"]); + const isInteractive = booleanOption(parsed.options, ["interactive", "i"]) || (!phone && !password && !isSms && !isSync); + + // 1. 浏览器同步 + if (isSync) { + const res = await fullBrowserSyncLogin({ saveAll: true }); + if (runtime.jsonMode) { + return { stdout: printJson(res), stderr: "", exitCode: 0 }; + } + return { + stdout: `[SUCCESS] 成功从浏览器会话同步企业凭证!\n默认企业: ${res.selectedCorp.name} (${res.selectedCorp.id})\n共保存企业: ${res.allCorps.length} 家\n`, + stderr: "", + exitCode: 0, + }; + } + + // 2. 短信验证码登录 + if (isSms) { + const inputPhone = phone || (await prompt("请输入手机号: ")); + if (!inputPhone) return { stdout: "", stderr: "手机号不能为空\n", exitCode: 1 }; + + let codeId: string | undefined; + try { + const sendRes = await sendSmsVerificationCode({ phone: inputPhone }); + codeId = sendRes.codeId; + console.log("短信验证码已发送!"); + } catch (e) { + console.log("若触发了人机验证,请在浏览器中获取验证码后直接在下方输入。"); + } + + const code = await prompt("请输入收到的 6 位短信验证码: "); + if (!code) return { stdout: "", stderr: "验证码不能为空\n", exitCode: 1 }; + + const res = await fullSmsLogin({ + phone: inputPhone, + code, + codeId, + saveAll: true, + }); + + if (runtime.jsonMode) { + return { stdout: printJson(res), stderr: "", exitCode: 0 }; + } + return { + stdout: `[SUCCESS] 短信验证码登录成功!\n账号: ${res.accountId}\n默认企业: ${res.selectedCorp.name} (${res.selectedCorp.id})\n共保存企业: ${res.allCorps.length} 家\n`, + stderr: "", + exitCode: 0, + }; + } + + // 3. 账号密码登录 + const inputPhone = phone || (isInteractive ? await prompt("请输入手机号: ") : ""); + const inputPassword = password || (isInteractive ? await prompt("请输入密码: ") : ""); + + if (!inputPhone || !inputPassword) { + return { stdout: "", stderr: "手机号和密码不能为空\n", exitCode: 1 }; + } + + const res = await fullPasswordLogin({ + phone: inputPhone, + password: inputPassword, + saveAll: true, + }); + + if (runtime.jsonMode) { + return { stdout: printJson(res), stderr: "", exitCode: 0 }; + } + + const rows = res.allCorps.map((c, i) => [ + i + 1, + c.id, + c.name, + c.credentials.staffId, + ]); + const table = printTable(["#", "企业 ID", "企业名称", "员工工号"], rows); + + return { + stdout: `[SUCCESS] 账密登录成功!\n账号: ${res.accountId}\n默认企业: ${res.selectedCorp.name} (${res.selectedCorp.id})\n共保存企业配置: ${res.allCorps.length} 家\n\n${table}\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const currentCorp = runtime.selectedCorp; + const activeAccount = getActiveAccount(); + + let sessionValid = false; + let sessionData: unknown = null; + + if (currentCorp) { + try { + const client = await createEkbClient(currentCorp); + const res = await client.get("api/account/v2/session").json<{ value?: unknown }>(); + sessionValid = !!res.value; + sessionData = res.value; + } catch { + sessionValid = false; + } + } + + const statusObj = { + activeAccount: activeAccount?.accountId || null, + currentCorp: currentCorp + ? { + id: currentCorp.id, + name: currentCorp.name, + staffId: currentCorp.credentials.staffId, + source: currentCorp.source, + accountId: currentCorp.accountId, + tokenValid: sessionValid, + } + : null, + session: sessionData, + }; + + if (runtime.jsonMode) { + return { stdout: printJson(statusObj), stderr: "", exitCode: 0 }; + } + + const summary = printKeyValue({ + "当前活跃账号": activeAccount?.accountId || "未登录", + "当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置", + "当前员工工号": currentCorp?.credentials.staffId || "-", + "凭证来源类型": currentCorp?.source || "-", + "Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接", + }); + + return { + stdout: `====== 当前登录与企业状态 ======\n${summary}\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const accountId = stringOption(parsed.options, ["account", "a"]); + const res = await refreshAccountCorporations(accountId, { saveAll: true }); + + if (runtime.jsonMode) { + return { stdout: printJson(res), stderr: "", exitCode: 0 }; + } + + return { + stdout: `[SUCCESS] 成功批量刷新账号 ${res.accountId} 下的所有企业 AccessToken!\n共刷新企业: ${res.allCorps.length} 家\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + let raw = stringOption(parsed.options, ["raw", "headers", "curl"]); + let accessToken = stringOption(parsed.options, ["token", "accessToken"]); + let corpId = stringOption(parsed.options, ["corp", "corpId"]); + let staffId = stringOption(parsed.options, ["staff", "staffId"]); + let name = stringOption(parsed.options, ["name"]); + + if (!raw && !accessToken) { + raw = await prompt("请粘贴 F12 抓包文本 / cURL 命令行 (直接回车则手动逐项输入): "); + } + + if (raw) { + const parsedObj = parseHeadersOrCurl(raw); + if (parsedObj.accessToken) accessToken = parsedObj.accessToken; + if (parsedObj.corpId) corpId = parsedObj.corpId; + if (parsedObj.staffId) staffId = parsedObj.staffId; + } + + if (!accessToken) accessToken = await prompt("请输入 accessToken: "); + if (!corpId) corpId = await prompt("请输入 corpId: "); + if (!staffId) staffId = await prompt("请输入 staffId: "); + + if (!accessToken || !corpId || !staffId) { + return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 }; + } + + const imported = await importF12Credentials({ + accessToken, + corpId, + staffId, + name, + }); + + if (runtime.jsonMode) { + return { stdout: printJson(imported), stderr: "", exitCode: 0 }; + } + + return { + stdout: `[SUCCESS] 成功导入并保存企业凭证!\n企业名称: ${imported.name}\n企业 ID: ${imported.id}\n员工工号: ${imported.credentials.staffId}\n保存路径: enterprises/${imported.id}.json\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const accounts = listAccounts(); + const active = getActiveAccount(); + + if (runtime.jsonMode) { + return { + stdout: printJson({ activeAccountId: active?.accountId, accounts }), + stderr: "", + exitCode: 0, + }; + } + + if (accounts.length === 0) { + return { stdout: "暂无保存的账号,请使用 hose auth login 登录\n", stderr: "", exitCode: 0 }; + } + + const rows = accounts.map((acc, i) => [ + acc.accountId === active?.accountId ? `* ${i + 1}` : ` ${i + 1}`, + acc.accountId, + acc.userId || "-", + acc.corporations.length, + new Date(acc.updatedAt).toLocaleString(), + ]); + + const table = printTable(["#", "账号标识", "用户 ID", "关联企业数", "最近更新时间"], rows); + return { stdout: `====== 本地已保存账号列表 ======\n${table}\n`, stderr: "", exitCode: 0 }; +} + +async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const target = parsed.args[0] || stringOption(parsed.options, ["account", "a"]); + if (!target) { + return { stdout: "", stderr: "用法: hose auth switch-account \n", exitCode: 1 }; + } + + const success = setActiveAccount(target); + if (!success) { + return { stdout: "", stderr: `未找到账号: ${target}\n`, exitCode: 1 }; + } + + return { + stdout: `[SUCCESS] 当前活跃主账号已切换至: ${target}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts new file mode 100644 index 0000000..ce14ce8 --- /dev/null +++ b/src/cli/commands/corps.ts @@ -0,0 +1,117 @@ +import { printJson, printKeyValue, printTable } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; + +export async function handleCorpsCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const action = parsed.action || "list"; + + switch (action) { + case "list": + return handleList(parsed, runtime); + case "switch": + case "use": + return handleSwitch(parsed, runtime); + case "current": + return handleCurrent(parsed, runtime); + default: + return { + stdout: "", + stderr: `未知 corps 子命令: ${action}。支持: list, switch, current\n`, + exitCode: 1, + }; + } +} + +async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const corps = runtime.corpContext.listCorps(); + + if (runtime.jsonMode) { + return { + stdout: printJson({ + activeCorpId: runtime.selectedCorp?.id, + corporations: corps, + }), + stderr: "", + exitCode: 0, + }; + } + + if (corps.length === 0) { + return { stdout: "未找到任何企业配置,请先运行 hose auth login\n", stderr: "", exitCode: 0 }; + } + + const rows = corps.map((c, i) => [ + c.current ? `* ${i + 1}` : ` ${i + 1}`, + c.id, + c.name, + c.staffId, + c.source || "manual", + c.accountId || "-", + ]); + + const table = printTable( + ["#", "企业 ID", "企业名称", "员工工号", "来源", "所属账号"], + rows + ); + + return { + stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示: 使用 hose corps switch <企业ID> 切换工作企业\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const corpId = parsed.args[0]; + if (!corpId) { + return { stdout: "", stderr: "用法: hose corps switch <企业ID>\n", exitCode: 1 }; + } + + const success = runtime.corpContext.switchCorp(corpId); + if (!success) { + return { + stdout: "", + stderr: `企业 ${corpId} 不存在或未配置。可运行 hose corps list 查看可用列表。\n`, + exitCode: 1, + }; + } + + const current = runtime.corpContext.getCurrent(); + if (runtime.jsonMode) { + return { stdout: printJson(current), stderr: "", exitCode: 0 }; + } + + return { + stdout: `[SUCCESS] 已切换到企业: ${current?.name} (${current?.id})\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const current = runtime.selectedCorp; + if (!current) { + return { stdout: "", stderr: "未选中任何企业\n", exitCode: 1 }; + } + + if (runtime.jsonMode) { + return { stdout: printJson(current), stderr: "", exitCode: 0 }; + } + + const output = printKeyValue({ + "企业 ID": current.id, + "企业名称": current.name, + "员工工号": current.credentials.staffId, + "来源类型": current.source || "manual", + "所属账号": current.accountId || "-", + "主站地址": current.baseUrl || "https://app.ekuaibao.com", + }); + + return { + stdout: `====== 当前激活企业 ======\n${output}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/mcp.ts b/src/cli/commands/mcp.ts new file mode 100644 index 0000000..abac1a4 --- /dev/null +++ b/src/cli/commands/mcp.ts @@ -0,0 +1,24 @@ +import { spawn } from "child_process"; +import { join } from "path"; +import type { CliParsedArgs, CliResult, CliRunOptions } from "../types.js"; + +export async function handleMcpCommand( + parsed: CliParsedArgs, + options: CliRunOptions +): Promise { + const appRoot = options.appRoot || process.cwd(); + const serverPath = join(appRoot, "src", "server.ts"); + + console.error("启动 MCP Server on stdio..."); + const child = spawn("bun", ["run", serverPath], { + stdio: "inherit", + cwd: appRoot, + env: process.env, + }); + + await new Promise((resolve) => { + child.on("exit", () => resolve()); + }); + + return { stdout: "", stderr: "", exitCode: 0 }; +} diff --git a/src/cli/commands/platform.ts b/src/cli/commands/platform.ts new file mode 100644 index 0000000..a3c4a78 --- /dev/null +++ b/src/cli/commands/platform.ts @@ -0,0 +1,64 @@ +import * as api from "../../domains/platform/api.js"; +import { createClientsForCorp } from "../helpers.js"; +import { printJson, printTable } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; + +export async function handlePlatformCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const currentCorp = runtime.selectedCorp; + if (!currentCorp) { + return { + stdout: "", + stderr: "未选中企业,请先通过 hose corps switch 或 --corp 指定企业\n", + exitCode: 1, + }; + } + + const action = parsed.action || "list"; + + switch (action) { + case "list": + case "ls": + return handleList(parsed, runtime); + default: + return { + stdout: "", + stderr: `未知 platform 子命令: ${action}。支持: list\n`, + exitCode: 1, + }; + } +} + +async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const clients = await createClientsForCorp(runtime.selectedCorp!); + const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId); + + if (runtime.jsonMode) { + return { stdout: printJson(platforms), stderr: "", exitCode: 0 }; + } + + if (platforms.length === 0) { + return { + stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = platforms.map((p, i) => [ + i + 1, + p.id, + p.name, + p.active ? "🟢 已启用" : "⚪ 未启用", + ]); + + const table = printTable(["#", "自建应用 ID", "应用名称", "状态"], rows); + + return { + stdout: `====== [${runtime.selectedCorp!.name}] 自建应用列表 (共 ${platforms.length} 个) ======\n${table}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts new file mode 100644 index 0000000..a03e887 --- /dev/null +++ b/src/cli/commands/probe.ts @@ -0,0 +1,96 @@ +import { createClientsForCorp } from "../helpers.js"; +import * as api from "../../domains/platform/api.js"; +import { printJson, printKeyValue } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; + +export async function handleProbeCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const currentCorp = runtime.selectedCorp; + if (!currentCorp) { + return { + stdout: "", + stderr: "未配置任何企业,请先运行 hose auth login 或使用 --corp 指定\n", + exitCode: 1, + }; + } + + const results: Record = { + enterprise: { + id: currentCorp.id, + name: currentCorp.name, + staffId: currentCorp.credentials.staffId, + baseUrl: currentCorp.baseUrl, + source: currentCorp.source, + accountId: currentCorp.accountId, + }, + ekbSession: { status: "pending" }, + easoToken: { status: "pending" }, + platformAccess: { status: "pending" }, + }; + + try { + const clients = await createClientsForCorp(currentCorp); + + // 1. 测试 EKB 主站 Session + try { + const sessionRes = await clients.ekbClient + .get("api/account/v2/session") + .json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>(); + + results.ekbSession = { + status: "ok", + userId: sessionRes.value?.userId, + loginStaffId: sessionRes.value?.loginStaffId, + expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined, + }; + } catch (e) { + results.ekbSession = { + status: "error", + error: e instanceof Error ? e.message : String(e), + }; + } + + // 2. 测试 EASO Token 换取 + try { + const platforms = await api.listPlatforms(clients.ekbClient, currentCorp.credentials.corpId); + results.platformAccess = { + status: "ok", + totalPlatforms: platforms.length, + }; + + const stats = await api.getWorkflowStats(clients.easoClient, platforms[0]?.id || "platform"); + results.easoToken = { + status: "ok", + message: "EASO 四步换票握手成功", + }; + } catch (e) { + results.easoToken = { + status: "error", + error: e instanceof Error ? e.message : String(e), + }; + } + } catch (error) { + results.error = error instanceof Error ? error.message : String(error); + } + + if (runtime.jsonMode) { + return { stdout: printJson(results), stderr: "", exitCode: 0 }; + } + + const summary = printKeyValue({ + "企业名称": currentCorp.name, + "企业 ID": currentCorp.id, + "员工工号": currentCorp.credentials.staffId, + "主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常", + "EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败", + "自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败", + }); + + return { + stdout: `====== 诊断结果 (Enterprise Probe) ======\n${summary}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/workflow.ts b/src/cli/commands/workflow.ts new file mode 100644 index 0000000..0d54ca3 --- /dev/null +++ b/src/cli/commands/workflow.ts @@ -0,0 +1,207 @@ +import { + listAllWorkflows, + findWorkflowsByTaskType, +} from "../../domains/platform/services.js"; +import * as api from "../../domains/platform/api.js"; +import { stringOption, numberOption, booleanOption } from "../parser.js"; +import { createClientsForCorp } from "../helpers.js"; +import { printJson, printTable, printKeyValue } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; + +export async function handleWorkflowCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const currentCorp = runtime.selectedCorp; + if (!currentCorp) { + return { + stdout: "", + stderr: "未选中企业,请先通过 hose corps switch 或 --corp 指定企业\n", + exitCode: 1, + }; + } + + const action = parsed.action || "list"; + + switch (action) { + case "list": + case "list-all": + case "ls": + return handleList(parsed, runtime); + case "get": + case "detail": + case "info": + return handleGet(parsed, runtime); + case "find": + case "search": + return handleFind(parsed, runtime); + case "toggle": + return handleToggle(parsed, runtime); + default: + return { + stdout: "", + stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, toggle\n`, + exitCode: 1, + }; + } +} + +async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const clients = await createClientsForCorp(runtime.selectedCorp!); + const page = numberOption(parsed.options, ["page"]) || 1; + const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50; + + const result = await listAllWorkflows(clients, { page, pageSize }); + + if (runtime.jsonMode) { + return { stdout: printJson(result), stderr: "", exitCode: 0 }; + } + + if (result.workflows.length === 0) { + return { + stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = result.workflows.map((wf, i) => [ + i + 1, + wf.id, + wf.pipelineName, + wf.platformName || wf.platformId || "-", + wf.state === 1 ? "🟢 启用" : "⚪ 停用", + wf.tasks?.length ?? "-", + ]); + + const table = printTable( + ["#", "工作流 ID", "工作流名称", "所属自建应用", "状态", "节点数"], + rows + ); + + return { + stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); + if (!pipelineId) { + return { stdout: "", stderr: "用法: hose workflow get \n", exitCode: 1 }; + } + + const clients = await createClientsForCorp(runtime.selectedCorp!); + const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId); + + if (runtime.jsonMode) { + return { stdout: printJson(detail), stderr: "", exitCode: 0 }; + } + + const summary = printKeyValue({ + "工作流 ID": detail.id, + "工作流名称": detail.label, + "状态": detail.state === 1 ? "🟢 启用" : "⚪ 停用", + "版本号": detail.version || "-", + "节点总数": detail.tasks?.length ?? 0, + }); + + let taskList = ""; + if (detail.tasks && detail.tasks.length > 0) { + const taskRows = detail.tasks.map((t, i) => [ + i + 1, + t.name || "-", + t.label || "-", + t.type, + t.groupName || "-", + ]); + taskList = `\n 节点结构:\n` + printTable(["#", "节点标识", "节点名称", "类型", "分组"], taskRows); + } + + return { + stdout: `====== 工作流详情 ======\n${summary}\n${taskList}\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const taskType = stringOption(parsed.options, ["task", "taskType", "type"]) || parsed.args[0]; + if (!taskType) { + return { + stdout: "", + stderr: "用法: hose workflow find --task=<节点类型> (如 code-js2, http, condition)\n", + exitCode: 1, + }; + } + + const clients = await createClientsForCorp(runtime.selectedCorp!); + const includeDetail = booleanOption(parsed.options, ["includeDetail", "detail"]); + const page = numberOption(parsed.options, ["page"]) || 1; + const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50; + + const result = await findWorkflowsByTaskType(clients, taskType, { + page, + pageSize, + includeDetail, + }); + + if (runtime.jsonMode) { + return { stdout: printJson(result), stderr: "", exitCode: 0 }; + } + + if (result.workflows.length === 0) { + return { + stdout: `未找到包含节点类型 [${taskType}] 的工作流\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = result.workflows.map((wf, i) => [ + i + 1, + wf.id, + wf.pipelineName, + wf.platformName || wf.platformId || "-", + wf.state === 1 ? "🟢 启用" : "⚪ 停用", + ]); + + const table = printTable( + ["#", "工作流 ID", "工作流名称", "所属自建应用", "状态"], + rows + ); + + return { + stdout: `====== 匹配节点类型 [${taskType}] 的工作流 (共 ${result.workflows.length} 条) ======\n${table}\n`, + stderr: "", + exitCode: 0, + }; +} + +async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); + const stateArg = stringOption(parsed.options, ["state", "s"]); + + if (!pipelineId || stateArg === undefined) { + return { + stdout: "", + stderr: "用法: hose workflow toggle --state=<1|0> (1启用, 0停用)\n", + exitCode: 1, + }; + } + + const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1; + const clients = await createClientsForCorp(runtime.selectedCorp!); + const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state); + + if (runtime.jsonMode) { + return { stdout: printJson(result), stderr: "", exitCode: 0 }; + } + + return { + stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${state === 1 ? "🟢 启用" : "⚪ 停用"}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts new file mode 100644 index 0000000..38dced2 --- /dev/null +++ b/src/cli/helpers.ts @@ -0,0 +1,45 @@ +import readline from "readline"; +import { loadCorpConfigs } from "../core/config/loader.js"; +import { CorpContext } from "../core/config/manager.js"; +import { CorpConfig } from "../core/config/types.js"; +import { createEkbClient } from "../core/auth/ekb.js"; +import { getEasoClient } from "../core/auth/easo.js"; +import { CliRuntime } from "./types.js"; + +export function initCorpRuntime(corpIdOption?: string, jsonMode: boolean = false): CliRuntime { + const corps = loadCorpConfigs(); + const corpContext = new CorpContext(corps); + + if (corpIdOption) { + corpContext.switchCorp(corpIdOption); + } + + return { + corpContext, + selectedCorp: corpContext.getCurrent(), + jsonMode, + }; +} + +export async function createClientsForCorp(corp: CorpConfig) { + const ekbClient = await createEkbClient(corp); + const { client: easoClient } = await getEasoClient(corp); + return { + corp, + ekbClient, + easoClient, + }; +} + +export function prompt(question: string): Promise { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer.trim()); + }); + }); +} diff --git a/src/cli/parser.ts b/src/cli/parser.ts new file mode 100644 index 0000000..cf9f6ff --- /dev/null +++ b/src/cli/parser.ts @@ -0,0 +1,98 @@ +import type { CliParsedArgs } from "./types.js"; + +export function parseArgs(rawArgs: string[]): CliParsedArgs { + const options: Record = {}; + const positional: string[] = []; + + for (let i = 0; i < rawArgs.length; i++) { + const arg = rawArgs[i]; + + if (arg === "--") { + positional.push(...rawArgs.slice(i + 1)); + break; + } + + if (arg.startsWith("--")) { + const eqIdx = arg.indexOf("="); + if (eqIdx !== -1) { + const key = arg.slice(2, eqIdx); + const val = arg.slice(eqIdx + 1); + options[key] = val; + } else { + const key = arg.slice(2); + const next = rawArgs[i + 1]; + if (next && !next.startsWith("-")) { + options[key] = next; + i++; + } else { + options[key] = true; + } + } + continue; + } + + if (arg.startsWith("-") && arg.length > 1) { + const flag = arg.slice(1); + if (flag === "h") options.help = true; + else if (flag === "j") options.json = true; + else if (flag === "v") options.version = true; + else options[flag] = true; + continue; + } + + positional.push(arg); + } + + const area = positional[0]?.toLowerCase(); + const action = positional[1]?.toLowerCase(); + const args = positional.slice(2); + + return { + area, + action, + args, + options, + raw: rawArgs, + }; +} + +export function stringOption( + options: Record, + keys: string[], + fallback?: string +): string | undefined { + for (const k of keys) { + const val = options[k]; + if (typeof val === "string" && val.length > 0) return val; + } + return fallback; +} + +export function booleanOption( + options: Record, + keys: string[], + fallback: boolean = false +): boolean { + for (const k of keys) { + const val = options[k]; + if (typeof val === "boolean") return val; + if (typeof val === "string") return val === "true" || val === "1"; + } + return fallback; +} + +export function numberOption( + options: Record, + keys: string[], + fallback?: number +): number | undefined { + for (const k of keys) { + const val = options[k]; + if (typeof val === "number" && !Number.isNaN(val)) return val; + if (typeof val === "string") { + const parsed = Number(val); + if (!Number.isNaN(parsed)) return parsed; + } + } + return fallback; +} diff --git a/src/cli/printer.ts b/src/cli/printer.ts new file mode 100644 index 0000000..611c420 --- /dev/null +++ b/src/cli/printer.ts @@ -0,0 +1,69 @@ +import { VERSION } from "../version.js"; + +export function printJson(data: unknown): string { + return JSON.stringify(data, null, 2); +} + +export function printKeyValue(pairs: Record): string { + const lines: string[] = []; + const maxKeyLen = Math.max(...Object.keys(pairs).map((k) => k.length), 0); + + for (const [key, val] of Object.entries(pairs)) { + const formattedVal = typeof val === "object" ? JSON.stringify(val) : String(val ?? ""); + lines.push(` ${key.padEnd(maxKeyLen + 2)}: ${formattedVal}`); + } + return lines.join("\n"); +} + +export function printTable( + headers: string[], + rows: Array> +): string { + if (rows.length === 0) return " (暂无数据)\n"; + + const strRows = rows.map((r) => r.map((c) => String(c ?? ""))); + const colWidths = headers.map((h, colIdx) => { + const maxRowWidth = Math.max(...strRows.map((r) => (r[colIdx] || "").length), 0); + return Math.max(h.length, maxRowWidth); + }); + + const headerLine = headers.map((h, i) => h.padEnd(colWidths[i])).join(" "); + const separatorLine = colWidths.map((w) => "-".repeat(w)).join(" "); + const dataLines = strRows.map((r) => + r.map((c, i) => c.padEnd(colWidths[i])).join(" ") + ); + + return [headerLine, separatorLine, ...dataLines].map((l) => ` ${l}`).join("\n"); +} + +export function printHelp(): string { + return ` +合思/易快报企业级 CLI 工具 (hose) v${VERSION} + +用法: + hose <命令域> <子命令> [参数] [选项] + +核心命令域: + auth 认证与凭证管理 (login, status, refresh, import, accounts) + corps 多企业租户管理 (list, switch, current) + workflow 工作流管理 (list, get, find, toggle) + platform 自建应用管理 (list) + probe 连通性诊断 (probe [corpId]) + mcp MCP Server 运行 (serve) + version 查看版本信息 + +全局选项: + --corp= 临时指定操作的企业 ID (覆盖当前激活企业) + --json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成) + --help, -h 查看帮助信息 + +常用示例: + hose auth login --phone=177... --password=... # 纯 API 账密自动登录 + hose auth status # 查看当前登录状态与活跃企业 + hose corps list # 列出名下所有企业 + hose corps switch uzU7pcWfScck00 # 切换工作企业 + hose workflow list # 汇总查看全部工作流 + hose workflow find --task=code-js2 # 搜索包含自定义脚本的工作流 + hose probe # 诊断当前企业鉴权连通性 +`.trim(); +} diff --git a/src/cli/runner.ts b/src/cli/runner.ts new file mode 100644 index 0000000..24cd75b --- /dev/null +++ b/src/cli/runner.ts @@ -0,0 +1,80 @@ +import { VERSION } from "../version.js"; +import { parseArgs, stringOption, booleanOption } from "./parser.js"; +import { printHelp, printJson } from "./printer.js"; +import { initCorpRuntime } from "./helpers.js"; +import { handleAuthCommand } from "./commands/auth.js"; +import { handleCorpsCommand } from "./commands/corps.js"; +import { handleWorkflowCommand } from "./commands/workflow.js"; +import { handlePlatformCommand } from "./commands/platform.js"; +import { handleProbeCommand } from "./commands/probe.js"; +import { handleMcpCommand } from "./commands/mcp.js"; +import type { CliResult, CliRunOptions } from "./types.js"; + +export async function runCli( + rawArgs: string[], + options: CliRunOptions = {} +): Promise { + const parsed = parseArgs(rawArgs); + + if (booleanOption(parsed.options, ["help", "h"]) || parsed.area === "help") { + return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 }; + } + + if (booleanOption(parsed.options, ["version", "v"]) || parsed.area === "version") { + return { stdout: `hose v${VERSION}\n`, stderr: "", exitCode: 0 }; + } + + const jsonMode = booleanOption(parsed.options, ["json", "j"]); + const corpIdOption = stringOption(parsed.options, ["corp", "c"]); + + const runtime = initCorpRuntime(corpIdOption, jsonMode); + + try { + switch (parsed.area) { + case "auth": + case "login": + return await handleAuthCommand(parsed, runtime); + case "corps": + case "corp": + return await handleCorpsCommand(parsed, runtime); + case "workflow": + case "workflows": + case "wf": + return await handleWorkflowCommand(parsed, runtime); + case "platform": + case "platforms": + case "app": + case "apps": + return await handlePlatformCommand(parsed, runtime); + case "probe": + case "check": + case "diagnose": + return await handleProbeCommand(parsed, runtime); + case "mcp": + case "serve": + return await handleMcpCommand(parsed, options); + case undefined: + return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 }; + default: + return { + stdout: "", + stderr: `未知命令域: ${parsed.area}。运行 hose --help 查看帮助\n`, + exitCode: 1, + }; + } + } catch (error) { + const errorMsg = error instanceof Error ? error.message : String(error); + if (jsonMode) { + return { + stdout: printJson({ error: true, message: errorMsg }), + stderr: "", + exitCode: 1, + }; + } + return { + stdout: "", + stderr: `[ERROR] ${errorMsg}\n`, + exitCode: 1, + }; + } +} diff --git a/src/cli/types.ts b/src/cli/types.ts new file mode 100644 index 0000000..eaa05d1 --- /dev/null +++ b/src/cli/types.ts @@ -0,0 +1,28 @@ +import type { CorpConfig } from "../core/config/types.js"; +import type { CorpContext } from "../core/config/manager.js"; + +export interface CliParsedArgs { + area?: string; + action?: string; + args: string[]; + options: Record; + raw: string[]; +} + +export interface CliRunOptions { + appRoot?: string; + entryFile?: string; + launcher?: string; +} + +export interface CliResult { + stdout: string; + stderr: string; + exitCode: number; +} + +export interface CliRuntime { + corpContext: CorpContext; + selectedCorp: CorpConfig | null; + jsonMode: boolean; +} diff --git a/src/core/auth/tools.ts b/src/core/auth/tools.ts index 8413156..1bc059c 100644 --- a/src/core/auth/tools.ts +++ b/src/core/auth/tools.ts @@ -1,20 +1,13 @@ import { z } from "zod"; import { CorpContext } from "../config/manager.js"; -import { loadCorpConfigs } from "../config/loader.js"; -import { - importF12Credentials, - parseHeadersOrCurl, - refreshAccountCorporations, -} from "./login.js"; -import { listAccounts, getActiveAccount } from "./account-store.js"; import { createEkbClient } from "./ekb.js"; -// ── Auth Tools 定义 ────────────────────────────────────────────────────────── +// ── 精简 MCP Auth Tools (其余复杂登录/刷新均由 CLI 直接提供) ─────────────────── export const authTools = [ { name: "list_corps", - description: "列出当前所有已配置的企业(包括账号关联企业与手动导入企业)", + description: "列出当前所有已配置的企业列表", parameters: z.object({}), handler: async ({ corpContext }: { corpContext: CorpContext }) => { return { @@ -25,7 +18,7 @@ export const authTools = [ }, { name: "switch_corp", - description: "切换当前活跃企业", + description: "切换当前活跃工作企业", parameters: z.object({ corpId: z.string().describe("目标企业 ID"), }), @@ -54,20 +47,18 @@ export const authTools = [ if (!current) { return { authenticated: false, - message: "未配置任何企业", - activeAccount: getActiveAccount(), + message: "未配置任何企业,请先运行 hose auth login", }; } - // 测试当前 Session - let sessionData: unknown = null; let sessionValid = false; + let sessionData: unknown = null; try { - const client = createEkbClient(current); + const client = await createEkbClient(current); const res = await client.get("api/account/v2/session").json<{ value?: unknown }>(); sessionData = res.value; sessionValid = !!res.value; - } catch (e) { + } catch { sessionValid = false; } @@ -85,91 +76,4 @@ export const authTools = [ }; }, }, - { - name: "import_f12_corp", - description: "从网页 F12 抓包(Network / Headers / cURL)直接导入单企业登录凭证", - parameters: z.object({ - accessToken: z.string().optional().describe("主站 accessToken"), - corpId: z.string().optional().describe("企业 ID"), - staffId: z.string().optional().describe("员工 ID"), - name: z.string().optional().describe("企业名称(可选)"), - rawHeadersOrCurl: z.string().optional().describe("F12 复制的原始 Headers 文本或 cURL 命令行字符串(自动解析)"), - baseUrl: z.string().optional().describe("站点基础地址,默认 https://app.ekuaibao.com"), - }), - handler: async ( - { corpContext }: { corpContext: CorpContext }, - params: { - accessToken?: string; - corpId?: string; - staffId?: string; - name?: string; - rawHeadersOrCurl?: string; - baseUrl?: string; - } - ) => { - let accessToken = params.accessToken; - let corpId = params.corpId; - let staffId = params.staffId; - - if (params.rawHeadersOrCurl) { - const parsed = parseHeadersOrCurl(params.rawHeadersOrCurl); - if (parsed.accessToken) accessToken = parsed.accessToken; - if (parsed.corpId) corpId = parsed.corpId; - if (parsed.staffId) staffId = parsed.staffId; - } - - if (!accessToken || !corpId || !staffId) { - throw new Error("导入失败:必须提供 accessToken, corpId, staffId 或有效的 rawHeadersOrCurl 抓包内容"); - } - - const importedConfig = await importF12Credentials({ - accessToken, - corpId, - staffId, - name: params.name, - baseUrl: params.baseUrl, - }); - - corpContext.upsertCorp(importedConfig, true); - - return { - success: true, - message: `成功导入并保存企业凭证: ${importedConfig.name} (${importedConfig.id})`, - corp: importedConfig, - }; - }, - }, - { - name: "refresh_corps", - description: "通过主账号登录态一键刷新名下所有企业的最新 AccessToken 并重新加载", - parameters: z.object({ - accountId: z.string().optional().describe("指定刷新的账号手机号,为空时刷新当前活跃账号"), - }), - handler: async ( - { corpContext }: { corpContext: CorpContext }, - params: { accountId?: string } - ) => { - const result = await refreshAccountCorporations(params.accountId, { saveAll: true }); - const freshCorps = loadCorpConfigs(); - corpContext.reload(freshCorps); - - return { - success: true, - message: `成功刷新账号 ${result.accountId} 下的所有企业凭证`, - refreshedCount: result.allCorps.length, - corporations: corpContext.listCorps(), - }; - }, - }, - { - name: "list_accounts", - description: "查看本地已保存的所有登录主账号", - parameters: z.object({}), - handler: async () => { - return { - activeAccount: getActiveAccount()?.accountId, - accounts: listAccounts(), - }; - }, - }, ]; diff --git a/src/domains/platform/tools.ts b/src/domains/platform/tools.ts index 6e6ae58..2d5c3b4 100644 --- a/src/domains/platform/tools.ts +++ b/src/domains/platform/tools.ts @@ -5,152 +5,13 @@ import { listAllWorkflows, findWorkflowsByTaskType, } from "./services.js"; -import { WorkflowStateSchema } from "./types.js"; -// ── Tool 定义 ───────────────────────────────────────────────────────────────── +// ── 精简核心 MCP Tools (其余功能均由 CLI 和底层 SDK 直接提供) ────────────────── export const platformTools = [ - { - name: "platform_list", - description: "列出企业下所有启用的自建应用", - parameters: z.object({}), - handler: async ({ ekbClient, corp }: PlatformClients) => { - return await api.listPlatforms(ekbClient, corp.credentials.corpId); - }, - }, - { - name: "platform_workflow_list", - description: "列出指定自建应用下的工作流(EASO)", - parameters: z.object({ - platformId: z.string().describe("自建应用 ID"), - page: z.number().optional().describe("页码,默认 1"), - pageSize: z.number().optional().describe("每页数量,默认 20"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { platformId: string; page?: number; pageSize?: number } - ) => { - return await api.listWorkflows( - easoClient, - params.platformId, - params.page, - params.pageSize - ); - }, - }, - { - name: "platform_workflow_stats", - description: "获取指定自建应用的工作流统计信息(EASO)", - parameters: z.object({ - platformId: z.string().describe("自建应用 ID"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { platformId: string } - ) => { - return await api.getWorkflowStats(easoClient, params.platformId); - }, - }, - { - name: "platform_workflow_charge", - description: "查询企业工作流用量配额(EASO)", - parameters: z.object({}), - handler: async ({ easoClient }: PlatformClients) => { - return await api.getWorkflowCharge(easoClient); - }, - }, - { - name: "platform_workflow_detail", - description: "获取工作流详情(Piper)", - parameters: z.object({ - pipelineId: z.string().describe("工作流 ID"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { pipelineId: string } - ) => { - return await api.getWorkflowDetail(easoClient, params.pipelineId); - }, - }, - { - name: "platform_workflow_toggle", - description: "启用或停用工作流(Piper)。state=1 启用,state=0 停用", - parameters: z.object({ - pipelineId: z.string().describe("工作流 ID"), - state: WorkflowStateSchema.describe("状态:1 启用,0 停用"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { pipelineId: string; state: 0 | 1 } - ) => { - return await api.toggleWorkflow(easoClient, params.pipelineId, params.state); - }, - }, - { - name: "platform_workflow_jobs", - description: "查询工作流运行中的任务(Piper)", - parameters: z.object({ - pipelineId: z.string().describe("工作流 ID"), - runType: z.enum(["DEBUG", "PROD"]).optional().describe("运行类型,默认 DEBUG"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { pipelineId: string; runType?: "DEBUG" | "PROD" } - ) => { - return await api.listRunningJobs(easoClient, params.pipelineId, params.runType); - }, - }, - { - name: "platform_workflow_dsl", - description: "获取工作流 DSL 配置列表(Piper)", - parameters: z.object({}), - handler: async ({ easoClient }: PlatformClients) => { - return await api.listDsl(easoClient); - }, - }, - { - name: "platform_workflow_staffs", - description: "获取企业员工列表(Piper)", - parameters: z.object({ - external: z.boolean().optional().describe("是否包含外部人员,默认 false"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { external?: boolean } - ) => { - return await api.listStaffs(easoClient, params.external); - }, - }, - { - name: "platform_workflow_webhook", - description: "获取工作流 Webhook 信息(Piper)", - parameters: z.object({ - pipelineId: z.string().describe("工作流 ID"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { pipelineId: string } - ) => { - return await api.getWebhookInfo(easoClient, params.pipelineId); - }, - }, - { - name: "platform_workflow_sample", - description: "获取工作流测试/采样数据(Piper)", - parameters: z.object({ - pipelineId: z.string().describe("工作流 ID"), - }), - handler: async ( - { easoClient }: PlatformClients, - params: { pipelineId: string } - ) => { - return await api.sampleWorkflowData(easoClient, params.pipelineId); - }, - }, { name: "platform_workflow_list_all", - description: - "跨所有启用自建应用汇总工作流列表,返回带 platformId/platformName 的扁平结果", + description: "跨所有启用自建应用汇总工作流列表,返回带 platformId/platformName 的聚合结果", parameters: z.object({ page: z.number().optional().describe("页码,默认 1"), pageSize: z.number().optional().describe("每页数量,默认 20"), @@ -163,28 +24,16 @@ export const platformTools = [ }, }, { - name: "platform_workflow_find_by_task", - description: - "跨所有启用自建应用查找包含指定节点类型的工作流,递归扫描嵌套 tasks", + name: "platform_workflow_detail", + description: "获取工作流节点与 DSL 配置详情", parameters: z.object({ - taskType: z.string().describe("节点类型,如 http、code-js2、every、condition"), - page: z.number().optional().describe("页码,默认 1"), - pageSize: z.number().optional().describe("每页数量,默认 20"), - includeDetail: z - .boolean() - .optional() - .describe("是否先调用详情接口获取完整节点后再匹配,默认 false"), + pipelineId: z.string().describe("工作流 ID"), }), handler: async ( - clients: PlatformClients, - params: { - taskType: string; - page?: number; - pageSize?: number; - includeDetail?: boolean; - } + { easoClient }: PlatformClients, + params: { pipelineId: string } ) => { - return await findWorkflowsByTaskType(clients, params.taskType, params); + return await api.getWorkflowDetail(easoClient, params.pipelineId); }, }, ]; diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 0000000..52c905c --- /dev/null +++ b/src/version.ts @@ -0,0 +1 @@ +export const VERSION = "0.1.0";