Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1dc9f1616 | ||
|
|
07b4e14e59 | ||
|
|
ba30c1a6cb | ||
|
|
cf44c7dcdf | ||
|
|
9e20caf4a3 | ||
|
|
4f510efc1b |
No files matched your search
+2
-3
@@ -43,6 +43,5 @@ data/
|
|||||||
*.db
|
*.db
|
||||||
*.sqlite
|
*.sqlite
|
||||||
|
|
||||||
# 环境变量
|
# Local roadmaps & scratch notes
|
||||||
.env
|
*.local.md
|
||||||
.env.local
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# hose-use (v0.3.0)
|
# hose-use (v0.5.0)
|
||||||
|
|
||||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||||
|
|
||||||
@@ -32,8 +32,9 @@ hose-use corps list # 列出名下所有已配置企
|
|||||||
hose-use corps switch <corpId> # 切换工作企业
|
hose-use corps switch <corpId> # 切换工作企业
|
||||||
hose-use corps current # 查看当前激活企业
|
hose-use corps current # 查看当前激活企业
|
||||||
|
|
||||||
# 3. 运行模式管理 (有状态 vs 无状态)
|
# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态)
|
||||||
hose-use config show # 查看当前运行模式
|
hose-use config show # 查看当前运行模式与默认企业
|
||||||
|
hose-use config paths # 查看多级企业目录发现链与配置文件位置
|
||||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||||
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
|
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
|
||||||
|
|
||||||
@@ -44,8 +45,10 @@ hose-use workflow find --task=code-js2 # 搜索包含特定节点类型
|
|||||||
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
||||||
hose-use platform list # 查看企业下所有启用的自建应用
|
hose-use platform list # 查看企业下所有启用的自建应用
|
||||||
|
|
||||||
# 5. 单据与费用明细管理 (DataLink 字典自动还原)
|
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
|
||||||
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
|
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
|
||||||
|
hose-use bill list --json -o /tmp/bills.json # 自动转储大报文至本地文件,防止打爆上下文
|
||||||
|
hose-use bill list --json --full # 确需完整原始数据时跳过 200KB 限制
|
||||||
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
|
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
|
||||||
hose-use bill schema # 查看企业全部单据实体与数据模型字典
|
hose-use bill schema # 查看企业全部单据实体与数据模型字典
|
||||||
|
|
||||||
@@ -56,16 +59,29 @@ hose-use openapi info # 查看 OpenAPI 规范元数据
|
|||||||
hose-use openapi # 输出包装层标准 OpenAPI 3.1.0 JSON
|
hose-use openapi # 输出包装层标准 OpenAPI 3.1.0 JSON
|
||||||
hose-use openapi --raw # 输出原生下游全量 OpenAPI 3.1.0 JSON
|
hose-use openapi --raw # 输出原生下游全量 OpenAPI 3.1.0 JSON
|
||||||
|
|
||||||
# 7. Agent Skill 与连通性诊断
|
# 7. 内置 HTTP Server 与常驻 Service 守护进程
|
||||||
|
hose-use http --port=8888 # 前台启动 HTTP 服务与 Scalar 交互式文档 (http://localhost:8888/docs)
|
||||||
|
hose-use service start # 后台启动常驻守护进程
|
||||||
|
hose-use service status # 查看常驻服务运行状态、PID 与接口端点
|
||||||
|
hose-use service logs # 查看守护进程日志
|
||||||
|
hose-use service stop # 优雅停止常驻守护进程
|
||||||
|
|
||||||
|
# 8. Agent Skill 与连通性诊断
|
||||||
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||||
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
|
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
|
||||||
|
|
||||||
# 8. 一键自更新与版本发布历史
|
# 9. MCP Server (单工具网关模式)
|
||||||
hose-use update # 自动检查并升级到最新版本 (多镜像源加速)
|
hose-use mcp # 启动 MCP Server (默认暴露 hose_cli 单工具网关)
|
||||||
hose-use update --check # 仅检查新版本与 Release Notes
|
|
||||||
hose-use update --changelog # 查看最近版本发布历史
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### AI 智能体与 MCP 单工具网关 (`hose_cli`)
|
||||||
|
|
||||||
|
`hose-use` 采用 **单工具网关架构 (Single-Gate Pattern)**。在 MCP 环境下默认仅暴露一个 `hose_cli` 工具,接收 `command` 字符串:
|
||||||
|
- 避免数十个业务工具占用大量 Prompt Tokens;
|
||||||
|
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 中,Agent 按需学习;
|
||||||
|
- 内部同进程调用 CLI 分发层,零子进程开销;
|
||||||
|
- 若需要传统细粒度工具,可通过环境变量 `HOSE_MCP_MODE=all` 开启兼容模式。
|
||||||
|
|
||||||
## 架构
|
## 架构
|
||||||
|
|
||||||
```text
|
```text
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
openapi: 3.1.0
|
openapi: 3.1.0
|
||||||
info:
|
info:
|
||||||
title: hose-use API & MCP Tools Specification
|
title: hose-use API & MCP Tools Specification
|
||||||
version: 0.3.0
|
version: 0.5.0
|
||||||
description: >-
|
description: >-
|
||||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||||
servers:
|
servers:
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hose-use",
|
"name": "hose-use",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"module": "src/server.ts",
|
"module": "src/server.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -15,6 +15,32 @@ description: 合思/易快报 (ekuaibao) 企业 SaaS CLI 命令行工具与底
|
|||||||
- **有状态 / 无状态双模式**:
|
- **有状态 / 无状态双模式**:
|
||||||
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
|
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
|
||||||
- **无状态 (Stateless)**:严格要求 `--corp <corpId>`,防止多租户或 Agent 误操作。
|
- **无状态 (Stateless)**:严格要求 `--corp <corpId>`,防止多租户或 Agent 误操作。
|
||||||
|
- **MCP 单工具网关架构**:统一暴露 `hose_cli` 工具,避免数十个细粒度工具膨胀污染 Agent 的上下文,零子进程同构执行。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 调用通道与执行协议
|
||||||
|
|
||||||
|
`hose-use` 同时支持 **MCP 工具** 与 **Shell CLI** 两种调用通道:
|
||||||
|
|
||||||
|
- **MCP 工具通道 (AI Agent 优先推荐)**:在具备 MCP 的智能体环境中,优先调用 `hose_cli` 工具网关:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"command": "corps list"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
或者执行业务检索:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"command": "bill query --code BX20260901001 --corp ID01MCcOgJl1td"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **Shell CLI 通道 (运维/终端/脚本)**:在终端或子进程环境中,直接执行:
|
||||||
|
```bash
|
||||||
|
hose corps list
|
||||||
|
# 或
|
||||||
|
hose-use bill query --code BX20260901001
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -58,6 +84,9 @@ hose-use corps current
|
|||||||
# 查看全局运行模式与配置文件路径
|
# 查看全局运行模式与配置文件路径
|
||||||
hose-use config show
|
hose-use config show
|
||||||
|
|
||||||
|
# 查看多级企业目录发现路径与诊断
|
||||||
|
hose-use config paths
|
||||||
|
|
||||||
# 切换为无状态模式 (Stateless)
|
# 切换为无状态模式 (Stateless)
|
||||||
hose-use config mode stateless
|
hose-use config mode stateless
|
||||||
|
|
||||||
@@ -91,6 +120,11 @@ hose-use platform list
|
|||||||
hose-use bill list
|
hose-use bill list
|
||||||
hose-use bill list --stage=expense --state=paid --count=10
|
hose-use bill list --stage=expense --state=paid --count=10
|
||||||
|
|
||||||
|
# 大数据量防爆落盘: 使用 -o / --output-file 将完整 JSON 转储至本地文件 (推荐 Agent 处理海量数据时使用)
|
||||||
|
hose-use bill list --json -o /tmp/bills.json
|
||||||
|
# 确需向终端输出完整大报文时附加 --full (跳过 200KB 防爆限制)
|
||||||
|
hose-use bill list --json --full
|
||||||
|
|
||||||
# 根据单号或 ID 精确查询单据结构化详情 (DataLink 字典自动还原)
|
# 根据单号或 ID 精确查询单据结构化详情 (DataLink 字典自动还原)
|
||||||
hose-use bill get n0GMIM0dkQmKbS
|
hose-use bill get n0GMIM0dkQmKbS
|
||||||
hose-use bill get ID01TRzg7HMLcb
|
hose-use bill get ID01TRzg7HMLcb
|
||||||
@@ -129,7 +163,26 @@ hose-use openapi
|
|||||||
hose-use openapi --raw
|
hose-use openapi --raw
|
||||||
```
|
```
|
||||||
|
|
||||||
### 8. 自更新与版本历史 (`hose-use update`)
|
### 8. HTTP 服务与常驻守护进程 (`hose-use http` / `hose-use service`)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 启动本地轻量 HTTP 服务并打开 Scalar 交互式文档 (http://127.0.0.1:8888/docs)
|
||||||
|
hose-use http --port=8888
|
||||||
|
|
||||||
|
# 后台启动常驻守护进程服务
|
||||||
|
hose-use service start
|
||||||
|
|
||||||
|
# 查看常驻守护进程运行状态与端点
|
||||||
|
hose-use service status
|
||||||
|
|
||||||
|
# 查看常驻守护进程最近运行日志
|
||||||
|
hose-use service logs
|
||||||
|
|
||||||
|
# 停止后台常驻守护进程
|
||||||
|
hose-use service stop
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9. 自更新与版本历史 (`hose-use update`)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 检查最新可用版本与 Release Notes
|
# 检查最新可用版本与 Release Notes
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
fullSmsLogin,
|
fullSmsLogin,
|
||||||
fullBrowserSyncLogin,
|
fullBrowserSyncLogin,
|
||||||
sendSmsVerificationCode,
|
sendSmsVerificationCode,
|
||||||
|
importCredentials,
|
||||||
importF12Credentials,
|
importF12Credentials,
|
||||||
parseHeadersOrCurl,
|
parseHeadersOrCurl,
|
||||||
refreshAccountCorporations,
|
refreshAccountCorporations,
|
||||||
@@ -14,7 +15,7 @@ import {
|
|||||||
} from "../../core/auth/account-store.js";
|
} from "../../core/auth/account-store.js";
|
||||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||||
import { stringOption, booleanOption } from "../parser.js";
|
import { stringOption, booleanOption } from "../parser.js";
|
||||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||||
import { prompt } from "../helpers.js";
|
import { prompt } from "../helpers.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
|
|
||||||
@@ -171,13 +172,41 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
return { stdout: printJson(statusObj), stderr: "", exitCode: 0 };
|
return { stdout: printJson(statusObj), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const summary = printKeyValue({
|
const pairs: Record<string, unknown> = {
|
||||||
"当前活跃账号": activeAccount?.accountId || "未登录",
|
"当前活跃账号": activeAccount?.accountId || "未登录",
|
||||||
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
|
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
|
||||||
"当前员工工号": currentCorp?.credentials.staffId || "-",
|
"当前员工工号": currentCorp?.credentials.staffId || "-",
|
||||||
"凭证来源类型": currentCorp?.source || "-",
|
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
|
||||||
|
"凭证来源类型": formatSourceLabel(currentCorp?.source),
|
||||||
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
|
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
|
||||||
});
|
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (currentCorp?.session) {
|
||||||
|
if (currentCorp.session.loginTime) {
|
||||||
|
pairs["会话创建时间"] = new Date(currentCorp.session.loginTime).toLocaleString("zh-CN", { hour12: false });
|
||||||
|
}
|
||||||
|
if (currentCorp.session.platform) {
|
||||||
|
pairs["官方平台类型"] = currentCorp.session.platform;
|
||||||
|
}
|
||||||
|
if (currentCorp.session.isAssistPlatform) {
|
||||||
|
pairs["协助调试模式"] = "是 (Assist Platform)";
|
||||||
|
if (currentCorp.session.operationUserName || currentCorp.session.operationUserId) {
|
||||||
|
pairs["协助操作人员"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
|
||||||
|
}
|
||||||
|
if (currentCorp.session.assistId) {
|
||||||
|
pairs["协助会话 ID"] = currentCorp.session.assistId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentCorp.session.cellphone) {
|
||||||
|
pairs["绑定手机号码"] = currentCorp.session.cellphone;
|
||||||
|
}
|
||||||
|
if (currentCorp.session.isAdmin !== undefined) {
|
||||||
|
pairs["是否企业管理"] = currentCorp.session.isAdmin ? "是" : "否";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = printKeyValue(pairs);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `====== 当前登录与企业状态 ======\n${summary}\n`,
|
stdout: `====== 当前登录与企业状态 ======\n${summary}\n`,
|
||||||
@@ -209,7 +238,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
let name = stringOption(parsed.options, ["name"]);
|
let name = stringOption(parsed.options, ["name"]);
|
||||||
|
|
||||||
if (!raw && !accessToken) {
|
if (!raw && !accessToken) {
|
||||||
raw = await prompt("请粘贴 F12 抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
|
raw = await prompt("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (raw) {
|
if (raw) {
|
||||||
@@ -227,7 +256,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
|
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const imported = await importF12Credentials({
|
const imported = await importCredentials({
|
||||||
accessToken,
|
accessToken,
|
||||||
corpId,
|
corpId,
|
||||||
staffId,
|
staffId,
|
||||||
@@ -238,8 +267,30 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
return { stdout: printJson(imported), stderr: "", exitCode: 0 };
|
return { stdout: printJson(imported), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const summaryPairs: Record<string, unknown> = {
|
||||||
|
"企业名称": imported.name,
|
||||||
|
"企业 ID": imported.id,
|
||||||
|
"员工工号": imported.credentials.staffId,
|
||||||
|
"员工姓名": imported.staffName || imported.session?.staffName || "-",
|
||||||
|
"凭证来源": formatSourceLabel(imported.source),
|
||||||
|
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
|
||||||
|
"保存路径": `enterprises/${imported.id}.json`,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (imported.session?.isAssistPlatform) {
|
||||||
|
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
|
||||||
|
if (imported.session.operationUserName || imported.session.operationUserId) {
|
||||||
|
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
|
||||||
|
}
|
||||||
|
if (imported.session.assistId) {
|
||||||
|
summaryPairs["协助会话 ID"] = imported.session.assistId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const summaryText = printKeyValue(summaryPairs);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n企业名称: ${imported.name}\n企业 ID: ${imported.id}\n员工工号: ${imported.credentials.staffId}\n保存路径: enterprises/${imported.id}.json\n`,
|
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
|
|||||||
+28
-19
@@ -43,13 +43,16 @@ export async function handleBillCommand(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
corpId,
|
{
|
||||||
corpName: corp.name,
|
corpId,
|
||||||
total: result.total,
|
corpName: corp.name,
|
||||||
returned: result.returned,
|
total: result.total,
|
||||||
items: result.items,
|
returned: result.returned,
|
||||||
}),
|
items: result.items,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
@@ -104,12 +107,15 @@ export async function handleBillCommand(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
corpId,
|
{
|
||||||
corpName: corp.name,
|
corpId,
|
||||||
count: bills.length,
|
corpName: corp.name,
|
||||||
bills,
|
count: bills.length,
|
||||||
}),
|
bills,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
@@ -157,12 +163,15 @@ export async function handleBillCommand(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
corpId,
|
{
|
||||||
corpName: corp.name,
|
corpId,
|
||||||
totalEntities: entities.length,
|
corpName: corp.name,
|
||||||
entities,
|
totalEntities: entities.length,
|
||||||
}),
|
entities,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ import {
|
|||||||
loadGlobalConfig,
|
loadGlobalConfig,
|
||||||
saveGlobalConfig,
|
saveGlobalConfig,
|
||||||
resolveGlobalConfigFile,
|
resolveGlobalConfigFile,
|
||||||
|
resolveEnterprisesDirs,
|
||||||
|
resolveWritableEnterprisesDir,
|
||||||
|
getEnterprisesDirCandidates,
|
||||||
} from "../../core/config/loader.js";
|
} from "../../core/config/loader.js";
|
||||||
import { printJson, printKeyValue } from "../printer.js";
|
import { printJson, printKeyValue } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
@@ -17,6 +20,10 @@ export async function handleConfigCommand(
|
|||||||
case "get":
|
case "get":
|
||||||
case "list":
|
case "list":
|
||||||
return handleShow(parsed, runtime);
|
return handleShow(parsed, runtime);
|
||||||
|
case "paths":
|
||||||
|
case "path":
|
||||||
|
case "dirs":
|
||||||
|
return handlePaths(parsed, runtime);
|
||||||
case "mode":
|
case "mode":
|
||||||
return handleMode(parsed, runtime);
|
return handleMode(parsed, runtime);
|
||||||
case "set":
|
case "set":
|
||||||
@@ -24,7 +31,7 @@ export async function handleConfigCommand(
|
|||||||
default:
|
default:
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: `未知 config 子命令: ${action}。支持: show, mode <stateful|stateless>, set <key> <val>\n`,
|
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, set <key> <val>\n`,
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -125,3 +132,43 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
|||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
|
const envDir = process.env.HOSE_ENTERPRISES_DIR;
|
||||||
|
const envUserDir = process.env.HOSE_USER_ENTERPRISES_DIR;
|
||||||
|
const envConfigFile = process.env.HOSE_CONFIG_FILE;
|
||||||
|
const existingDirs = resolveEnterprisesDirs();
|
||||||
|
const writableDir = resolveWritableEnterprisesDir();
|
||||||
|
const configFile = resolveGlobalConfigFile();
|
||||||
|
const candidates = getEnterprisesDirCandidates();
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
configFile,
|
||||||
|
writableDir,
|
||||||
|
existingDirs,
|
||||||
|
env: {
|
||||||
|
HOSE_ENTERPRISES_DIR: envDir || null,
|
||||||
|
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
|
||||||
|
HOSE_CONFIG_FILE: envConfigFile || null,
|
||||||
|
},
|
||||||
|
candidates,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return { stdout: printJson(data), stderr: "", exitCode: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = printKeyValue({
|
||||||
|
"当前生效配置文件": configFile,
|
||||||
|
"凭证保存写入目录": writableDir,
|
||||||
|
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
|
||||||
|
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
|
||||||
|
"全部目录候选链": candidates.join("\n "),
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
stdout: `====== 配置路径诊断 (Config Paths) ======\n${output}\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
+43
-11
@@ -1,4 +1,4 @@
|
|||||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
|
|
||||||
export async function handleCorpsCommand(
|
export async function handleCorpsCommand(
|
||||||
@@ -29,10 +29,13 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
activeCorpId: runtime.selectedCorp?.id,
|
{
|
||||||
corporations: corps,
|
activeCorpId: runtime.selectedCorp?.id,
|
||||||
}),
|
corporations: corps,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
@@ -48,11 +51,12 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
c.name,
|
c.name,
|
||||||
c.staffId,
|
c.staffId,
|
||||||
c.source || "manual",
|
c.source || "manual",
|
||||||
|
formatExpiresAt(c.expiresAt),
|
||||||
c.accountId || "-",
|
c.accountId || "-",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const table = printTable(
|
const table = printTable(
|
||||||
["#", "企业 ID", "企业名称", "员工工号", "来源", "所属账号"],
|
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||||
rows
|
rows
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -80,7 +84,7 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
|
|
||||||
const current = runtime.corpContext.getCurrent();
|
const current = runtime.corpContext.getCurrent();
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(current), stderr: "", exitCode: 0 };
|
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -97,17 +101,45 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(current), stderr: "", exitCode: 0 };
|
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const output = printKeyValue({
|
const pairs: Record<string, unknown> = {
|
||||||
"企业 ID": current.id,
|
"企业 ID": current.id,
|
||||||
"企业名称": current.name,
|
"企业名称": current.name,
|
||||||
"员工工号": current.credentials.staffId,
|
"员工工号": current.credentials.staffId,
|
||||||
"来源类型": current.source || "manual",
|
"员工姓名": current.staffName || current.session?.staffName || "-",
|
||||||
|
"凭证来源": formatSourceLabel(current.source),
|
||||||
|
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
|
||||||
"所属账号": current.accountId || "-",
|
"所属账号": current.accountId || "-",
|
||||||
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
||||||
});
|
};
|
||||||
|
|
||||||
|
if (current.session) {
|
||||||
|
if (current.session.loginTime) {
|
||||||
|
pairs["会话创建时间"] = new Date(current.session.loginTime).toLocaleString("zh-CN", { hour12: false });
|
||||||
|
}
|
||||||
|
if (current.session.platform) {
|
||||||
|
pairs["官方平台类型"] = current.session.platform;
|
||||||
|
}
|
||||||
|
if (current.session.isAssistPlatform) {
|
||||||
|
pairs["协助登录模式"] = "是 (Assist Platform)";
|
||||||
|
if (current.session.operationUserName || current.session.operationUserId) {
|
||||||
|
pairs["协助操作人员"] = `${current.session.operationUserName || ""} (${current.session.operationUserId || ""})`.trim();
|
||||||
|
}
|
||||||
|
if (current.session.assistId) {
|
||||||
|
pairs["协助会话 ID"] = current.session.assistId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (current.session.cellphone) {
|
||||||
|
pairs["绑定手机号码"] = current.session.cellphone;
|
||||||
|
}
|
||||||
|
if (current.session.isAdmin !== undefined) {
|
||||||
|
pairs["是否企业管理"] = current.session.isAdmin ? "是" : "否";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = printKeyValue(pairs);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `====== 当前激活企业 ======\n${output}\n`,
|
stdout: `====== 当前激活企业 ======\n${output}\n`,
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { startHttpServer } from "../../http/server.js";
|
||||||
|
import { numberOption, stringOption } from "../parser.js";
|
||||||
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
|
|
||||||
|
export async function handleHttpCommand(
|
||||||
|
parsed: CliParsedArgs,
|
||||||
|
runtime: CliRuntime
|
||||||
|
): Promise<CliResult> {
|
||||||
|
const port = numberOption(parsed.options, ["port", "p"]);
|
||||||
|
const host = stringOption(parsed.options, ["host", "h"]);
|
||||||
|
|
||||||
|
const server = await startHttpServer({ port, host, silent: runtime.jsonMode });
|
||||||
|
|
||||||
|
// Handle graceful shutdown
|
||||||
|
const shutdown = () => {
|
||||||
|
server.close(() => {
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
process.on("SIGINT", shutdown);
|
||||||
|
process.on("SIGTERM", shutdown);
|
||||||
|
|
||||||
|
// Keep alive in foreground
|
||||||
|
await new Promise<void>(() => {});
|
||||||
|
|
||||||
|
return { stdout: "", stderr: "", exitCode: 0 };
|
||||||
|
}
|
||||||
@@ -36,7 +36,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(platforms), stderr: "", exitCode: 0 };
|
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (platforms.length === 0) {
|
if (platforms.length === 0) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createClientsForCorp } from "../helpers.js";
|
import { createClientsForCorp } from "../helpers.js";
|
||||||
import * as api from "../../domains/platform/api.js";
|
import * as api from "../../domains/platform/api.js";
|
||||||
import { printJson, printKeyValue } from "../printer.js";
|
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
|
|
||||||
export async function handleProbeCommand(
|
export async function handleProbeCommand(
|
||||||
@@ -79,14 +79,26 @@ export async function handleProbeCommand(
|
|||||||
return { stdout: printJson(results), stderr: "", exitCode: 0 };
|
return { stdout: printJson(results), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const summary = printKeyValue({
|
const probePairs: Record<string, unknown> = {
|
||||||
"企业名称": currentCorp.name,
|
"企业名称": currentCorp.name,
|
||||||
"企业 ID": currentCorp.id,
|
"企业 ID": currentCorp.id,
|
||||||
"员工工号": currentCorp.credentials.staffId,
|
"员工工号": currentCorp.credentials.staffId,
|
||||||
|
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
|
||||||
|
"凭证来源": formatSourceLabel(currentCorp.source),
|
||||||
|
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime),
|
||||||
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
|
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
|
||||||
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
|
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
|
||||||
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
|
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
|
||||||
});
|
};
|
||||||
|
|
||||||
|
if (currentCorp.session?.isAssistPlatform) {
|
||||||
|
probePairs["协助操作人"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
|
||||||
|
if (currentCorp.session.assistId) {
|
||||||
|
probePairs["协助会话 ID"] = currentCorp.session.assistId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = printKeyValue(probePairs);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `====== 诊断结果 (Enterprise Probe) ======\n${summary}\n`,
|
stdout: `====== 诊断结果 (Enterprise Probe) ======\n${summary}\n`,
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { homedir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { VERSION } from "../../version.js";
|
||||||
|
import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../service.js";
|
||||||
|
import { printJson, printKeyValue } from "../printer.js";
|
||||||
|
import { numberOption, stringOption } from "../parser.js";
|
||||||
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
|
|
||||||
|
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||||
|
|
||||||
|
export async function handleServiceCommand(
|
||||||
|
parsed: CliParsedArgs,
|
||||||
|
runtime: CliRuntime
|
||||||
|
): Promise<CliResult> {
|
||||||
|
const action = parsed.action || parsed.args[0] || "status";
|
||||||
|
const port = numberOption(parsed.options, ["port", "p"]);
|
||||||
|
const host = stringOption(parsed.options, ["host", "h"]);
|
||||||
|
|
||||||
|
const config: ServiceConfig = {
|
||||||
|
appRoot: runtime.appRoot || process.cwd(),
|
||||||
|
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
|
||||||
|
stateDir: SERVICE_STATE_DIR,
|
||||||
|
version: VERSION,
|
||||||
|
launcher: runtime.launcher,
|
||||||
|
port,
|
||||||
|
host,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await runServiceCommand(action, config);
|
||||||
|
|
||||||
|
if (result === undefined) {
|
||||||
|
// 'run' keeps running, resolves on shutdown
|
||||||
|
return { stdout: "", stderr: "", exitCode: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action === "logs" || action === "log") {
|
||||||
|
const logsResult = result as { logFile: string; lines: string[]; content: string };
|
||||||
|
return {
|
||||||
|
stdout: `====== hose-use 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = result as Record<string, unknown>;
|
||||||
|
const isRunning = Boolean(status.running);
|
||||||
|
|
||||||
|
const displayPairs: Record<string, unknown> = {
|
||||||
|
"服务状态": isRunning ? "🟢 正在运行 (Running)" : "⚪ 已停止 (Stopped)",
|
||||||
|
...(status.pid ? { "进程 PID": status.pid } : {}),
|
||||||
|
...(status.url ? { "服务地址": status.url } : {}),
|
||||||
|
...(status.url ? { "交互式文档": `${status.url}/docs` } : {}),
|
||||||
|
...(status.url ? { "CLI 网关": `POST ${status.url}/api/cli` } : {}),
|
||||||
|
"运行版本": status.version || config.version,
|
||||||
|
"状态目录": status.stateDir || config.stateDir,
|
||||||
|
"PID 文件": status.pidFile || getPidFile(config),
|
||||||
|
"日志文件": status.logFile || getLogFile(config),
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatted = printKeyValue(displayPairs);
|
||||||
|
return {
|
||||||
|
stdout: `====== hose-use 常驻服务管理 (Service) ======\n${formatted}\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -54,7 +54,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
const result = await listAllWorkflows(clients, { page, pageSize });
|
const result = await listAllWorkflows(clients, { page, pageSize });
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.workflows.length === 0) {
|
if (result.workflows.length === 0) {
|
||||||
@@ -96,7 +96,7 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
|||||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(detail), stderr: "", exitCode: 0 };
|
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const summary = printKeyValue({
|
const summary = printKeyValue({
|
||||||
@@ -148,7 +148,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.workflows.length === 0) {
|
if (result.workflows.length === 0) {
|
||||||
@@ -196,7 +196,7 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
|
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
+14
-3
@@ -1,10 +1,10 @@
|
|||||||
import readline from "readline";
|
import readline from "readline";
|
||||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
import { loadCorpConfigs, loadGlobalConfig, getEnterprisesDirCandidates } from "../core/config/loader.js";
|
||||||
import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||||
import { CorpConfig } from "../core/config/types.js";
|
import { CorpConfig } from "../core/config/types.js";
|
||||||
import { createEkbClient } from "../core/auth/ekb.js";
|
import { createEkbClient } from "../core/auth/ekb.js";
|
||||||
import { getEasoClient } from "../core/auth/easo.js";
|
import { getEasoClient } from "../core/auth/easo.js";
|
||||||
import { CliRuntime } from "./types.js";
|
import { CliRuntime, OutputOptions } from "./types.js";
|
||||||
|
|
||||||
export function initCorpRuntime(
|
export function initCorpRuntime(
|
||||||
options: {
|
options: {
|
||||||
@@ -12,6 +12,13 @@ export function initCorpRuntime(
|
|||||||
stateless?: boolean;
|
stateless?: boolean;
|
||||||
stateful?: boolean;
|
stateful?: boolean;
|
||||||
jsonMode?: boolean;
|
jsonMode?: boolean;
|
||||||
|
outputOptions?: OutputOptions;
|
||||||
|
appRoot?: string;
|
||||||
|
entryFile?: string;
|
||||||
|
launcher?: {
|
||||||
|
command: string;
|
||||||
|
args?: string[];
|
||||||
|
};
|
||||||
} = {}
|
} = {}
|
||||||
): CliRuntime {
|
): CliRuntime {
|
||||||
const corps = loadCorpConfigs();
|
const corps = loadCorpConfigs();
|
||||||
@@ -31,7 +38,7 @@ export function initCorpRuntime(
|
|||||||
|
|
||||||
let selectedCorp: CorpConfig | null = null;
|
let selectedCorp: CorpConfig | null = null;
|
||||||
try {
|
try {
|
||||||
selectedCorp = corpContext.resolve(options.corpId);
|
selectedCorp = corpContext.resolve(options.corpId, getEnterprisesDirCandidates());
|
||||||
} catch {
|
} catch {
|
||||||
selectedCorp = null;
|
selectedCorp = null;
|
||||||
}
|
}
|
||||||
@@ -40,6 +47,10 @@ export function initCorpRuntime(
|
|||||||
corpContext,
|
corpContext,
|
||||||
selectedCorp,
|
selectedCorp,
|
||||||
jsonMode: options.jsonMode ?? false,
|
jsonMode: options.jsonMode ?? false,
|
||||||
|
outputOptions: options.outputOptions,
|
||||||
|
appRoot: options.appRoot,
|
||||||
|
entryFile: options.entryFile,
|
||||||
|
launcher: options.launcher,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-2
@@ -1,4 +1,4 @@
|
|||||||
import type { CliParsedArgs } from "./types.js";
|
import type { CliParsedArgs, OutputOptions } from "./types.js";
|
||||||
|
|
||||||
const KNOWN_BOOLEAN_FLAGS = new Set([
|
const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||||
"raw",
|
"raw",
|
||||||
@@ -19,6 +19,10 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
|||||||
"local",
|
"local",
|
||||||
"workspace",
|
"workspace",
|
||||||
"external",
|
"external",
|
||||||
|
"full",
|
||||||
|
"allow-full",
|
||||||
|
"allowFull",
|
||||||
|
"summary",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||||
@@ -61,7 +65,17 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
|||||||
if (flag === "h") options.help = true;
|
if (flag === "h") options.help = true;
|
||||||
else if (flag === "j") options.json = true;
|
else if (flag === "j") options.json = true;
|
||||||
else if (flag === "v") options.version = true;
|
else if (flag === "v") options.version = true;
|
||||||
else options[flag] = true;
|
else if (flag === "o") {
|
||||||
|
const next = rawArgs[i + 1];
|
||||||
|
if (next && !next.startsWith("-")) {
|
||||||
|
options.outputFile = next;
|
||||||
|
i++;
|
||||||
|
} else {
|
||||||
|
options.o = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
options[flag] = true;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,3 +135,11 @@ export function numberOption(
|
|||||||
}
|
}
|
||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function outputOptions(options: Record<string, unknown>): OutputOptions {
|
||||||
|
return {
|
||||||
|
allowFull: booleanOption(options, ["full", "allow-full", "allowFull"]),
|
||||||
|
outputFile: stringOption(options, ["output-file", "outputFile", "o"]),
|
||||||
|
summary: booleanOption(options, ["summary"]),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
|
||||||
|
import { mkdtempSync, rmSync, existsSync, readFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import {
|
||||||
|
DEFAULT_OUTPUT_BYTES_LIMIT,
|
||||||
|
protectLargeOutput,
|
||||||
|
printJson,
|
||||||
|
redactSensitiveText,
|
||||||
|
} from "./printer.js";
|
||||||
|
|
||||||
|
describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||||
|
describe("redactSensitiveText 脱敏处理", () => {
|
||||||
|
test("脱敏 URL Query 中的 accessToken / token / returnToken", () => {
|
||||||
|
const input = "https://app.ekuaibao.com/api/test?accessToken=sec_123456&corpId=corpxx&returnToken=ret_789";
|
||||||
|
const redacted = redactSensitiveText(input);
|
||||||
|
expect(redacted).not.toContain("sec_123456");
|
||||||
|
expect(redacted).not.toContain("ret_789");
|
||||||
|
expect(redacted).toContain("accessToken=<redacted>");
|
||||||
|
expect(redacted).toContain("returnToken=<redacted>");
|
||||||
|
expect(redacted).toContain("corpId=corpxx");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("脱敏 Authorization Bearer token", () => {
|
||||||
|
const input = "Request headers: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz";
|
||||||
|
const redacted = redactSensitiveText(input);
|
||||||
|
expect(redacted).not.toContain("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz");
|
||||||
|
expect(redacted).toContain("Bearer <redacted>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("脱敏 password、secret、appSecurity 等键值", () => {
|
||||||
|
const input = '{"username": "admin", "password": "super_secret_password_123", "appSecurity": "sec_key"}';
|
||||||
|
const redacted = redactSensitiveText(input);
|
||||||
|
expect(redacted).not.toContain("super_secret_password_123");
|
||||||
|
expect(redacted).not.toContain("sec_key");
|
||||||
|
expect(redacted).toContain('"password": "<redacted>"');
|
||||||
|
expect(redacted).toContain('"appSecurity": "<redacted>"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("protectLargeOutput 与 printJson 体积熔断保护", () => {
|
||||||
|
let tempDir: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = mkdtempSync(join(tmpdir(), "hose-printer-test-"));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
try {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("正常体积的数据可以直接输出 JSON", () => {
|
||||||
|
const normalData = { hello: "world", numbers: [1, 2, 3] };
|
||||||
|
expect(() => protectLargeOutput(normalData)).not.toThrow();
|
||||||
|
const output = printJson(normalData);
|
||||||
|
expect(JSON.parse(output)).toEqual(normalData);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("超过 200KB 的巨型数据默认抛出熔断错误", () => {
|
||||||
|
// 构造超过 200KB 的大数组
|
||||||
|
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||||
|
id: `id-${i}`,
|
||||||
|
description: "这是一个用于测试大报文熔断拦截的测试长字段内容,模拟企业级海量单据与工作流节点拓扑",
|
||||||
|
nested: { count: i, payload: "x".repeat(120) },
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(() => protectLargeOutput(bigArray)).toThrow(
|
||||||
|
/输出体积过大.*超过安全阈值.*--output-file.*--full/
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(() => printJson(bigArray)).toThrow(/输出体积过大/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("显式指定 allowFull 时允许全量输出大报文", () => {
|
||||||
|
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||||
|
id: `id-${i}`,
|
||||||
|
payload: "y".repeat(150),
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(() => protectLargeOutput(bigArray, { allowFull: true })).not.toThrow();
|
||||||
|
const output = printJson(bigArray, { allowFull: true });
|
||||||
|
expect(output.length).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("指定 outputFile 时大报文直接落盘并返回精简摘要", () => {
|
||||||
|
const targetFile = join(tempDir, "exported-bills.json");
|
||||||
|
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||||
|
id: `id-${i}`,
|
||||||
|
payload: "z".repeat(150),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const resultJson = printJson(bigArray, { outputFile: targetFile });
|
||||||
|
const summary = JSON.parse(resultJson);
|
||||||
|
|
||||||
|
expect(summary.outputFile).toBe(targetFile);
|
||||||
|
expect(summary.bytes).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
|
||||||
|
expect(existsSync(targetFile)).toBe(true);
|
||||||
|
|
||||||
|
const savedContent = JSON.parse(readFileSync(targetFile, "utf-8"));
|
||||||
|
expect(savedContent).toHaveLength(1500);
|
||||||
|
expect(savedContent[0].id).toBe("id-0");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
+88
-8
@@ -1,7 +1,78 @@
|
|||||||
|
import { writeFileSync } from "node:fs";
|
||||||
import { VERSION } from "../version.js";
|
import { VERSION } from "../version.js";
|
||||||
|
import type { OutputOptions } from "./types.js";
|
||||||
|
|
||||||
export function printJson(data: unknown): string {
|
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||||
return JSON.stringify(data, null, 2);
|
|
||||||
|
export function redactSensitiveText(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1<redacted>")
|
||||||
|
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||||
|
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
|
||||||
|
if (options.allowFull || options.outputFile) return;
|
||||||
|
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
|
||||||
|
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
|
||||||
|
throw new Error(
|
||||||
|
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||||
|
protectLargeOutput(data, options);
|
||||||
|
const json = JSON.stringify(data, null, 2);
|
||||||
|
if (options.outputFile) {
|
||||||
|
writeFileSync(options.outputFile, json, "utf-8");
|
||||||
|
return JSON.stringify(
|
||||||
|
{
|
||||||
|
outputFile: options.outputFile,
|
||||||
|
bytes: Buffer.byteLength(json, "utf-8"),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatSourceLabel(source?: string): string {
|
||||||
|
switch (source) {
|
||||||
|
case "assist":
|
||||||
|
return "官方协助/代客平台 (Assist Platform)";
|
||||||
|
case "account":
|
||||||
|
return "统一认证中心 (IDP 账密/短信)";
|
||||||
|
case "browser":
|
||||||
|
return "浏览器会话同步 (WebBridge)";
|
||||||
|
case "curl":
|
||||||
|
case "f12":
|
||||||
|
return "cURL 抓包导入 (cURL/F12)";
|
||||||
|
case "manual":
|
||||||
|
return "手动配置";
|
||||||
|
default:
|
||||||
|
return source || "未知来源";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatExpiresAt(expiresAt?: number): string {
|
||||||
|
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
|
||||||
|
const diffMs = expiresAt - Date.now();
|
||||||
|
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
|
||||||
|
if (diffMs <= 0) {
|
||||||
|
return `${dateStr} (⚠️ 已过期)`;
|
||||||
|
}
|
||||||
|
const diffMins = Math.floor(diffMs / 60000);
|
||||||
|
if (diffMins < 60) {
|
||||||
|
return `${dateStr} (约剩余 ${diffMins} 分钟)`;
|
||||||
|
}
|
||||||
|
const diffHours = (diffMs / 3600000).toFixed(1);
|
||||||
|
if (Number(diffHours) < 24) {
|
||||||
|
return `${dateStr} (约剩余 ${diffHours} 小时)`;
|
||||||
|
}
|
||||||
|
const diffDays = Math.floor(diffMs / 86400000);
|
||||||
|
return `${dateStr} (约剩余 ${diffDays} 天)`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function printKeyValue(pairs: Record<string, unknown>): string {
|
export function printKeyValue(pairs: Record<string, unknown>): string {
|
||||||
@@ -46,7 +117,7 @@ export function printHelp(): string {
|
|||||||
核心命令域:
|
核心命令域:
|
||||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||||
corps 多企业租户管理 (list, switch, current)
|
corps 多企业租户管理 (list, switch, current)
|
||||||
config 全局运行模式 (show, mode <stateful|stateless>, set)
|
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||||
workflow 工作流管理 (list, get, find, toggle)
|
workflow 工作流管理 (list, get, find, toggle)
|
||||||
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
|
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
|
||||||
platform 自建应用管理 (list)
|
platform 自建应用管理 (list)
|
||||||
@@ -54,26 +125,35 @@ export function printHelp(): string {
|
|||||||
probe 连通性诊断 (probe [corpId])
|
probe 连通性诊断 (probe [corpId])
|
||||||
update 版本自更新与发布记录 (update, update check, update --changelog)
|
update 版本自更新与发布记录 (update, update check, update --changelog)
|
||||||
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
|
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
|
||||||
|
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
|
||||||
|
service 常驻守护进程管理 (service start|stop|restart|status|logs)
|
||||||
mcp MCP Server 运行 (serve)
|
mcp MCP Server 运行 (serve)
|
||||||
version 查看版本信息
|
version 查看版本信息
|
||||||
|
|
||||||
全局选项:
|
全局选项:
|
||||||
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
|
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
|
||||||
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
|
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
|
||||||
--stateless 单次强制以无状态模式执行
|
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
|
||||||
--stateful 单次强制以有状态模式执行
|
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
|
||||||
--help, -h 查看帮助信息
|
--stateless 单次强制以无状态模式执行
|
||||||
|
--stateful 单次强制以有状态模式执行
|
||||||
|
--help, -h 查看帮助信息
|
||||||
|
|
||||||
常用示例:
|
常用示例:
|
||||||
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
||||||
hose-use auth status # 查看当前登录状态与活跃企业
|
hose-use auth status # 查看当前登录状态与活跃企业
|
||||||
|
hose-use config paths # 查看多级企业配置目录链
|
||||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||||
hose-use corps list # 列出名下所有企业
|
hose-use corps list # 列出名下所有企业
|
||||||
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
|
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
|
||||||
hose-use workflow list # 汇总查看全部工作流
|
hose-use workflow list # 汇总查看全部工作流
|
||||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||||
hose-use bill list # 查看当前企业单据与报销列表
|
hose-use bill list # 查看当前企业单据与报销列表
|
||||||
|
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
|
||||||
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
||||||
|
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
|
||||||
|
hose-use service start # 后台启动常驻守护进程服务
|
||||||
|
hose-use service status # 查看守护进程运行状态与接口地址
|
||||||
hose-use probe # 诊断当前企业鉴权连通性
|
hose-use probe # 诊断当前企业鉴权连通性
|
||||||
hose-use skill install # 安装 Agent 技能到用户目录
|
hose-use skill install # 安装 Agent 技能到用户目录
|
||||||
hose-use update # 自动检查并升级到最新版本
|
hose-use update # 自动检查并升级到最新版本
|
||||||
|
|||||||
+77
-5
@@ -1,6 +1,6 @@
|
|||||||
import { VERSION } from "../version.js";
|
import { VERSION } from "../version.js";
|
||||||
import { parseArgs, stringOption, booleanOption } from "./parser.js";
|
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
|
||||||
import { printHelp, printJson } from "./printer.js";
|
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||||
import { initCorpRuntime } from "./helpers.js";
|
import { initCorpRuntime } from "./helpers.js";
|
||||||
import { handleAuthCommand } from "./commands/auth.js";
|
import { handleAuthCommand } from "./commands/auth.js";
|
||||||
import { handleCorpsCommand } from "./commands/corps.js";
|
import { handleCorpsCommand } from "./commands/corps.js";
|
||||||
@@ -13,9 +13,70 @@ import { handleMcpCommand } from "./commands/mcp.js";
|
|||||||
import { handleUpdateCommand } from "./commands/update.js";
|
import { handleUpdateCommand } from "./commands/update.js";
|
||||||
import { handleOpenApiCommand } from "./commands/openapi.js";
|
import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||||
import { handleBillCommand } from "./commands/bill.js";
|
import { handleBillCommand } from "./commands/bill.js";
|
||||||
|
import { handleServiceCommand } from "./commands/service.js";
|
||||||
|
import { handleHttpCommand } from "./commands/http.js";
|
||||||
import type { CliResult, CliRunOptions } from "./types.js";
|
import type { CliResult, CliRunOptions } from "./types.js";
|
||||||
|
|
||||||
export async function runCli(
|
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||||
|
|
||||||
|
function isStandingCommand(args: string[]): boolean {
|
||||||
|
if (!args.length) return false;
|
||||||
|
const first = args[0]?.toLowerCase();
|
||||||
|
const second = args[1]?.toLowerCase();
|
||||||
|
if (STANDING_COMMANDS.has(first)) return true;
|
||||||
|
if ((first === "service" || first === "daemon") && second === "run") return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let runQueue = Promise.resolve<any>(undefined);
|
||||||
|
|
||||||
|
export function runCli(
|
||||||
|
rawArgs: string[],
|
||||||
|
options: CliRunOptions = {}
|
||||||
|
): Promise<CliResult> {
|
||||||
|
if (isStandingCommand(rawArgs)) {
|
||||||
|
return dispatchCli(rawArgs, options);
|
||||||
|
}
|
||||||
|
const run = runQueue.then(() => runCliOnce(rawArgs, options));
|
||||||
|
runQueue = run.then(
|
||||||
|
() => undefined,
|
||||||
|
() => undefined
|
||||||
|
);
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runCliOnce(
|
||||||
|
rawArgs: string[],
|
||||||
|
options: CliRunOptions = {}
|
||||||
|
): Promise<CliResult> {
|
||||||
|
const stdoutChunks: string[] = [];
|
||||||
|
const stderrChunks: string[] = [];
|
||||||
|
const originalLog = console.log;
|
||||||
|
const originalError = console.error;
|
||||||
|
|
||||||
|
console.log = (...values: unknown[]) => {
|
||||||
|
stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
|
||||||
|
};
|
||||||
|
console.error = (...values: unknown[]) => {
|
||||||
|
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await dispatchCli(rawArgs, options);
|
||||||
|
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
|
||||||
|
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
|
||||||
|
return {
|
||||||
|
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
|
||||||
|
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
|
||||||
|
exitCode: result.exitCode,
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
console.log = originalLog;
|
||||||
|
console.error = originalError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dispatchCli(
|
||||||
rawArgs: string[],
|
rawArgs: string[],
|
||||||
options: CliRunOptions = {}
|
options: CliRunOptions = {}
|
||||||
): Promise<CliResult> {
|
): Promise<CliResult> {
|
||||||
@@ -33,12 +94,17 @@ export async function runCli(
|
|||||||
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
||||||
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
||||||
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
||||||
|
const outputOpts = outputOptions(parsed.options);
|
||||||
|
|
||||||
const runtime = initCorpRuntime({
|
const runtime = initCorpRuntime({
|
||||||
corpId: corpIdOption,
|
corpId: corpIdOption,
|
||||||
stateless: statelessOption,
|
stateless: statelessOption,
|
||||||
stateful: statefulOption,
|
stateful: statefulOption,
|
||||||
jsonMode,
|
jsonMode,
|
||||||
|
outputOptions: outputOpts,
|
||||||
|
appRoot: options.appRoot,
|
||||||
|
entryFile: options.entryFile,
|
||||||
|
launcher: options.launcher,
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -83,8 +149,14 @@ export async function runCli(
|
|||||||
case "schema":
|
case "schema":
|
||||||
case "spec":
|
case "spec":
|
||||||
return await handleOpenApiCommand(parsed, runtime);
|
return await handleOpenApiCommand(parsed, runtime);
|
||||||
|
case "http":
|
||||||
|
case "server":
|
||||||
|
case "web":
|
||||||
|
return await handleHttpCommand(parsed, runtime);
|
||||||
|
case "service":
|
||||||
|
case "daemon":
|
||||||
|
return await handleServiceCommand(parsed, runtime);
|
||||||
case "mcp":
|
case "mcp":
|
||||||
case "serve":
|
|
||||||
return await handleMcpCommand(parsed, options);
|
return await handleMcpCommand(parsed, options);
|
||||||
case undefined:
|
case undefined:
|
||||||
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
|
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
|
||||||
@@ -96,7 +168,7 @@ export async function runCli(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||||
if (jsonMode) {
|
if (jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({ error: true, message: errorMsg }),
|
stdout: printJson({ error: true, message: errorMsg }),
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import {
|
||||||
|
serviceStatus,
|
||||||
|
getPidFile,
|
||||||
|
getLogFile,
|
||||||
|
isHoseServiceProcess,
|
||||||
|
ServiceConfig,
|
||||||
|
} from "./service.js";
|
||||||
|
|
||||||
|
describe("cli/service - 守护进程状态与自愈管理", () => {
|
||||||
|
let tempDir: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = mkdtempSync(join(tmpdir(), "hose-service-test-"));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
try {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("服务未运行时返回 running: false 并生成规范状态对象", () => {
|
||||||
|
const config: ServiceConfig = {
|
||||||
|
appRoot: tempDir,
|
||||||
|
entryFile: join(tempDir, "entry.js"),
|
||||||
|
stateDir: tempDir,
|
||||||
|
version: "0.5.0",
|
||||||
|
port: 8888,
|
||||||
|
host: "127.0.0.1",
|
||||||
|
};
|
||||||
|
|
||||||
|
const status = serviceStatus(config);
|
||||||
|
expect(status.running).toBe(false);
|
||||||
|
expect(status.pid).toBeUndefined();
|
||||||
|
expect(status.version).toBe("0.5.0");
|
||||||
|
expect(status.port).toBe(8888);
|
||||||
|
expect(status.pidFile).toBe(join(tempDir, "service.pid"));
|
||||||
|
expect(status.logFile).toBe(join(tempDir, "service.log"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("发现失效的孤儿 PID 时自动自愈清理 pidFile", () => {
|
||||||
|
const config: ServiceConfig = {
|
||||||
|
appRoot: tempDir,
|
||||||
|
entryFile: join(tempDir, "entry.js"),
|
||||||
|
stateDir: tempDir,
|
||||||
|
version: "0.5.0",
|
||||||
|
};
|
||||||
|
|
||||||
|
const pidFile = getPidFile(config);
|
||||||
|
// 写入一个不存在的荒谬 PID
|
||||||
|
writeFileSync(pidFile, "9999999\n", "utf-8");
|
||||||
|
expect(existsSync(pidFile)).toBe(true);
|
||||||
|
|
||||||
|
const status = serviceStatus(config);
|
||||||
|
expect(status.running).toBe(false);
|
||||||
|
// 验证旧文件已被自愈删除
|
||||||
|
expect(existsSync(pidFile)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("isHoseServiceProcess 正确识别非 hose 进程", () => {
|
||||||
|
// 当前测试进程自身不是后台 service run 守护进程
|
||||||
|
expect(isHoseServiceProcess(process.pid, "/non/existent/path")).toBe(false);
|
||||||
|
// 不存在的进程
|
||||||
|
expect(isHoseServiceProcess(9999999, tempDir)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("路径辅助函数返回规范的子路径", () => {
|
||||||
|
const config: ServiceConfig = {
|
||||||
|
appRoot: tempDir,
|
||||||
|
entryFile: join(tempDir, "entry.js"),
|
||||||
|
stateDir: tempDir,
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(getPidFile(config)).toBe(join(tempDir, "service.pid"));
|
||||||
|
expect(getLogFile(config)).toBe(join(tempDir, "service.log"));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
import { spawn, execFileSync } from "node:child_process";
|
||||||
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
|
||||||
|
|
||||||
|
export type ServiceConfig = {
|
||||||
|
appRoot: string;
|
||||||
|
entryFile: string;
|
||||||
|
stateDir: string;
|
||||||
|
version?: string;
|
||||||
|
launcher?: {
|
||||||
|
command: string;
|
||||||
|
args?: string[];
|
||||||
|
};
|
||||||
|
port?: number;
|
||||||
|
host?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function runServiceCommand(
|
||||||
|
action: string | undefined,
|
||||||
|
config: ServiceConfig,
|
||||||
|
options: { quiet?: boolean } = {}
|
||||||
|
) {
|
||||||
|
switch (action) {
|
||||||
|
case "run":
|
||||||
|
await runService(config);
|
||||||
|
return undefined;
|
||||||
|
case "start":
|
||||||
|
return startService(config);
|
||||||
|
case "stop":
|
||||||
|
return stopService(config, options);
|
||||||
|
case "restart":
|
||||||
|
stopService(config, { quiet: true });
|
||||||
|
return startService(config);
|
||||||
|
case "logs":
|
||||||
|
case "log":
|
||||||
|
return readServiceLogs(config);
|
||||||
|
case "status":
|
||||||
|
case undefined:
|
||||||
|
return serviceStatus(config);
|
||||||
|
default:
|
||||||
|
throw new Error("用法: hose service <start|stop|restart|status|logs>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serviceStatus(config: ServiceConfig) {
|
||||||
|
const pidFile = getPidFile(config);
|
||||||
|
const pid = readServicePid(pidFile);
|
||||||
|
const running = pid ? isHoseServiceProcess(pid, config.appRoot) : false;
|
||||||
|
|
||||||
|
if (pid && !running) {
|
||||||
|
rmSync(pidFile, { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||||
|
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||||
|
|
||||||
|
return {
|
||||||
|
running,
|
||||||
|
pid: running ? pid : undefined,
|
||||||
|
version: config.version,
|
||||||
|
port,
|
||||||
|
host,
|
||||||
|
url: running ? `http://${host}:${port}` : undefined,
|
||||||
|
appRoot: config.appRoot,
|
||||||
|
stateDir: config.stateDir,
|
||||||
|
pidFile,
|
||||||
|
logFile: getLogFile(config),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runService(config: ServiceConfig) {
|
||||||
|
const pidFile = getPidFile(config);
|
||||||
|
const logFile = getLogFile(config);
|
||||||
|
ensureStateDir(config.stateDir);
|
||||||
|
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
|
||||||
|
|
||||||
|
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||||
|
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||||
|
|
||||||
|
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
|
||||||
|
|
||||||
|
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
|
||||||
|
try {
|
||||||
|
server = await startHttpServer({ port, host, silent: true });
|
||||||
|
appendLog(logFile, `service listening pid=${process.pid}`);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
if (readServicePid(pidFile) === process.pid) {
|
||||||
|
rmSync(pidFile, { force: true });
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
if (server) {
|
||||||
|
server.close();
|
||||||
|
server = null;
|
||||||
|
}
|
||||||
|
if (readServicePid(pidFile) === process.pid) {
|
||||||
|
rmSync(pidFile, { force: true });
|
||||||
|
}
|
||||||
|
appendLog(logFile, `service stopped pid=${process.pid}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
let stopped = false;
|
||||||
|
const stop = () => {
|
||||||
|
if (stopped) return;
|
||||||
|
stopped = true;
|
||||||
|
cleanup();
|
||||||
|
process.off("SIGTERM", stop);
|
||||||
|
process.off("SIGINT", stop);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
process.once("SIGTERM", stop);
|
||||||
|
process.once("SIGINT", stop);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function startService(config: ServiceConfig) {
|
||||||
|
ensureStateDir(config.stateDir);
|
||||||
|
const current = serviceStatus(config);
|
||||||
|
if (current.running) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
|
||||||
|
const serviceArgs = [...(launcher.args ?? []), "service", "run"];
|
||||||
|
if (config.port) serviceArgs.push(`--port=${config.port}`);
|
||||||
|
if (config.host) serviceArgs.push(`--host=${config.host}`);
|
||||||
|
|
||||||
|
const child = spawn(launcher.command, serviceArgs, {
|
||||||
|
cwd: config.appRoot,
|
||||||
|
detached: true,
|
||||||
|
stdio: ["ignore", "ignore", "ignore"],
|
||||||
|
env: process.env,
|
||||||
|
});
|
||||||
|
child.unref();
|
||||||
|
|
||||||
|
const pidFile = getPidFile(config);
|
||||||
|
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
|
||||||
|
appendLog(getLogFile(config), `service started pid=${child.pid}`);
|
||||||
|
return { started: true, ...serviceStatus(config) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
|
||||||
|
const pidFile = getPidFile(config);
|
||||||
|
const pid = readServicePid(pidFile);
|
||||||
|
if (!pid || !isHoseServiceProcess(pid, config.appRoot)) {
|
||||||
|
rmSync(pidFile, { force: true });
|
||||||
|
return options.quiet ? undefined : { stopped: false, reason: "服务未处于运行状态" };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
process.kill(pid, "SIGTERM");
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
rmSync(pidFile, { force: true });
|
||||||
|
appendLog(getLogFile(config), `service stop requested pid=${pid}`);
|
||||||
|
return options.quiet ? undefined : { stopped: true, pid };
|
||||||
|
}
|
||||||
|
|
||||||
|
function readServiceLogs(config: ServiceConfig, maxLines = 50) {
|
||||||
|
const logFile = getLogFile(config);
|
||||||
|
if (!existsSync(logFile)) {
|
||||||
|
return { logFile, lines: [], content: "暂无服务运行日志" };
|
||||||
|
}
|
||||||
|
const content = readFileSync(logFile, "utf-8");
|
||||||
|
const lines = content.trim().split("\n").filter(Boolean).slice(-maxLines);
|
||||||
|
return {
|
||||||
|
logFile,
|
||||||
|
lines,
|
||||||
|
content: lines.join("\n"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isHoseServiceProcess(pid: number, appRoot: string): boolean {
|
||||||
|
if (!isProcessRunning(pid)) return false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
||||||
|
const matchesTarget =
|
||||||
|
command.includes(appRoot) ||
|
||||||
|
command.includes("hose-use") ||
|
||||||
|
command.includes("src/cli.ts");
|
||||||
|
return matchesTarget && command.includes("service") && command.includes("run");
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isProcessRunning(pid: number): boolean {
|
||||||
|
try {
|
||||||
|
process.kill(pid, 0);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPidFile(config: ServiceConfig): string {
|
||||||
|
return join(config.stateDir, "service.pid");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLogFile(config: ServiceConfig): string {
|
||||||
|
return join(config.stateDir, "service.log");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readServicePid(path: string): number | undefined {
|
||||||
|
if (!existsSync(path)) return undefined;
|
||||||
|
const pid = Number(readFileSync(path, "utf-8").trim());
|
||||||
|
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureStateDir(stateDir: string): void {
|
||||||
|
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendLog(path: string, message: string): void {
|
||||||
|
writeFileSync(path, `${new Date().toISOString()} ${message}\n`, { flag: "a", mode: 0o600 });
|
||||||
|
}
|
||||||
+17
-1
@@ -12,7 +12,10 @@ export interface CliParsedArgs {
|
|||||||
export interface CliRunOptions {
|
export interface CliRunOptions {
|
||||||
appRoot?: string;
|
appRoot?: string;
|
||||||
entryFile?: string;
|
entryFile?: string;
|
||||||
launcher?: string;
|
launcher?: {
|
||||||
|
command: string;
|
||||||
|
args?: string[];
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CliResult {
|
export interface CliResult {
|
||||||
@@ -21,8 +24,21 @@ export interface CliResult {
|
|||||||
exitCode: number;
|
exitCode: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface OutputOptions {
|
||||||
|
allowFull?: boolean;
|
||||||
|
outputFile?: string;
|
||||||
|
summary?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CliRuntime {
|
export interface CliRuntime {
|
||||||
corpContext: CorpContext;
|
corpContext: CorpContext;
|
||||||
selectedCorp: CorpConfig | null;
|
selectedCorp: CorpConfig | null;
|
||||||
jsonMode: boolean;
|
jsonMode: boolean;
|
||||||
|
outputOptions?: OutputOptions;
|
||||||
|
appRoot?: string;
|
||||||
|
entryFile?: string;
|
||||||
|
launcher?: {
|
||||||
|
command: string;
|
||||||
|
args?: string[];
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+148
-7
@@ -263,13 +263,35 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 3. 从 URL 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx)
|
||||||
|
if (!result.corpId) {
|
||||||
|
const urlCorpMatch = /(?:[?&]corpId=)([^&'"\s]+)/i.exec(rawInput);
|
||||||
|
if (urlCorpMatch) {
|
||||||
|
result.corpId = decodeURIComponent(urlCorpMatch[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 从 Cookie (-b / Cookie header) 中提取 ekb-access-token 或 corpId
|
||||||
|
if (!result.accessToken) {
|
||||||
|
const cookieTokenMatch = /ekb-access-token=([^;'"\s]+)/i.exec(rawInput);
|
||||||
|
if (cookieTokenMatch) {
|
||||||
|
result.accessToken = decodeURIComponent(cookieTokenMatch[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!result.corpId) {
|
||||||
|
const cookieCorpMatch = /(?:^|;\s*)corpId=([^;'"\s]+)/i.exec(rawInput);
|
||||||
|
if (cookieCorpMatch) {
|
||||||
|
result.corpId = decodeURIComponent(cookieCorpMatch[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 校验并导入单个 F12 抓包/手动凭证,保存到企业配置
|
* 校验并导入单个抓包/手动凭证,自动探测官方 Session 平台类型并保存到企业配置
|
||||||
*/
|
*/
|
||||||
export async function importF12Credentials(
|
export async function importCredentials(
|
||||||
params: F12ImportParams
|
params: F12ImportParams
|
||||||
): Promise<CorpConfig> {
|
): Promise<CorpConfig> {
|
||||||
const { accessToken, corpId, staffId } = params;
|
const { accessToken, corpId, staffId } = params;
|
||||||
@@ -279,8 +301,25 @@ export async function importF12Credentials(
|
|||||||
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
|
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证凭证有效性并尝试自动获取企业名称
|
// 1. 验证凭证有效性并提取官方服务端 Session 元数据
|
||||||
let corpName = params.name;
|
let sessionData: {
|
||||||
|
id?: string;
|
||||||
|
userId?: string;
|
||||||
|
loginStaffId?: string;
|
||||||
|
corporationId?: string;
|
||||||
|
platform?: string;
|
||||||
|
isAssistPlatform?: boolean;
|
||||||
|
isShortTermToken?: boolean;
|
||||||
|
assistId?: string;
|
||||||
|
operationUserId?: string;
|
||||||
|
operationUserName?: string;
|
||||||
|
privilege?: string;
|
||||||
|
deviceType?: string;
|
||||||
|
loginAccountType?: string;
|
||||||
|
loginTime?: number;
|
||||||
|
expTime?: number;
|
||||||
|
} | undefined;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await ky
|
const res = await ky
|
||||||
.get(`${baseUrl}/api/account/v2/session`, {
|
.get(`${baseUrl}/api/account/v2/session`, {
|
||||||
@@ -290,20 +329,102 @@ export async function importF12Credentials(
|
|||||||
staffid: staffId,
|
staffid: staffId,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.json<{ value?: { corporationId?: string; loginStaffId?: string; expTime?: number } }>();
|
.json<{
|
||||||
|
value?: {
|
||||||
|
id?: string;
|
||||||
|
userId?: string;
|
||||||
|
loginStaffId?: string;
|
||||||
|
corporationId?: string;
|
||||||
|
platform?: string;
|
||||||
|
isAssistPlatform?: boolean;
|
||||||
|
isShortTermToken?: boolean;
|
||||||
|
assistId?: string;
|
||||||
|
operationUserId?: string;
|
||||||
|
operationUserName?: string;
|
||||||
|
privilege?: string;
|
||||||
|
deviceType?: string;
|
||||||
|
loginAccountType?: string;
|
||||||
|
loginTime?: number;
|
||||||
|
expTime?: number;
|
||||||
|
};
|
||||||
|
}>();
|
||||||
|
|
||||||
if (!res.value?.corporationId) {
|
sessionData = res.value;
|
||||||
|
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
|
||||||
throw new Error("服务端未返回有效 Session");
|
throw new Error("服务端未返回有效 Session");
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
|
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2. 尝试通过 $UNITY JWT 获取真实企业名称与员工详细信息 (如果未手动指定)
|
||||||
|
let corpName = params.name;
|
||||||
|
let staffName = sessionData?.privilege;
|
||||||
|
let cellphone: string | undefined;
|
||||||
|
let isAdmin: boolean | undefined;
|
||||||
|
let sourceChannel: string | undefined;
|
||||||
|
let jwtExpMs: number | undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const jwtRes = await ky
|
||||||
|
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||||
|
searchParams: { corpId },
|
||||||
|
headers: {
|
||||||
|
accesstoken: accessToken,
|
||||||
|
corpid: corpId,
|
||||||
|
staffid: staffId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.json<{ id?: string; value?: string }>();
|
||||||
|
const token = jwtRes.id || jwtRes.value;
|
||||||
|
if (token) {
|
||||||
|
const parts = token.split(".");
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
|
||||||
|
if (!corpName && payload.corporationName) {
|
||||||
|
corpName = payload.corporationName;
|
||||||
|
}
|
||||||
|
if (payload.staffName) {
|
||||||
|
staffName = payload.staffName;
|
||||||
|
}
|
||||||
|
if (payload.cellphone) {
|
||||||
|
cellphone = payload.cellphone;
|
||||||
|
}
|
||||||
|
if (payload.isAdmin !== undefined) {
|
||||||
|
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
|
||||||
|
}
|
||||||
|
if (payload.exp) {
|
||||||
|
jwtExpMs = Number(payload.exp) * 1000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略尝试获取企业名失败
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 智能判断语义化凭证来源
|
||||||
|
let source: import("../config/types.js").CredentialSource = "curl";
|
||||||
|
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
|
||||||
|
source = "assist";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 计算 Token 过期时间戳 (ms)
|
||||||
|
let expiresAt: number | undefined;
|
||||||
|
if (sessionData?.expTime && sessionData.expTime > 0) {
|
||||||
|
expiresAt = sessionData.expTime;
|
||||||
|
} else if (jwtExpMs && jwtExpMs > 0) {
|
||||||
|
expiresAt = jwtExpMs;
|
||||||
|
} else if (sessionData?.isAssistPlatform && sessionData?.loginTime) {
|
||||||
|
// 协助平台短期调试 Token 通常 2 小时有效
|
||||||
|
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
const corpConfig: CorpConfig = {
|
const corpConfig: CorpConfig = {
|
||||||
id: corpId,
|
id: corpId,
|
||||||
name: corpName || `企业-${corpId}`,
|
name: corpName || `企业-${corpId}`,
|
||||||
baseUrl,
|
baseUrl,
|
||||||
source: "f12",
|
source,
|
||||||
|
staffName,
|
||||||
credentials: {
|
credentials: {
|
||||||
accessToken,
|
accessToken,
|
||||||
corpId,
|
corpId,
|
||||||
@@ -311,6 +432,23 @@ export async function importF12Credentials(
|
|||||||
},
|
},
|
||||||
auth: {
|
auth: {
|
||||||
refreshTtl: 300,
|
refreshTtl: 300,
|
||||||
|
expiresAt,
|
||||||
|
},
|
||||||
|
session: {
|
||||||
|
platform: sessionData?.platform,
|
||||||
|
isAssistPlatform: sessionData?.isAssistPlatform,
|
||||||
|
isShortTermToken: sessionData?.isShortTermToken,
|
||||||
|
assistId: sessionData?.assistId,
|
||||||
|
operationUserId: sessionData?.operationUserId,
|
||||||
|
operationUserName: sessionData?.operationUserName,
|
||||||
|
staffName,
|
||||||
|
cellphone,
|
||||||
|
isAdmin,
|
||||||
|
deviceType: sessionData?.deviceType,
|
||||||
|
loginAccountType: sessionData?.loginAccountType,
|
||||||
|
loginTime: sessionData?.loginTime,
|
||||||
|
expTime: expiresAt || sessionData?.expTime,
|
||||||
|
sourceChannel,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -318,6 +456,9 @@ export async function importF12Credentials(
|
|||||||
return corpConfig;
|
return corpConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 保持历史命名兼容
|
||||||
|
export const importF12Credentials = importCredentials;
|
||||||
|
|
||||||
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
|
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import {
|
||||||
|
loadCorpConfigs,
|
||||||
|
saveCorpConfig,
|
||||||
|
resolveEnterprisesDirs,
|
||||||
|
resolveWritableEnterprisesDir,
|
||||||
|
loadGlobalConfig,
|
||||||
|
saveGlobalConfig,
|
||||||
|
resolveGlobalConfigFile,
|
||||||
|
} from "./loader.js";
|
||||||
|
import type { CorpConfig } from "./types.js";
|
||||||
|
|
||||||
|
describe("core/config/loader", () => {
|
||||||
|
let tempDir: string;
|
||||||
|
const originalEnv = { ...process.env };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = mkdtempSync(join(tmpdir(), "hose-config-test-"));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.env = { ...originalEnv };
|
||||||
|
try {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveEnterprisesDirs prioritizes HOSE_ENTERPRISES_DIR environment variable", () => {
|
||||||
|
const customDir = join(tempDir, "custom-enterprises");
|
||||||
|
mkdirSync(customDir, { recursive: true });
|
||||||
|
process.env.HOSE_ENTERPRISES_DIR = customDir;
|
||||||
|
|
||||||
|
const dirs = resolveEnterprisesDirs();
|
||||||
|
expect(dirs).toEqual([customDir]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveWritableEnterprisesDir respects HOSE_ENTERPRISES_DIR", () => {
|
||||||
|
const customDir = join(tempDir, "writable-enterprises");
|
||||||
|
mkdirSync(customDir, { recursive: true });
|
||||||
|
process.env.HOSE_ENTERPRISES_DIR = customDir;
|
||||||
|
|
||||||
|
expect(resolveWritableEnterprisesDir()).toBe(customDir);
|
||||||
|
});
|
||||||
|
|
||||||
|
const createMockCorp = (id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
baseUrl: "https://app.ekuaibao.com",
|
||||||
|
source: "manual",
|
||||||
|
credentials: {
|
||||||
|
accessToken: `token-${id}`,
|
||||||
|
corpId: id,
|
||||||
|
staffId: `staff-${id}`,
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("loadCorpConfigs loads valid configs and skips example files", () => {
|
||||||
|
const dirA = join(tempDir, "dirA");
|
||||||
|
mkdirSync(dirA, { recursive: true });
|
||||||
|
|
||||||
|
const validCorp = createMockCorp("corp-1", "企业1");
|
||||||
|
|
||||||
|
// Save valid corp
|
||||||
|
writeFileSync(join(dirA, "corp-1.json"), JSON.stringify(validCorp));
|
||||||
|
// Save example corp
|
||||||
|
writeFileSync(
|
||||||
|
join(dirA, "example.json"),
|
||||||
|
JSON.stringify(createMockCorp("example-corp", "模板企业"))
|
||||||
|
);
|
||||||
|
|
||||||
|
const loaded = loadCorpConfigs([dirA]);
|
||||||
|
expect(loaded).toHaveLength(1);
|
||||||
|
expect(loaded[0]?.id).toBe("corp-1");
|
||||||
|
expect(loaded[0]?.name).toBe("企业1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("loadCorpConfigs merges multiple directories with earlier directory taking precedence", () => {
|
||||||
|
const dirA = join(tempDir, "dirA");
|
||||||
|
const dirB = join(tempDir, "dirB");
|
||||||
|
mkdirSync(dirA, { recursive: true });
|
||||||
|
mkdirSync(dirB, { recursive: true });
|
||||||
|
|
||||||
|
const corpInA = createMockCorp("corp-common", "本地优先企业", {
|
||||||
|
credentials: { accessToken: "token-a", corpId: "corp-common", staffId: "staff-a" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const corpInB = createMockCorp("corp-common", "全局覆盖企业", {
|
||||||
|
credentials: { accessToken: "token-b", corpId: "corp-common", staffId: "staff-b" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const corpOnlyB = createMockCorp("corp-b-only", "仅在B的企业", {
|
||||||
|
credentials: { accessToken: "token-b2", corpId: "corp-b-only", staffId: "staff-b2" },
|
||||||
|
});
|
||||||
|
|
||||||
|
writeFileSync(join(dirA, "corp-common.json"), JSON.stringify(corpInA));
|
||||||
|
writeFileSync(join(dirB, "corp-common.json"), JSON.stringify(corpInB));
|
||||||
|
writeFileSync(join(dirB, "corp-b-only.json"), JSON.stringify(corpOnlyB));
|
||||||
|
|
||||||
|
const loaded = loadCorpConfigs([dirA, dirB]);
|
||||||
|
expect(loaded).toHaveLength(2);
|
||||||
|
|
||||||
|
const common = loaded.find((c) => c.id === "corp-common");
|
||||||
|
expect(common?.name).toBe("本地优先企业");
|
||||||
|
|
||||||
|
const bOnly = loaded.find((c) => c.id === "corp-b-only");
|
||||||
|
expect(bOnly?.name).toBe("仅在B的企业");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("saveCorpConfig writes validated JSON to target directory", () => {
|
||||||
|
const targetDir = join(tempDir, "save-target");
|
||||||
|
const corp = createMockCorp("corp-save-test", "保存测试企业", {
|
||||||
|
credentials: { accessToken: "tok-123", corpId: "corp-save-test", staffId: "stf-1" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const filePath = saveCorpConfig(corp, targetDir);
|
||||||
|
expect(existsSync(filePath)).toBe(true);
|
||||||
|
|
||||||
|
const saved = JSON.parse(readFileSync(filePath, "utf-8"));
|
||||||
|
expect(saved.id).toBe("corp-save-test");
|
||||||
|
expect(saved.credentials.accessToken).toBe("tok-123");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("loadGlobalConfig and saveGlobalConfig respect HOSE_CONFIG_FILE", () => {
|
||||||
|
const customConfigFile = join(tempDir, "config.json");
|
||||||
|
process.env.HOSE_CONFIG_FILE = customConfigFile;
|
||||||
|
|
||||||
|
expect(resolveGlobalConfigFile()).toBe(customConfigFile);
|
||||||
|
|
||||||
|
const initial = loadGlobalConfig();
|
||||||
|
expect(initial.stateful).toBe(true);
|
||||||
|
|
||||||
|
saveGlobalConfig({ stateful: false, defaultCorpId: "test-corp-123" });
|
||||||
|
const updated = loadGlobalConfig();
|
||||||
|
expect(updated.stateful).toBe(false);
|
||||||
|
expect(updated.defaultCorpId).toBe("test-corp-123");
|
||||||
|
});
|
||||||
|
});
|
||||||
+114
-37
@@ -1,30 +1,96 @@
|
|||||||
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs";
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||||
import { join, dirname } from "path";
|
import { homedir } from "node:os";
|
||||||
import { homedir } from "os";
|
import { dirname, join } from "node:path";
|
||||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||||
|
|
||||||
const ENTERPRISES_DIR = "./enterprises";
|
const ENTERPRISES_DIR = "enterprises";
|
||||||
const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
||||||
|
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||||
|
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
|
||||||
|
|
||||||
|
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
|
||||||
|
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
|
||||||
|
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
|
||||||
|
|
||||||
|
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
|
||||||
|
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
||||||
|
|
||||||
function ensureDir(dir: string): void {
|
function ensureDir(dir: string): void {
|
||||||
mkdirSync(dir, { recursive: true });
|
mkdirSync(dir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function resolveEnterprisesDirs(): string[] {
|
||||||
|
const configured = process.env[CONFIG_ENV]?.trim();
|
||||||
|
if (configured) {
|
||||||
|
return existsSync(configured) ? [configured] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||||
|
if (configuredUserDir) {
|
||||||
|
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||||
|
const uniqueExisting: string[] = [];
|
||||||
|
for (const d of dirs) {
|
||||||
|
if (existsSync(d) && !uniqueExisting.includes(d)) {
|
||||||
|
uniqueExisting.push(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return uniqueExisting;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePrimaryEnterprisesDir(): string | undefined {
|
||||||
|
const configured = process.env[CONFIG_ENV]?.trim();
|
||||||
|
if (configured) return existsSync(configured) ? configured : undefined;
|
||||||
|
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||||
|
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
|
||||||
|
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWritableEnterprisesDir(): string {
|
||||||
|
const configured = process.env[CONFIG_ENV]?.trim();
|
||||||
|
if (configured) return configured;
|
||||||
|
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||||
|
if (configuredUserDir) return configuredUserDir;
|
||||||
|
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||||
|
return PRIMARY_USER_ENTERPRISES_DIR;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getEnterprisesDirCandidates(): string[] {
|
||||||
|
return [
|
||||||
|
`${CONFIG_ENV}=<path>`,
|
||||||
|
ENTERPRISES_DIR,
|
||||||
|
PRIMARY_USER_ENTERPRISES_DIR,
|
||||||
|
LEGACY_USER_ENTERPRISES_DIR,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
export function resolveGlobalConfigFile(): string {
|
export function resolveGlobalConfigFile(): string {
|
||||||
return GLOBAL_CONFIG_PATH;
|
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||||
|
if (configured) return configured;
|
||||||
|
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||||
|
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
|
||||||
|
return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadGlobalConfig(): GlobalConfig {
|
export function loadGlobalConfig(): GlobalConfig {
|
||||||
|
const file = resolveGlobalConfigFile();
|
||||||
try {
|
try {
|
||||||
const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
|
if (existsSync(file)) {
|
||||||
return GlobalConfigSchema.parse(JSON.parse(content));
|
const content = readFileSync(file, "utf-8");
|
||||||
|
return GlobalConfigSchema.parse(JSON.parse(content));
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
return {
|
// 容错返回默认
|
||||||
stateful: true,
|
|
||||||
defaultCorpId: undefined,
|
|
||||||
defaultAccountId: undefined,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
stateful: true,
|
||||||
|
defaultCorpId: undefined,
|
||||||
|
defaultAccountId: undefined,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||||
@@ -33,50 +99,61 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
|||||||
...current,
|
...current,
|
||||||
...config,
|
...config,
|
||||||
});
|
});
|
||||||
ensureDir(dirname(GLOBAL_CONFIG_PATH));
|
|
||||||
writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(updated, null, 2), "utf-8");
|
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||||
|
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
|
||||||
|
ensureDir(dirname(targetFile));
|
||||||
|
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] {
|
export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||||
let files: string[];
|
const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs();
|
||||||
try {
|
const byId = new Map<string, CorpConfig>();
|
||||||
ensureDir(dir);
|
|
||||||
files = readdirSync(dir).filter((f) => f.endsWith(".json"));
|
|
||||||
} catch (error) {
|
|
||||||
console.error(
|
|
||||||
`[config] failed to read enterprises directory: ${error instanceof Error ? error.message : String(error)}`
|
|
||||||
);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const configs: CorpConfig[] = [];
|
for (const dir of dirs) {
|
||||||
for (const file of files) {
|
|
||||||
try {
|
try {
|
||||||
const content = readFileSync(join(dir, file), "utf-8");
|
const files = readdirSync(dir)
|
||||||
const parsed = JSON.parse(content);
|
.filter((item) => item.endsWith(".json"))
|
||||||
configs.push(CorpConfigSchema.parse(parsed));
|
.filter((item) => !item.startsWith("example."));
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
const content = readFileSync(join(dir, file), "utf-8");
|
||||||
|
const parsed = JSON.parse(content);
|
||||||
|
const corp = CorpConfigSchema.parse(parsed);
|
||||||
|
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
|
||||||
|
if (!byId.has(corp.id)) {
|
||||||
|
byId.set(corp.id, corp);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
`[config] failed to load ${file} from ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(
|
console.error(
|
||||||
`[config] failed to load ${file}: ${error instanceof Error ? error.message : String(error)}`
|
`[config] failed to read enterprises directory ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return configs;
|
return Array.from(byId.values());
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveCorpConfig(config: CorpConfig, dir: string = ENTERPRISES_DIR): string {
|
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||||
ensureDir(dir);
|
const targetDir = dir || resolveWritableEnterprisesDir();
|
||||||
|
ensureDir(targetDir);
|
||||||
const validated = CorpConfigSchema.parse(config);
|
const validated = CorpConfigSchema.parse(config);
|
||||||
const filePath = join(dir, `${validated.id}.json`);
|
const filePath = join(targetDir, `${validated.id}.json`);
|
||||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveMultipleCorpConfigs(
|
export function saveMultipleCorpConfigs(
|
||||||
configs: CorpConfig[],
|
configs: CorpConfig[],
|
||||||
dir: string = ENTERPRISES_DIR
|
dir?: string
|
||||||
): string[] {
|
): string[] {
|
||||||
return configs.map((config) => saveCorpConfig(config, dir));
|
return configs.map((config) => saveCorpConfig(config, dir));
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,7 @@ export interface CorpSummary {
|
|||||||
staffId: string;
|
staffId: string;
|
||||||
baseUrl?: string;
|
baseUrl?: string;
|
||||||
current: boolean;
|
current: boolean;
|
||||||
|
expiresAt?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveCorpConfig(
|
export function resolveCorpConfig(
|
||||||
@@ -17,7 +18,8 @@ export function resolveCorpConfig(
|
|||||||
stateful: boolean;
|
stateful: boolean;
|
||||||
defaultCorpId?: string;
|
defaultCorpId?: string;
|
||||||
corpId?: string;
|
corpId?: string;
|
||||||
}
|
},
|
||||||
|
candidateDirs?: string[]
|
||||||
): CorpConfig {
|
): CorpConfig {
|
||||||
const requestedCorpId = options.corpId?.trim() || undefined;
|
const requestedCorpId = options.corpId?.trim() || undefined;
|
||||||
const configuredCorpId = options.stateful
|
const configuredCorpId = options.stateful
|
||||||
@@ -50,7 +52,8 @@ export function resolveCorpConfig(
|
|||||||
const firstCorp = corps[0];
|
const firstCorp = corps[0];
|
||||||
if (firstCorp) return firstCorp;
|
if (firstCorp) return firstCorp;
|
||||||
|
|
||||||
throw new Error("未找到任何企业配置。请先运行 `hose auth login` 或在 enterprises/ 目录下添加配置。");
|
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
|
||||||
|
throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CorpContext {
|
export class CorpContext {
|
||||||
@@ -109,12 +112,16 @@ export class CorpContext {
|
|||||||
return this.corps.get(corpId);
|
return this.corps.get(corpId);
|
||||||
}
|
}
|
||||||
|
|
||||||
resolve(corpId?: string): CorpConfig {
|
resolve(corpId?: string, candidateDirs?: string[]): CorpConfig {
|
||||||
return resolveCorpConfig(Array.from(this.corps.values()), {
|
return resolveCorpConfig(
|
||||||
stateful: this.stateful,
|
Array.from(this.corps.values()),
|
||||||
defaultCorpId: this.defaultCorpId,
|
{
|
||||||
corpId,
|
stateful: this.stateful,
|
||||||
});
|
defaultCorpId: this.defaultCorpId,
|
||||||
|
corpId,
|
||||||
|
},
|
||||||
|
candidateDirs
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
|
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
|
||||||
@@ -145,6 +152,7 @@ export class CorpContext {
|
|||||||
staffId: corp.credentials.staffId,
|
staffId: corp.credentials.staffId,
|
||||||
baseUrl: corp.baseUrl,
|
baseUrl: corp.baseUrl,
|
||||||
current: corp.id === this.current?.id,
|
current: corp.id === this.current?.id,
|
||||||
|
expiresAt: corp.auth?.expiresAt || corp.session?.expTime,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,13 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
export const CredentialSourceSchema = z.enum(["account", "manual", "browser", "f12"]);
|
export const CredentialSourceSchema = z.enum([
|
||||||
|
"account", // 官方统一认证中心 (IDP) 账密/短信登录
|
||||||
|
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
|
||||||
|
"browser", // 浏览器会话 / Cookie 同步
|
||||||
|
"manual", // 手动配置
|
||||||
|
"curl", // cURL 抓包 / HTTP Headers 导入
|
||||||
|
"f12", // 兼容旧版抓包标识
|
||||||
|
]);
|
||||||
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
|
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
|
||||||
|
|
||||||
export const CorpCredentialsSchema = z.object({
|
export const CorpCredentialsSchema = z.object({
|
||||||
@@ -15,17 +22,37 @@ export const CorpAuthConfigSchema = z.object({
|
|||||||
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
|
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const CorpSessionInfoSchema = z.object({
|
||||||
|
platform: z.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
|
||||||
|
isAssistPlatform: z.boolean().optional().describe("是否为官方协助/代客平台登录"),
|
||||||
|
isShortTermToken: z.boolean().optional().describe("是否为短期临时 Token"),
|
||||||
|
assistId: z.string().optional().describe("协助会话/工单 ID"),
|
||||||
|
operationUserId: z.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
|
||||||
|
operationUserName: z.string().optional().describe("协助操作人姓名"),
|
||||||
|
staffName: z.string().optional().describe("当前员工真实姓名"),
|
||||||
|
cellphone: z.string().optional().describe("绑定手机号"),
|
||||||
|
isAdmin: z.boolean().optional().describe("是否管理员"),
|
||||||
|
deviceType: z.string().optional().describe("设备类型"),
|
||||||
|
loginAccountType: z.string().optional().describe("登录账号类型"),
|
||||||
|
loginTime: z.number().optional().describe("登录时间戳 (ms)"),
|
||||||
|
expTime: z.number().optional().describe("过期时间戳 (ms)"),
|
||||||
|
sourceChannel: z.string().optional().describe("来源渠道 (如 APP, WEB)"),
|
||||||
|
});
|
||||||
|
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
|
||||||
|
|
||||||
export const CorpConfigSchema = z.object({
|
export const CorpConfigSchema = z.object({
|
||||||
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
|
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
|
||||||
name: z.string().describe("企业名称"),
|
name: z.string().describe("企业名称"),
|
||||||
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
|
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
|
||||||
userId: z.string().optional().describe("所属用户 ID"),
|
userId: z.string().optional().describe("所属用户 ID"),
|
||||||
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
|
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
|
||||||
|
staffName: z.string().optional().describe("员工真实姓名"),
|
||||||
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
|
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
|
||||||
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/manual/browser/f12"),
|
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),
|
||||||
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
|
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
|
||||||
credentials: CorpCredentialsSchema,
|
credentials: CorpCredentialsSchema,
|
||||||
auth: CorpAuthConfigSchema.optional(),
|
auth: CorpAuthConfigSchema.optional(),
|
||||||
|
session: CorpSessionInfoSchema.optional().describe("官方服务端 Session 与操作人元数据"),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
||||||
|
|||||||
@@ -11,6 +11,53 @@ import {
|
|||||||
import { CorpContext } from "../../core/config/manager.js";
|
import { CorpContext } from "../../core/config/manager.js";
|
||||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||||
|
|
||||||
|
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
const COMMON_FIELD_LABELS: Record<string, string> = {
|
||||||
|
code: "单据编号",
|
||||||
|
name: "单据名称",
|
||||||
|
stage: "业务阶段",
|
||||||
|
state: "审批状态",
|
||||||
|
title: "单据标题",
|
||||||
|
amount: "单据金额",
|
||||||
|
expenseMoney: "报销金额",
|
||||||
|
payMoney: "支付金额",
|
||||||
|
apportionMoney: "分摊金额",
|
||||||
|
submitDate: "提交时间",
|
||||||
|
submitterId: "提交人ID",
|
||||||
|
ownerId: "归属人ID",
|
||||||
|
description: "事由说明",
|
||||||
|
detailType: "明细类型",
|
||||||
|
entityType: "实体类型",
|
||||||
|
settleStatus: "结算状态",
|
||||||
|
settleTime: "结算时间",
|
||||||
|
billingStatus: "开票状态",
|
||||||
|
voucherStatus: "凭证状态",
|
||||||
|
voucherCreateTime: "凭证生成时间",
|
||||||
|
writtenOffAmount: "已核销金额",
|
||||||
|
unwrittenOffAmount: "未核销金额",
|
||||||
|
linkType: "关联类型",
|
||||||
|
linkId: "关联审批流ID",
|
||||||
|
detailId: "明细ID",
|
||||||
|
detailNo: "明细序号",
|
||||||
|
feeTypeId: "费用类型ID",
|
||||||
|
attachments: "附件列表",
|
||||||
|
invoiceForm: "发票表单",
|
||||||
|
submitCount: "提交次数",
|
||||||
|
rejectionNum: "驳回次数",
|
||||||
|
reviewStatus: "审核状态",
|
||||||
|
preApprovedNodeName: "上一审批节点",
|
||||||
|
preNodeApprovedTime: "节点审批通过时间",
|
||||||
|
accountPropertyMoney: "核算属性金额",
|
||||||
|
accountPropertyDate: "核算属性日期",
|
||||||
|
flowSpecificationId: "流程规范ID",
|
||||||
|
feeDetailSpecificationId: "费用明细规范ID",
|
||||||
|
printState: "打印状态",
|
||||||
|
printCount: "打印次数",
|
||||||
|
onlyOwnerPrint: "仅提交人可打印",
|
||||||
|
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
|
||||||
|
};
|
||||||
|
|
||||||
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
|
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
|
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
|
||||||
@@ -88,10 +135,8 @@ export function formatSingleBill(
|
|||||||
|
|
||||||
// 字典 Label 还原
|
// 字典 Label 还原
|
||||||
const meta = dictionary.get(k);
|
const meta = dictionary.get(k);
|
||||||
let readableKey = meta ? meta.label : k.replace(/^E_[^_]+_/, "");
|
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
|
||||||
if (readableKey.startsWith("E_")) {
|
let readableKey = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || bareKey);
|
||||||
readableKey = readableKey.replace(/^E_/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 格式化字段值
|
// 格式化字段值
|
||||||
let formattedVal = v;
|
let formattedVal = v;
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { VERSION } from "../version.js";
|
||||||
|
|
||||||
|
export function renderDocsHtml(): string {
|
||||||
|
return `<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
|
||||||
|
<title>hose-use API Reference (v${VERSION})</title>
|
||||||
|
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
background-color: #0f172a;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script
|
||||||
|
id="api-reference"
|
||||||
|
data-url="/openapi.json"
|
||||||
|
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
|
||||||
|
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
|
||||||
|
></script>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||||
|
import { URL } from "node:url";
|
||||||
|
import { runCli } from "../cli/runner.js";
|
||||||
|
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||||
|
import { getOpenApiSchema } from "../core/embedded-openapi.js";
|
||||||
|
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||||
|
import { VERSION } from "../version.js";
|
||||||
|
import { renderDocsHtml } from "./docs.js";
|
||||||
|
|
||||||
|
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||||
|
// 1. CORS headers
|
||||||
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||||
|
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||||
|
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
|
||||||
|
|
||||||
|
if (req.method === "OPTIONS") {
|
||||||
|
res.writeHead(204);
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = req.headers.host || "localhost";
|
||||||
|
const protocol = req.headers["x-forwarded-proto"] || "http";
|
||||||
|
const url = new URL(req.url || "/", `${protocol}://${host}`);
|
||||||
|
const pathname = url.pathname.replace(/\/+$/, "") || "/";
|
||||||
|
const method = (req.method || "GET").toUpperCase();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 2. Metadata & Health
|
||||||
|
if (method === "GET" && pathname === "/") {
|
||||||
|
sendJson(res, 200, {
|
||||||
|
name: "hose-use",
|
||||||
|
version: VERSION,
|
||||||
|
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
|
||||||
|
docs: "/docs",
|
||||||
|
openapi: "/openapi.json",
|
||||||
|
rawOpenapi: "/raw-openapi.json",
|
||||||
|
health: "/health",
|
||||||
|
endpoints: {
|
||||||
|
cli: "POST /api/cli",
|
||||||
|
corps: "GET /v1/corps",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === "GET" && pathname === "/health") {
|
||||||
|
sendJson(res, 200, {
|
||||||
|
status: "ok",
|
||||||
|
name: "hose-use",
|
||||||
|
version: VERSION,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === "GET" && pathname === "/docs") {
|
||||||
|
sendHtml(res, 200, renderDocsHtml());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === "GET" && pathname === "/openapi.json") {
|
||||||
|
sendJson(res, 200, getOpenApiSchema("wrapped"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === "GET" && pathname === "/raw-openapi.json") {
|
||||||
|
sendJson(res, 200, getOpenApiSchema("raw"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Command Execution Endpoint: POST /api/cli
|
||||||
|
if (method === "POST" && pathname === "/api/cli") {
|
||||||
|
const body = (await parseJsonBody(req)) as Record<string, unknown> | null;
|
||||||
|
const command = (typeof body?.command === "string" ? body.command : "").trim();
|
||||||
|
if (!command) {
|
||||||
|
sendError(res, 400, "Missing 'command' property in request body");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokens = tokenizeCommand(command);
|
||||||
|
const cliArgs = normalizeCliArgs(tokens);
|
||||||
|
const result = await runCli(cliArgs);
|
||||||
|
|
||||||
|
let parsedData: unknown = undefined;
|
||||||
|
const trimmedStdout = result.stdout.trim();
|
||||||
|
try {
|
||||||
|
if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) {
|
||||||
|
parsedData = JSON.parse(trimmedStdout);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// keep string
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(res, result.exitCode === 0 ? 200 : 400, {
|
||||||
|
success: result.exitCode === 0,
|
||||||
|
stdout: result.stdout,
|
||||||
|
stderr: result.stderr,
|
||||||
|
exitCode: result.exitCode,
|
||||||
|
...(parsedData !== undefined ? { data: parsedData } : {}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. RESTful: GET /v1/corps
|
||||||
|
if (method === "GET" && pathname === "/v1/corps") {
|
||||||
|
const configs = loadCorpConfigs();
|
||||||
|
const globalConfig = loadGlobalConfig();
|
||||||
|
sendJson(res, 200, {
|
||||||
|
count: configs.length,
|
||||||
|
mode: globalConfig.stateful ? "stateful" : "stateless",
|
||||||
|
defaultCorpId: globalConfig.defaultCorpId,
|
||||||
|
corps: configs.map((c) => ({
|
||||||
|
id: c.id,
|
||||||
|
name: c.name,
|
||||||
|
source: c.source,
|
||||||
|
staffId: c.credentials.staffId,
|
||||||
|
baseUrl: c.baseUrl,
|
||||||
|
expiresAt: c.auth?.expiresAt || c.session?.expTime,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
|
sendError(res, 500, message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendJson(res: ServerResponse, status: number, data: unknown): void {
|
||||||
|
if (res.headersSent) return;
|
||||||
|
const payload = JSON.stringify(data, null, 2);
|
||||||
|
res.writeHead(status, {
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
"Content-Length": Buffer.byteLength(payload, "utf-8"),
|
||||||
|
});
|
||||||
|
res.end(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendHtml(res: ServerResponse, status: number, html: string): void {
|
||||||
|
if (res.headersSent) return;
|
||||||
|
res.writeHead(status, {
|
||||||
|
"Content-Type": "text/html; charset=utf-8",
|
||||||
|
"Content-Length": Buffer.byteLength(html, "utf-8"),
|
||||||
|
});
|
||||||
|
res.end(html);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendError(res: ServerResponse, status: number, message: string): void {
|
||||||
|
sendJson(res, status, { error: true, message });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function parseJsonBody(req: IncomingMessage): Promise<unknown> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let raw = "";
|
||||||
|
req.on("data", (chunk) => {
|
||||||
|
raw += chunk;
|
||||||
|
if (raw.length > 5 * 1024 * 1024) {
|
||||||
|
// 5MB max payload
|
||||||
|
reject(new Error("Request payload too large (max 5MB)"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
req.on("end", () => {
|
||||||
|
if (!raw.trim()) {
|
||||||
|
resolve(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
resolve(JSON.parse(raw));
|
||||||
|
} catch (err) {
|
||||||
|
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
req.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { describe, expect, test, afterAll, beforeAll } from "bun:test";
|
||||||
|
import type { Server } from "node:http";
|
||||||
|
import { startHttpServer } from "./server.js";
|
||||||
|
import { VERSION } from "../version.js";
|
||||||
|
|
||||||
|
describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||||
|
let server: Server;
|
||||||
|
const testPort = 18888;
|
||||||
|
const baseUrl = `http://127.0.0.1:${testPort}`;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
server = await startHttpServer({ port: testPort, host: "127.0.0.1", silent: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("GET / 返回服务概览与 CORS 标头", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/`);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||||
|
const json = (await res.json()) as any;
|
||||||
|
expect(json.name).toBe("hose-use");
|
||||||
|
expect(json.version).toBe(VERSION);
|
||||||
|
expect(json.docs).toBe("/docs");
|
||||||
|
expect(json.openapi).toBe("/openapi.json");
|
||||||
|
expect(json.health).toBe("/health");
|
||||||
|
expect(json.endpoints.cli).toBe("POST /api/cli");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("GET /health 返回存活探针状态", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/health`);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const json = (await res.json()) as any;
|
||||||
|
expect(json.status).toBe("ok");
|
||||||
|
expect(json.name).toBe("hose-use");
|
||||||
|
expect(json.version).toBe(VERSION);
|
||||||
|
expect(json.timestamp).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("GET /openapi.json 返回标准包装层 OpenAPI 规范", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/openapi.json`);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const json = (await res.json()) as any;
|
||||||
|
expect(json.openapi).toBe("3.1.0");
|
||||||
|
expect(json.info.title).toContain("hose-use");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("GET /raw-openapi.json 返回原生下游 OpenAPI 规范", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/raw-openapi.json`);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const json = (await res.json()) as any;
|
||||||
|
expect(json.openapi).toBe("3.1.0");
|
||||||
|
expect(json.info.title).toContain("Downstream");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("GET /docs 返回 Scalar 交互式文档 HTML 页面", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/docs`);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.headers.get("content-type")).toContain("text/html");
|
||||||
|
const html = await res.text();
|
||||||
|
expect(html).toContain("<html");
|
||||||
|
expect(html).toContain("api-reference");
|
||||||
|
expect(html).toContain("data-url=\"/openapi.json\"");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("POST /api/cli 允许同进程执行 CLI 指令", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/api/cli`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ command: "version" }),
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const json = (await res.json()) as any;
|
||||||
|
expect(json.success).toBe(true);
|
||||||
|
expect(json.exitCode).toBe(0);
|
||||||
|
expect(json.stdout).toContain(`hose-use v${VERSION}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("GET /v1/corps 返回企业列表与运行模式", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/v1/corps`);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const json = (await res.json()) as any;
|
||||||
|
expect(json).toHaveProperty("count");
|
||||||
|
expect(json).toHaveProperty("mode");
|
||||||
|
expect(Array.isArray(json.corps)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OPTIONS /v1/corps 处理 CORS 跨域预检", async () => {
|
||||||
|
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
|
||||||
|
expect(res.status).toBe(204);
|
||||||
|
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
|
||||||
|
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { createServer, type Server } from "node:http";
|
||||||
|
import { handleHttpRequest } from "./routes.js";
|
||||||
|
import { VERSION } from "../version.js";
|
||||||
|
|
||||||
|
export type HttpServerOptions = {
|
||||||
|
port?: number;
|
||||||
|
host?: string;
|
||||||
|
silent?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DEFAULT_HTTP_PORT = 8888;
|
||||||
|
export const DEFAULT_HTTP_HOST = "127.0.0.1";
|
||||||
|
|
||||||
|
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
|
||||||
|
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||||
|
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||||
|
|
||||||
|
const server = createServer(async (req, res) => {
|
||||||
|
try {
|
||||||
|
await handleHttpRequest(req, res);
|
||||||
|
} catch (err) {
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
|
||||||
|
res.end(JSON.stringify({ error: true, message: err instanceof Error ? err.message : String(err) }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
server.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
|
||||||
|
server.listen(port, host, () => {
|
||||||
|
if (!options.silent) {
|
||||||
|
console.error(`\n⚡ hose-use HTTP Server (v${VERSION}) 已启动`);
|
||||||
|
console.error(` 主服务地址: http://${host}:${port}`);
|
||||||
|
console.error(` 交互式文档: http://${host}:${port}/docs`);
|
||||||
|
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
|
||||||
|
console.error(` CLI执行网关: POST http://${host}:${port}/api/cli`);
|
||||||
|
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||||
|
}
|
||||||
|
resolve(server);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||||
|
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||||
|
import {
|
||||||
|
createServer,
|
||||||
|
resolveMcpMode,
|
||||||
|
HOSE_CLI_TOOL_NAME,
|
||||||
|
HOSE_MCP_MODE_ENV,
|
||||||
|
tokenizeCommand,
|
||||||
|
normalizeCliArgs,
|
||||||
|
} from "./server.js";
|
||||||
|
import { VERSION } from "./version.js";
|
||||||
|
|
||||||
|
describe("hose-use MCP server & hose_cli single-gate pattern", () => {
|
||||||
|
test("tokenizes complex CLI arguments with quotes and JSON payloads", () => {
|
||||||
|
expect(
|
||||||
|
tokenizeCommand(`hose-use bill query --code "BX20260901001" --corp ID01MCcOgJl1td`)
|
||||||
|
).toEqual([
|
||||||
|
"hose-use",
|
||||||
|
"bill",
|
||||||
|
"query",
|
||||||
|
"--code",
|
||||||
|
"BX20260901001",
|
||||||
|
"--corp",
|
||||||
|
"ID01MCcOgJl1td",
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
tokenizeCommand(`hose auth import --raw 'curl "https://app.ekuaibao.com/api?corpId=123" -H "accessToken: abc"'`)
|
||||||
|
).toEqual([
|
||||||
|
"hose",
|
||||||
|
"auth",
|
||||||
|
"import",
|
||||||
|
"--raw",
|
||||||
|
`curl "https://app.ekuaibao.com/api?corpId=123" -H "accessToken: abc"`,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("normalizes CLI prefix binary names", () => {
|
||||||
|
expect(normalizeCliArgs(["hose-use", "version"])).toEqual(["version"]);
|
||||||
|
expect(normalizeCliArgs(["hose", "corps", "list"])).toEqual(["corps", "list"]);
|
||||||
|
expect(normalizeCliArgs(["/usr/local/bin/hose", "probe"])).toEqual(["probe"]);
|
||||||
|
expect(normalizeCliArgs(["corps", "current"])).toEqual(["corps", "current"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolves HOSE_MCP_MODE from environment variable", () => {
|
||||||
|
const original = process.env[HOSE_MCP_MODE_ENV];
|
||||||
|
delete process.env[HOSE_MCP_MODE_ENV];
|
||||||
|
|
||||||
|
try {
|
||||||
|
expect(resolveMcpMode()).toBe("single");
|
||||||
|
expect(resolveMcpMode("single")).toBe("single");
|
||||||
|
expect(resolveMcpMode("all")).toBe("all");
|
||||||
|
expect(resolveMcpMode("both")).toBe("all");
|
||||||
|
expect(resolveMcpMode("legacy")).toBe("legacy");
|
||||||
|
} finally {
|
||||||
|
if (original === undefined) delete process.env[HOSE_MCP_MODE_ENV];
|
||||||
|
else process.env[HOSE_MCP_MODE_ENV] = original;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("advertises only hose_cli in single mode and executes commands in-process", async () => {
|
||||||
|
const server = createServer({ mode: "single" });
|
||||||
|
const client = new Client({ name: "hose-use-test-client", version: "1.0.0" });
|
||||||
|
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.all([
|
||||||
|
server.connect(serverTransport),
|
||||||
|
client.connect(clientTransport),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const listed = await client.listTools();
|
||||||
|
expect(listed.tools).toHaveLength(1);
|
||||||
|
expect(listed.tools[0]?.name).toBe(HOSE_CLI_TOOL_NAME);
|
||||||
|
expect(listed.tools[0]?.inputSchema).toMatchObject({
|
||||||
|
type: "object",
|
||||||
|
required: ["command"],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Execute 'version'
|
||||||
|
const versionResult = await client.callTool({
|
||||||
|
name: HOSE_CLI_TOOL_NAME,
|
||||||
|
arguments: { command: "hose-use version" },
|
||||||
|
});
|
||||||
|
expect(versionResult.isError).not.toBe(true);
|
||||||
|
const content = versionResult.content as Array<{ type: "text"; text: string }>;
|
||||||
|
expect(content[0]?.text).toContain(`hose-use v${VERSION}`);
|
||||||
|
|
||||||
|
// Execute 'corps list'
|
||||||
|
const corpsResult = await client.callTool({
|
||||||
|
name: HOSE_CLI_TOOL_NAME,
|
||||||
|
arguments: { command: "corps list" },
|
||||||
|
});
|
||||||
|
expect(corpsResult.isError).not.toBe(true);
|
||||||
|
const corpsContent = corpsResult.content as Array<{ type: "text"; text: string }>;
|
||||||
|
const text = corpsContent[0]?.text || "";
|
||||||
|
expect(text.includes("已配置企业列表") || text.includes("未找到任何企业配置")).toBe(true);
|
||||||
|
|
||||||
|
// Execute invalid command
|
||||||
|
const invalidResult = await client.callTool({
|
||||||
|
name: HOSE_CLI_TOOL_NAME,
|
||||||
|
arguments: { command: "not-a-real-command-xyz" },
|
||||||
|
});
|
||||||
|
expect(invalidResult.isError).toBe(true);
|
||||||
|
const errContent = invalidResult.content as Array<{ type: "text"; text: string }>;
|
||||||
|
expect(errContent[0]?.text).toContain("未知命令域");
|
||||||
|
} finally {
|
||||||
|
await Promise.allSettled([client.close(), server.close()]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("advertises both hose_cli and fine-grained tools in all mode", async () => {
|
||||||
|
const server = createServer({ mode: "all" });
|
||||||
|
const client = new Client({ name: "hose-use-test-all", version: "1.0.0" });
|
||||||
|
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.all([
|
||||||
|
server.connect(serverTransport),
|
||||||
|
client.connect(clientTransport),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const listed = await client.listTools();
|
||||||
|
const toolNames = listed.tools.map((t) => t.name);
|
||||||
|
expect(toolNames).toContain(HOSE_CLI_TOOL_NAME);
|
||||||
|
expect(toolNames).toContain("bill_search");
|
||||||
|
expect(toolNames).toContain("list_corps");
|
||||||
|
expect(toolNames).toContain("platform_workflow_list_all");
|
||||||
|
expect(toolNames.length).toBeGreaterThan(5);
|
||||||
|
} finally {
|
||||||
|
await Promise.allSettled([client.close(), server.close()]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("advertises only fine-grained tools in legacy mode", async () => {
|
||||||
|
const server = createServer({ mode: "legacy" });
|
||||||
|
const client = new Client({ name: "hose-use-test-legacy", version: "1.0.0" });
|
||||||
|
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.all([
|
||||||
|
server.connect(serverTransport),
|
||||||
|
client.connect(clientTransport),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const listed = await client.listTools();
|
||||||
|
const toolNames = listed.tools.map((t) => t.name);
|
||||||
|
expect(toolNames).not.toContain(HOSE_CLI_TOOL_NAME);
|
||||||
|
expect(toolNames).toContain("bill_search");
|
||||||
|
expect(toolNames).toContain("list_corps");
|
||||||
|
} finally {
|
||||||
|
await Promise.allSettled([client.close(), server.close()]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
+227
-26
@@ -5,6 +5,8 @@ import {
|
|||||||
ListToolsRequestSchema,
|
ListToolsRequestSchema,
|
||||||
} from "@modelcontextprotocol/sdk/types.js";
|
} from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
import { dirname, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
import { loadCorpConfigs } from "./core/config/loader.js";
|
import { loadCorpConfigs } from "./core/config/loader.js";
|
||||||
import { CorpContext } from "./core/config/manager.js";
|
import { CorpContext } from "./core/config/manager.js";
|
||||||
import { createEkbClient } from "./core/auth/ekb.js";
|
import { createEkbClient } from "./core/auth/ekb.js";
|
||||||
@@ -13,6 +15,117 @@ import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.j
|
|||||||
import { authTools } from "./core/auth/tools.js";
|
import { authTools } from "./core/auth/tools.js";
|
||||||
import { platformTools } from "./domains/platform/tools.js";
|
import { platformTools } from "./domains/platform/tools.js";
|
||||||
import { billTools } from "./domains/bill/tools.js";
|
import { billTools } from "./domains/bill/tools.js";
|
||||||
|
import { runCli } from "./cli/runner.js";
|
||||||
|
import { redactSensitiveText } from "./cli/printer.js";
|
||||||
|
import { VERSION } from "./version.js";
|
||||||
|
import type { CliResult } from "./cli/types.js";
|
||||||
|
|
||||||
|
export const HOSE_CLI_TOOL_NAME = "hose_cli";
|
||||||
|
export const HOSE_MCP_MODE_ENV = "HOSE_MCP_MODE"; // "single" | "all" | "legacy"
|
||||||
|
|
||||||
|
export type HoseMcpMode = "single" | "all" | "legacy";
|
||||||
|
|
||||||
|
const serverEntryFile = fileURLToPath(import.meta.url);
|
||||||
|
const appRoot = dirname(dirname(serverEntryFile));
|
||||||
|
|
||||||
|
export function resolveMcpMode(value = process.env[HOSE_MCP_MODE_ENV]): HoseMcpMode {
|
||||||
|
if (!value) return "single";
|
||||||
|
const normalized = value.trim().toLowerCase();
|
||||||
|
if (normalized === "all" || normalized === "both" || normalized === "full") return "all";
|
||||||
|
if (normalized === "legacy" || normalized === "multi") return "legacy";
|
||||||
|
return "single";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function tokenizeCommand(command: string): string[] {
|
||||||
|
const tokens: string[] = [];
|
||||||
|
let token = "";
|
||||||
|
let quote: "'" | '"' | undefined;
|
||||||
|
let escaped = false;
|
||||||
|
let tokenStarted = false;
|
||||||
|
|
||||||
|
for (const character of command) {
|
||||||
|
if (escaped) {
|
||||||
|
token += character;
|
||||||
|
escaped = false;
|
||||||
|
tokenStarted = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (character === "\\" && quote !== "'") {
|
||||||
|
escaped = true;
|
||||||
|
tokenStarted = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (quote) {
|
||||||
|
if (character === quote) {
|
||||||
|
quote = undefined;
|
||||||
|
} else {
|
||||||
|
token += character;
|
||||||
|
}
|
||||||
|
tokenStarted = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (character === "'" || character === '"') {
|
||||||
|
quote = character;
|
||||||
|
tokenStarted = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (/\s/.test(character)) {
|
||||||
|
if (tokenStarted) {
|
||||||
|
tokens.push(token);
|
||||||
|
token = "";
|
||||||
|
tokenStarted = false;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
token += character;
|
||||||
|
tokenStarted = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (escaped) throw new Error("Invalid command: trailing escape");
|
||||||
|
if (quote) throw new Error("Invalid command: unterminated quote");
|
||||||
|
if (tokenStarted) tokens.push(token);
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeCliArgs(tokens: string[]): string[] {
|
||||||
|
const first = tokens[0];
|
||||||
|
if (!first) return [];
|
||||||
|
const lower = first.toLowerCase().replace(/\\/g, "/");
|
||||||
|
if (
|
||||||
|
lower === "hose-use" ||
|
||||||
|
lower === "hose" ||
|
||||||
|
lower.endsWith("/hose-use") ||
|
||||||
|
lower.endsWith("/hose") ||
|
||||||
|
lower.endsWith("/hose-use.exe") ||
|
||||||
|
lower.endsWith("/hose.exe")
|
||||||
|
) {
|
||||||
|
return tokens.slice(1);
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cliResult(result: CliResult): {
|
||||||
|
content: Array<{ type: "text"; text: string }>;
|
||||||
|
isError: boolean;
|
||||||
|
} {
|
||||||
|
const isError = result.exitCode !== 0;
|
||||||
|
let text = isError ? (result.stderr || result.stdout || "Command failed") : (result.stdout || result.stderr || "Success");
|
||||||
|
text = redactSensitiveText(text);
|
||||||
|
return {
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
text: text.trimEnd(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
isError,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function formatError(error: unknown): {
|
function formatError(error: unknown): {
|
||||||
content: Array<{ type: "text"; text: string }>;
|
content: Array<{ type: "text"; text: string }>;
|
||||||
@@ -46,22 +159,19 @@ function formatError(error: unknown): {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error(error);
|
|
||||||
return {
|
return {
|
||||||
content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }],
|
content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }],
|
||||||
isError: true,
|
isError: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
export function createServer(options: { mode?: HoseMcpMode } = {}) {
|
||||||
// 加载企业配置
|
const mode = options.mode ?? resolveMcpMode();
|
||||||
const corps = loadCorpConfigs();
|
|
||||||
const corpContext = new CorpContext(corps);
|
|
||||||
|
|
||||||
const server = new Server(
|
const server = new Server(
|
||||||
{
|
{
|
||||||
name: "ekb-mcp",
|
name: "hose-use",
|
||||||
version: "0.1.0",
|
version: VERSION,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
capabilities: {
|
capabilities: {
|
||||||
@@ -70,26 +180,89 @@ async function main() {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// 聚合所有工具
|
const fineGrainedTools = [...authTools, ...platformTools, ...billTools];
|
||||||
const allTools = [...authTools, ...platformTools, ...billTools];
|
|
||||||
|
|
||||||
// 注册工具列表
|
// 注册工具列表
|
||||||
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
||||||
return {
|
const tools: Array<{ name: string; description?: string; inputSchema: any }> = [];
|
||||||
tools: allTools.map((t) => ({
|
|
||||||
name: t.name,
|
// 单工具网关
|
||||||
description: t.description,
|
if (mode === "single" || mode === "all") {
|
||||||
inputSchema: (t.parameters as any).toJSONSchema(),
|
tools.push({
|
||||||
})),
|
name: HOSE_CLI_TOOL_NAME,
|
||||||
};
|
description:
|
||||||
|
"Run hose-use CLI commands (e.g. 'bill query', 'corps list', 'workflow search'). See the hose-use skill for command reference.",
|
||||||
|
inputSchema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
command: {
|
||||||
|
type: "string",
|
||||||
|
description:
|
||||||
|
"A hose-use CLI command string, with or without the leading 'hose-use' or 'hose'. Example: 'corps list' or 'bill query --code BX20260901001'.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ["command"],
|
||||||
|
additionalProperties: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 细粒度工具(仅在 all 或 legacy 模式下保留)
|
||||||
|
if (mode === "all" || mode === "legacy") {
|
||||||
|
for (const t of fineGrainedTools) {
|
||||||
|
tools.push({
|
||||||
|
name: t.name,
|
||||||
|
description: t.description,
|
||||||
|
inputSchema: (t.parameters as any).toJSONSchema(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { tools };
|
||||||
});
|
});
|
||||||
|
|
||||||
// 处理工具调用
|
// 处理工具调用
|
||||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||||
const { name, arguments: args } = request.params;
|
const { name, arguments: args } = request.params;
|
||||||
|
|
||||||
|
// 1. 处理 hose_cli 网关工具调用
|
||||||
|
if (name === HOSE_CLI_TOOL_NAME) {
|
||||||
|
const command = args && typeof args.command === "string" ? args.command : undefined;
|
||||||
|
if (!command?.trim()) {
|
||||||
|
return cliResult({
|
||||||
|
stdout: "",
|
||||||
|
stderr: "hose_cli requires a non-empty command string",
|
||||||
|
exitCode: 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tokens = tokenizeCommand(command);
|
||||||
|
const cliArgs = normalizeCliArgs(tokens);
|
||||||
|
if (!cliArgs.length) {
|
||||||
|
throw new Error("hose_cli requires a non-empty command string");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await runCli(cliArgs, {
|
||||||
|
appRoot,
|
||||||
|
entryFile: serverEntryFile,
|
||||||
|
});
|
||||||
|
return cliResult(result);
|
||||||
|
} catch (error) {
|
||||||
|
return cliResult({
|
||||||
|
stdout: "",
|
||||||
|
stderr: error instanceof Error ? error.message : String(error),
|
||||||
|
exitCode: 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 处理细粒度工具兼容调用
|
||||||
try {
|
try {
|
||||||
// 1. 检查 Auth 工具
|
const corps = loadCorpConfigs();
|
||||||
|
const corpContext = new CorpContext(corps);
|
||||||
|
|
||||||
|
// Auth 工具
|
||||||
const authTool = authTools.find((t) => t.name === name);
|
const authTool = authTools.find((t) => t.name === name);
|
||||||
if (authTool) {
|
if (authTool) {
|
||||||
const parsed = authTool.parameters.safeParse(args || {});
|
const parsed = authTool.parameters.safeParse(args || {});
|
||||||
@@ -110,7 +283,7 @@ async function main() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 检查 Bill 工具
|
// Bill 工具
|
||||||
const billTool = billTools.find((t) => t.name === name);
|
const billTool = billTools.find((t) => t.name === name);
|
||||||
if (billTool) {
|
if (billTool) {
|
||||||
const parsed = billTool.parameters.safeParse(args || {});
|
const parsed = billTool.parameters.safeParse(args || {});
|
||||||
@@ -131,21 +304,20 @@ async function main() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 检查 Domain 业务工具(需要当前企业上下文)
|
// Platform 业务工具
|
||||||
const currentCorp = corpContext.getCurrent();
|
const currentCorp = corpContext.getCurrent();
|
||||||
if (!currentCorp) {
|
if (!currentCorp) {
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: "text",
|
||||||
text: "未配置企业,请先调用 import_f12_corp 导入凭证,或执行 bun run login 登录",
|
text: "未配置企业,请先调用 auth login 登录或 auth import 导入凭证",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
isError: true,
|
isError: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Platform 工具
|
|
||||||
const platformTool = platformTools.find((t) => t.name === name);
|
const platformTool = platformTools.find((t) => t.name === name);
|
||||||
if (platformTool) {
|
if (platformTool) {
|
||||||
const parsed = platformTool.parameters.safeParse(args || {});
|
const parsed = platformTool.parameters.safeParse(args || {});
|
||||||
@@ -175,7 +347,7 @@ async function main() {
|
|||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: "text",
|
||||||
text: `未知工具: ${name}`,
|
text: `未知工具: ${name}。在单工具网关模式下,请通过 ${HOSE_CLI_TOOL_NAME} 调用。`,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
isError: true,
|
isError: true,
|
||||||
@@ -185,9 +357,38 @@ async function main() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const transport = new StdioServerTransport();
|
return server;
|
||||||
await server.connect(transport);
|
|
||||||
console.error("EKB MCP Server running on stdio");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch(console.error);
|
export async function startServer() {
|
||||||
|
const server = createServer();
|
||||||
|
const transport = new StdioServerTransport();
|
||||||
|
await server.connect(transport);
|
||||||
|
console.error(`hose-use MCP Server (v${VERSION}) running on stdio [mode: ${resolveMcpMode()}]`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runEmbeddedCli() {
|
||||||
|
const result = await runCli(process.argv.slice(3), {
|
||||||
|
appRoot,
|
||||||
|
entryFile: serverEntryFile,
|
||||||
|
});
|
||||||
|
if (result.stdout) process.stdout.write(result.stdout);
|
||||||
|
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
|
||||||
|
process.exitCode = result.exitCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isMainModule = Boolean(
|
||||||
|
(import.meta as any).main ||
|
||||||
|
(!import.meta.url.includes("$bunfs") && process.argv[1] && resolve(process.argv[1]) === resolve(serverEntryFile))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isMainModule) {
|
||||||
|
if (process.argv[2] === "--hose-use-cli" || process.argv[2] === "--hose-cli") {
|
||||||
|
await runEmbeddedCli();
|
||||||
|
} else {
|
||||||
|
startServer().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
export const VERSION = "0.3.0";
|
export const VERSION = "0.5.0";
|
||||||
Reference in new issue
Block a user