Compare commits

..
8 Commits
Author SHA1 Message Date
gitea 07b4e14e59 fix(test): 增强 server.test.ts 在无凭证全新 CI 容器环境下的兼容断言
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:41:10 +08:00
gitea ba30c1a6cb feat(cli): 支持大输出防爆保护、本地文件转储与敏感凭证全链路脱敏并发布 v0.4.2
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:40:32 +08:00
gitea cf44c7dcdf feat(config): 支持多层级企业配置发现、读写分离安全落盘与路径诊断并发布 v0.4.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:34:29 +08:00
gitea 9e20caf4a3 feat(mcp): 引入 MCP 单工具网关模式 (hose_cli) 与并发流调度并发布 v0.4.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:28:41 +08:00
gitea 4f510efc1b feat(auth): 支持代客协助平台凭证智能识别、Token过期感知与单据字典增强并发布 v0.3.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:08:47 +08:00
gitea 5cf6c9e014 feat(bill): 引入费控单据与费用明细检索(支持按单号精准查询与 DataLink 字典自动还原)并发布 v0.3.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:48:20 +08:00
gitea 0372698ff9 ci: 添加 openapi:all 构建步骤并集成 GitHub 与 Gitea 自动双发布
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:33:45 +08:00
gitea b13959451a feat(openapi): 引入双层 OpenAPI 规范管理 (原始下游 & 包装层工具) 并升级版本至 v0.2.2
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:29:32 +08:00
47 changed files with 4009 additions and 146 deletions

No files matched your search

+61
View File
@@ -25,9 +25,15 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Generate & bundle OpenAPI
run: bun run openapi:all
- name: Type-check
run: bun run check
- name: Test
run: bun test
- name: Compile multi-target binaries
run: |
mkdir -p dist/bin
@@ -54,3 +60,58 @@ jobs:
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --generate-notes
fi
gh release upload "${GITHUB_REF_NAME}" dist/bin/hose-use-* --repo "${GITHUB_REPOSITORY}" --clobber
- name: Publish Gitea Release
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_HOST: "https://git.ying-qing.cn"
GITEA_REPO: "gitea/hose-use"
run: |
if [ -z "$GITEA_TOKEN" ]; then
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
exit 0
fi
TAG_NAME="${GITHUB_REF_NAME}"
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
echo "==> Creating release on Gitea for ${TAG_NAME}..."
RELEASE_RESP=$(curl -s -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":$(echo "$NOTES" | jq -Rsa .),\"draft\":false,\"prerelease\":false}")
RELEASE_ID=$(echo "$RELEASE_RESP" | jq -r '.id // empty')
if [ -z "$RELEASE_ID" ]; then
RELEASE_ID=$(curl -s -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
fi
if [ -z "$RELEASE_ID" ]; then
echo "::warning::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
exit 0
fi
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
upload_asset() {
local file="$1"
local filename
filename=$(basename "$file")
echo " [start] Uploading ${filename} to Gitea..."
RESP=$(curl -s -m 120 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${file}")
STATUS=$(echo "$RESP" | tail -n 1)
echo " [done] ${filename} -> ${STATUS}"
}
pids=()
for file in dist/bin/hose-use-*; do
upload_asset "$file" &
pids+=($!)
done
for pid in "${pids[@]}"; do
wait "$pid" || true
done
echo "✓ Successfully published release assets to Gitea!"
+2 -3
View File
@@ -43,6 +43,5 @@ data/
*.db
*.sqlite
# 环境变量
.env
.env.local
# Local roadmaps & scratch notes
*.local.md
+29 -8
View File
@@ -1,4 +1,4 @@
# hose-use (v0.2.1)
# hose-use (v0.4.2)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -32,8 +32,9 @@ hose-use corps list # 列出名下所有已配置企
hose-use corps switch <corpId> # 切换工作企业
hose-use corps current # 查看当前激活企业
# 3. 运行模式管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式
# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式与默认企业
hose-use config paths # 查看多级企业目录发现链与配置文件位置
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
@@ -44,16 +45,36 @@ hose-use workflow find --task=code-js2 # 搜索包含特定节点类型
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
hose-use platform list # 查看企业下所有启用的自建应用
# 5. Agent Skill 与连通性诊断
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
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 schema # 查看企业全部单据实体与数据模型字典
# 6. OpenAPI 规范导出 (原始下游契约 & 包装层工具规范)
hose-use openapi paths # 查看包装层 API 路径与概要一览
hose-use openapi --raw paths # 查看合思原生下游全量 API 路径
hose-use openapi info # 查看 OpenAPI 规范元数据概览
hose-use openapi # 输出包装层标准 OpenAPI 3.1.0 JSON
hose-use openapi --raw # 输出原生下游全量 OpenAPI 3.1.0 JSON
# 7. Agent Skill 与连通性诊断
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
# 6. 一键自更新与版本发布历史
hose-use update # 自动检查并升级到最新版本 (多镜像源加速)
hose-use update --check # 仅检查新版本与 Release Notes
hose-use update --changelog # 查看最近版本发布历史
# 8. MCP Server (单工具网关模式)
hose-use mcp # 启动 MCP Server (默认暴露 hose_cli 单工具网关)
```
### 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
+3
View File
@@ -7,6 +7,7 @@
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"ky": "^2.0.2",
"yaml": "^2.9.0",
"zod": "^4.4.3",
},
"devDependencies": {
@@ -206,6 +207,8 @@
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
+167
View File
@@ -0,0 +1,167 @@
ErrorResponse:
type: object
properties:
error:
type: boolean
example: true
message:
type: string
example: 操作失败原因
AuthLoginRequest:
type: object
required:
- phone
- password
properties:
phone:
type: string
description: 登录手机号
example: "17718556446"
password:
type: string
description: 登录明文密码 (由客户端自动完成 RSA 加密)
autoSwitch:
type: boolean
description: 是否自动切换到首个企业
default: true
AuthStatusResponse:
type: object
properties:
loggedIn:
type: boolean
activeCorpId:
type: string
activeCorpName:
type: string
totalAccounts:
type: integer
totalCorps:
type: integer
CorpConfig:
type: object
properties:
corpId:
type: string
description: 企业唯一标识
corpName:
type: string
description: 企业名称
staffId:
type: string
description: 员工身份 ID
accountId:
type: string
description: 归属账号手机号
PlatformItem:
type: object
properties:
id:
type: string
description: 自建应用 ID
name:
type: string
description: 自建应用名称
code:
type: string
description: 应用编码
status:
type: string
description: 应用状态
WorkflowSummary:
type: object
properties:
id:
type: string
description: 工作流 ID
name:
type: string
description: 工作流名称
platformId:
type: string
description: 归属自建应用 ID
platformName:
type: string
description: 归属自建应用名称
state:
type: integer
description: "1: 启用, 0: 停用"
updatedAt:
type: string
WorkflowDetail:
type: object
properties:
id:
type: string
name:
type: string
state:
type: integer
nodes:
type: array
items:
type: object
description: 工作流节点列表 (code-js2, loop, sql 等)
links:
type: array
items:
type: object
ProbeResult:
type: object
properties:
corpId:
type: string
corpName:
type: string
mainSession:
type: boolean
description: 主站会话是否有效
easoToken:
type: boolean
description: EASO 平台 Token 是否有效
platformsReachable:
type: boolean
description: 自建应用接口是否可访问
FormattedBill:
type: object
properties:
billId:
type: string
description: 单据 ID
billCode:
type: string
description: 单据业务编号 (单号)
billName:
type: string
description: 单据名称
title:
type: string
description: 单据标题
stage:
type: string
description: 业务阶段 (如 expense, loan, payment)
state:
type: string
description: 审批/支付状态 (如 paid, approving, draft)
amount:
type: string
description: 格式化金额 (如 ¥100.00 CNY)
submitterId:
type: string
description: 提交人员 ID
submitDate:
type: string
description: 提交时间
corporationId:
type: string
description: 归属企业 ID
details:
type: object
description: DataLink 字段字典还原后的中文字段键值对
+54
View File
@@ -0,0 +1,54 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.4.2
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
- url: http://localhost:3000
description: Local hose-use CLI / MCP Runtime Gateway
tags:
- name: Auth & SSO
description: 统一认证、多账号管理与 30 天 Token 自动无感续杯
- name: Corps & Tenancy
description: 多企业租户管理与工作空间切换
- name: Platforms
description: 自建应用检索与实例枚举
- name: Workflows
description: 跨自建应用工作流聚合检索、DSL 图谱与启停
- name: Bills & Documents
description: 费控单据、报销借款单、发票明细与 DataLink 实体字典
- name: Probe & Diagnostics
description: 会话有效性与 EASO 鉴权连通性诊断
paths:
/api/auth/login:
$ref: ./paths/auth.yaml#/login
/api/auth/status:
$ref: ./paths/auth.yaml#/status
/api/auth/refresh:
$ref: ./paths/auth.yaml#/refresh
/api/corps:
$ref: ./paths/corps.yaml#/list
/api/corps/switch:
$ref: ./paths/corps.yaml#/switch
/api/platforms:
$ref: ./paths/platform.yaml#/list
/api/workflows:
$ref: ./paths/workflow.yaml#/list
/api/workflows/find:
$ref: ./paths/workflow.yaml#/find
/api/workflows/{pipelineId}:
$ref: ./paths/workflow.yaml#/detail
/api/workflows/{pipelineId}/toggle:
$ref: ./paths/workflow.yaml#/toggle
/api/bills:
$ref: ./paths/bill.yaml#/list
/api/bills/{code}:
$ref: ./paths/bill.yaml#/get
/api/bills/schema:
$ref: ./paths/bill.yaml#/schema
/api/probe:
$ref: ./paths/probe.yaml#/probe
components:
schemas:
$ref: ./components/schemas/index.yaml
+68
View File
@@ -0,0 +1,68 @@
login:
post:
tags:
- Auth & SSO
summary: 纯 API 账密自动全流程登录
description: 自动拉取公钥进行 RSA PKCS#1 加密,发起统一认证中心握手并批量获取名下所有企业身份。
operationId: authLogin
requestBody:
required: true
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/AuthLoginRequest
responses:
"200":
description: 登录成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
totalCorps:
type: integer
activeCorp:
$ref: ../components/schemas/index.yaml#/CorpConfig
"401":
description: 账密错误或鉴权失败
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/ErrorResponse
status:
get:
tags:
- Auth & SSO
summary: 查看当前登录与活跃企业状态
description: 查询本地或无状态下的当前账号、工作企业与凭证有效期。
operationId: authStatus
responses:
"200":
description: 状态正常
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/AuthStatusResponse
refresh:
post:
tags:
- Auth & SSO
summary: 批量刷新企业 30 天 AccessToken
description: 自动无感为当前账号名下的所有企业租户更新最新 30 天访问令牌。
operationId: authRefresh
responses:
"200":
description: 刷新完成
content:
"application/json":
schema:
type: object
properties:
refreshed:
type: integer
total:
type: integer
+101
View File
@@ -0,0 +1,101 @@
list:
get:
tags:
- Bills & Documents
summary: 检索费用单据与发票明细列表
description: 查询企业名下的费用单据、报销单、借款单与发票列表,支持按单号、阶段、状态过滤。
operationId: listBills
parameters:
- name: code
in: query
required: false
description: 按单据编号/单号过滤(如 jO1it3cIufDjNS)
schema:
type: string
- name: keyword
in: query
required: false
description: 按关键字搜索标题、名称或内容
schema:
type: string
- name: stage
in: query
required: false
description: 按业务阶段过滤(expense 报销, loan 借款, payment 付款)
schema:
type: string
- name: state
in: query
required: false
description: 按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)
schema:
type: string
- name: count
in: query
required: false
description: 返回条数限制
schema:
type: integer
default: 20
responses:
"200":
description: 格式化后的单据列表
content:
"application/json":
schema:
type: object
properties:
total:
type: integer
returned:
type: integer
items:
type: array
items:
$ref: "../components/schemas/index.yaml#/FormattedBill"
get:
get:
tags:
- Bills & Documents
summary: 根据单号或 ID 查询单据结构化详情
description: 自动结合 DataLink 字段字典将代码字段还原为业务中文字段。
operationId: getBillByCode
parameters:
- name: code
in: path
required: true
description: 单据编号(如 n0GMIM0dkQmKbS)或单据 ID(如 ID01TRzg7HMLcb)
schema:
type: string
responses:
"200":
description: 单据详情列表
content:
"application/json":
schema:
type: array
items:
$ref: "../components/schemas/index.yaml#/FormattedBill"
schema:
get:
tags:
- Bills & Documents
summary: 获取单据实体与数据模型字典
description: 获取企业全部表单实体、中文字段 Label 与类型定义。
operationId: getBillSchemas
responses:
"200":
description: 实体模型字典
content:
"application/json":
schema:
type: object
properties:
totalEntities:
type: integer
entities:
type: array
items:
type: object
+48
View File
@@ -0,0 +1,48 @@
list:
get:
tags:
- Corps & Tenancy
summary: 列出当前账号名下所有已配置企业租户
description: 支持单账号管理多家企业与同一企业下的多员工身份分层展示。
operationId: listCorps
responses:
"200":
description: 企业租户列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/CorpConfig
switch:
post:
tags:
- Corps & Tenancy
summary: 切换当前工作企业
description: 在有状态模式下切换并记忆工作企业,后续操作自动以该企业身份执行。
operationId: switchCorp
requestBody:
required: true
content:
"application/json":
schema:
type: object
required:
- corpId
properties:
corpId:
type: string
description: 目标企业 ID 或身份 ID (corpId@accountId)
responses:
"200":
description: 切换成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
activeCorp:
$ref: ../components/schemas/index.yaml#/CorpConfig
+23
View File
@@ -0,0 +1,23 @@
list:
get:
tags:
- Platforms
summary: 查询企业下所有启用的自建应用
description: 枚举当前企业已配置的自建应用及 EASO 平台实例。
operationId: listPlatforms
parameters:
- name: corpId
in: query
required: false
schema:
type: string
description: 目标企业 ID (未指定时使用默认工作企业)
responses:
"200":
description: 自建应用列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/PlatformItem
+20
View File
@@ -0,0 +1,20 @@
probe:
get:
tags:
- Probe & Diagnostics
summary: 诊断当前企业鉴权与接口连通性
description: 依次校验企业主站 Session Cookie、EASO 换票握手与自建应用接口可访问性。
operationId: probeCorp
parameters:
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 诊断报告
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/ProbeResult
+113
View File
@@ -0,0 +1,113 @@
list:
get:
tags:
- Workflows
summary: 跨自建应用汇总查看全部工作流
description: 自动遍历当前企业下所有自建应用,聚合返回全量工作流列表及运行状态。
operationId: listAllWorkflows
parameters:
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 聚合工作流列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/WorkflowSummary
find:
get:
tags:
- Workflows
summary: 按节点类型递归搜索工作流
description: 递归解析所有工作流的 DSL 节点图谱,检索包含特定任务类型(如 code-js2, loop, sql 等)的工作流。
operationId: findWorkflowsByTask
parameters:
- name: task
in: query
required: true
schema:
type: string
example: "code-js2"
description: 目标节点任务类型
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 匹配的工作流列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/WorkflowSummary
detail:
get:
tags:
- Workflows
summary: 获取单个工作流详情与节点结构
description: 查询指定工作流的完整节点链、输入输出参数映射与触发器配置。
operationId: getWorkflowDetail
parameters:
- name: pipelineId
in: path
required: true
schema:
type: string
description: 工作流 ID
responses:
"200":
description: 工作流详情
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/WorkflowDetail
toggle:
put:
tags:
- Workflows
summary: 启用或停用工作流
description: "切换工作流的运行开关(1: 启用, 0: 停用)。"
operationId: toggleWorkflow
parameters:
- name: pipelineId
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
"application/json":
schema:
type: object
required:
- state
properties:
state:
type: integer
enum: [0, 1]
description: "目标状态 (1=启用, 0=停用)"
responses:
"200":
description: 状态切换成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
state:
type: integer
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.2.1",
"version": "0.4.2",
"module": "src/server.ts",
"type": "module",
"bin": {
@@ -14,6 +14,9 @@
"typecheck": "tsc --noEmit",
"test": "bun test",
"bump": "bun run scripts/bump-version.ts",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"openapi:generate-raw": "bun run scripts/generate-raw-openapi.ts",
"openapi:all": "bun run scripts/generate-raw-openapi.ts && bun run scripts/bundle-openapi.ts",
"build:binary": "node scripts/build-binary.mjs",
"dev": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
@@ -22,6 +25,7 @@
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"ky": "^2.0.2",
"yaml": "^2.9.0",
"zod": "^4.4.3"
},
"devDependencies": {
+15 -3
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync } from "node:fs";
import { readFileSync, writeFileSync, existsSync, cpSync } from "node:fs";
import { join } from "node:path";
import { execSync } from "node:child_process";
@@ -54,14 +54,26 @@ skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${n
writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/hose-use/SKILL.md");
// 5. Sync to global ~/.agents/skills/hose-use/ if present
// 5. openapi/openapi.yaml
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
if (existsSync(openapiPath)) {
let openapiContent = readFileSync(openapiPath, "utf-8");
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
writeFileSync(openapiPath, openapiContent);
console.log("✓ Updated openapi/openapi.yaml");
}
// 6. Sync to global ~/.agents/skills/hose-use/ if present
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
const { existsSync, cpSync } = await import("node:fs");
if (existsSync(globalSkillDir)) {
cpSync(join(ROOT, "skills", "hose-use"), globalSkillDir, { recursive: true });
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
}
// 7. Rebuild OpenAPI bundles
console.log("==> Rebuilding OpenAPI bundles...");
execSync("bun run openapi:all", { cwd: ROOT, stdio: "inherit" });
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
console.log("\nNext steps to publish:");
console.log(` 1. Update CHANGELOG.md (if exists)`);
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bun
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import YAML from "yaml";
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
const inputFile = resolve("openapi/openapi.yaml");
const outputFile = resolve("dist/openapi.json");
const bundled = bundle(inputFile, new Set());
mkdirSync(dirname(outputFile), { recursive: true });
writeFileSync(outputFile, `${JSON.stringify(bundled, null, 2)}\n`);
console.log(`✓ Bundled wrapped OpenAPI: ${outputFile}`);
function bundle(filePath: string, seen: Set<string>): Json {
const absolutePath = resolve(filePath);
if (seen.has(absolutePath)) {
throw new Error(`Circular OpenAPI reference: ${absolutePath}`);
}
const parsed = YAML.parse(readFileSync(absolutePath, "utf8")) as Json;
return resolveReferences(parsed, absolutePath, new Set([...seen, absolutePath]));
}
function resolveReferences(value: Json, currentFile: string, seen: Set<string>): Json {
if (Array.isArray(value)) {
return value.map((item) => resolveReferences(item, currentFile, seen));
}
if (!isObject(value)) return value;
if (typeof value.$ref === "string" && isFileReference(value.$ref)) {
const [refPath, pointer = ""] = value.$ref.split("#");
const refFile = refPath ? resolve(dirname(currentFile), refPath) : currentFile;
const target = pointer ? resolvePointer(bundle(refFile, seen), pointer) : bundle(refFile, seen);
return resolveReferences(target, refFile, seen);
}
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
resolveReferences(item as Json, currentFile, seen),
])
);
}
function isFileReference(ref: string) {
return !ref.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(ref);
}
function resolvePointer(document: Json, pointer: string): Json {
const path = pointer.replace(/^#/, "");
if (!path) return document;
return path
.split("/")
.filter(Boolean)
.map((part) => part.replace(/~1/g, "/").replace(/~0/g, "~"))
.reduce((target: Json, key) => {
if (!isObject(target) && !Array.isArray(target)) {
throw new Error(`Invalid JSON pointer segment "${key}" in ${pointer}`);
}
const next = (target as Record<string, Json>)[key];
if (next === undefined) {
throw new Error(`Missing JSON pointer segment "${key}" in ${pointer}`);
}
return next;
}, document);
}
function isObject(value: Json): value is { [key: string]: Json } {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
+768
View File
@@ -0,0 +1,768 @@
#!/usr/bin/env bun
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
const outputFile = resolve("dist/raw-hose-openapi.json");
function standardResponse(description: string, dataSchema: any) {
return {
"200": {
description,
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: dataSchema,
code: { type: "string", example: "SUCCESS" },
message: { type: "string", example: "成功" },
},
},
},
},
},
"401": {
description: "未授权或 Token 已失效",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/ErrorResponse" },
},
},
},
"400": {
description: "请求参数错误或鉴权异常",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/ErrorResponse" },
},
},
},
};
}
const spec = {
openapi: "3.1.0",
info: {
title: "Hose / Ekuaibao Downstream Native API",
version: "1.0.0",
description: "Raw downstream Ekuaibao (合思/易快报), EASO, and Piper business API contracts.",
},
servers: [
{
url: "https://app.ekuaibao.com",
description: "合思/易快报主站与统一认证中心",
},
{
url: "https://easo.ekuaibao.com",
description: "合思 EASO 开放平台网关",
},
{
url: "https://piper.ekuaibao.com",
description: "合思 Piper 工作流与集成网关",
},
],
tags: [
{ name: "SSO & Security", description: "统一认证中心、RSA 公钥密码加密与多企业身份切换" },
{ name: "EASO & Piper Auth", description: "开放平台 OAuth2 免登握手、换票与 Token 自动刷新" },
{ name: "Platforms & Apps", description: "自建应用列表与集成检索" },
{ name: "Workflows & Pipelines", description: "跨应用工作流聚合、运行日志、节点详情与启停" },
{ name: "Bills & Invoices", description: "费控单据、报销单、借款单、发票与 DataLink 实体字典" },
{ name: "Jobs & Execution", description: "工作流任务运行实例与调试" },
{ name: "Staffs & Webhooks", description: "企业通讯录人员与 Webhook 触发配置" },
],
paths: {
"/api/v2/invoice/search": {
post: {
tags: ["Bills & Invoices"],
summary: "检索企业费用单据与发票池",
description: "检索企业名下的费用单据、报销借款单、发票与审批流记录,支持分页与阶段过滤。",
operationId: "rawSearchInvoices",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
content: {
"application/json": {
schema: {
type: "object",
properties: {
limit: {
type: "object",
properties: {
start: { type: "integer", default: 0 },
count: { type: "integer", default: 50 },
},
},
},
},
},
},
},
responses: {
"200": {
description: "单据列表响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
count: { type: "integer" },
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/v2/invoice": {
post: {
tags: ["Bills & Invoices"],
summary: "批量按 ID 精确获取单据详情",
description: "根据单据物理 ID 列表批量拉取完整的表单数据与状态。",
operationId: "rawGetInvoicesByIds",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["ids"],
properties: {
ids: { type: "array", items: { type: "string" } },
},
},
},
},
},
responses: {
"200": {
description: "单据详情列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/v2/datalink/entity/search": {
post: {
tags: ["Bills & Invoices"],
summary: "查询 DataLink 实体定义与字段字典",
description: "获取企业全部单据实体模型、字段 Label 中文映射与类型定义。",
operationId: "rawSearchEntities",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
content: {
"application/json": {
schema: {
type: "object",
properties: {
limit: {
type: "object",
properties: {
start: { type: "integer", default: 0 },
count: { type: "integer", default: 100 },
},
},
},
},
},
},
},
responses: {
"200": {
description: "实体定义字典",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/common/security/getPublicKey": {
post: {
tags: ["SSO & Security"],
summary: "获取统一认证中心 RSA 公钥",
description: "获取用于登录密码加密的 RSA Public Key 模数与指数 (PKCS#1)。",
operationId: "getPublicKey",
responses: {
"200": {
description: "RSA 公钥响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
publicKey: { type: "string", description: "RSA 公钥字符串" },
modulus: { type: "string", description: "RSA Modulus" },
exponent: { type: "string", description: "RSA Exponent" },
},
},
},
},
},
},
},
},
},
},
"/api/common/login/verifyPhone": {
post: {
tags: ["SSO & Security"],
summary: "手机号与加密密码纯 API 登录",
description: "使用 RSA 加密后的密码和手机号发起统一认证,换取全企业 AccessToken 与 Session Cookie。",
operationId: "loginVerifyPhone",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["phone", "password"],
properties: {
phone: { type: "string", description: "手机号" },
password: { type: "string", description: "RSA 加密后的密码密文" },
countryCode: { type: "string", default: "+86" },
},
},
},
},
},
responses: {
"200": {
description: "登录成功并下发凭证",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
accessToken: { type: "string", description: "全局访问令牌" },
user: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
phone: { type: "string" },
},
},
},
},
},
},
},
},
},
},
},
},
"/api/common/user/corporations": {
get: {
tags: ["SSO & Security"],
summary: "获取账号名下可访问企业列表",
description: "拉取当前已登录账号授权的所有企业租户及其 Staff 身份。",
operationId: "listCorporations",
responses: {
"200": {
description: "企业与身份列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/CorporationItem" },
},
},
},
},
},
},
},
},
},
"/api/common/user/corporations/{corpId}/switch": {
post: {
tags: ["SSO & Security"],
summary: "切换工作企业上下文",
description: "切换当前会话至指定企业租户,并签发该企业的专属 Session。",
operationId: "switchCorporation",
parameters: [
{ name: "corpId", in: "path", required: true, schema: { type: "string" }, description: "目标企业 ID" },
],
responses: {
"200": {
description: "切换结果",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
activeCorpId: { type: "string" },
staffId: { type: "string" },
},
},
},
},
},
},
},
},
},
},
"/api/open/oauth2/auth": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 1: 获取授权码",
description: "使用主站会话 Cookie 和 appKey 获取临时 code。",
operationId: "easoGetAuthCode",
responses: {
"200": {
description: "临时授权码",
content: {
"application/json": {
schema: {
type: "object",
properties: {
code: { type: "string", description: "临时授权码" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/token": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 2: 换取 AccessToken",
description: "使用授权码 code 换取平台接口访问 Token 与 RefreshToken。",
operationId: "easoGetToken",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["code", "appKey", "appSecret"],
properties: {
code: { type: "string" },
appKey: { type: "string" },
appSecret: { type: "string" },
grant_type: { type: "string", default: "authorization_code" },
},
},
},
},
},
responses: {
"200": {
description: "平台 Token 响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
access_token: { type: "string" },
refresh_token: { type: "string" },
expires_in: { type: "integer" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/user_info": {
get: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 3: 获取当前开放平台用户信息",
description: "使用 AccessToken 获取当前用户的 openId 与企业绑定身份。",
operationId: "easoGetUserInfo",
responses: {
"200": {
description: "用户信息",
content: {
"application/json": {
schema: {
type: "object",
properties: {
openId: { type: "string" },
corpId: { type: "string" },
name: { type: "string" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/token/refresh": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 令牌无感刷新",
description: "使用 refresh_token 换取新的 30 天 accessToken。",
operationId: "easoRefreshToken",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["refresh_token"],
properties: {
refresh_token: { type: "string" },
grant_type: { type: "string", default: "refresh_token" },
},
},
},
},
},
responses: {
"200": {
description: "新 Token",
content: {
"application/json": {
schema: {
type: "object",
properties: {
access_token: { type: "string" },
refresh_token: { type: "string" },
expires_in: { type: "integer" },
},
},
},
},
},
},
},
},
"/api/v2/datalink/platform/search": {
get: {
tags: ["Platforms & Apps"],
summary: "获取企业自建应用列表",
description: "查询指定企业下已启用的自建应用与平台实例列表。",
operationId: "searchPlatforms",
parameters: [
{ name: "corpId", in: "query", required: true, schema: { type: "string" }, description: "企业 ID" },
{ name: "scope", in: "query", schema: { type: "string", default: "enable" } },
],
responses: {
"200": {
description: "应用列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/PlatformItem" },
},
},
},
},
},
},
},
},
},
"/api/easo/pipelines/logs": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取应用下的工作流列表与日志",
description: "按自建应用 ID 分页查询名下的工作流及最近执行日志。",
operationId: "listWorkflowsByPlatform",
parameters: [
{ name: "platformId", in: "query", required: true, schema: { type: "string" } },
{ name: "number", in: "query", schema: { type: "integer", default: 1 } },
{ name: "pageSize", in: "query", schema: { type: "integer", default: 20 } },
],
responses: standardResponse("工作流分页列表", { $ref: "#/components/schemas/WorkflowPageData" }),
},
},
"/api/easo/stats": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流运行统计",
description: "统计指定应用下工作流的成功、失败及总触发次数。",
operationId: "getWorkflowStats",
parameters: [
{ name: "platformId", in: "query", required: true, schema: { type: "string" } },
],
responses: standardResponse("工作流运行统计", { $ref: "#/components/schemas/WorkflowStatsData" }),
},
},
"/api/easo/charge": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流配额与计费信息",
description: "查询当前企业工作流运行调用次数与配额剩余。",
operationId: "getWorkflowCharge",
responses: standardResponse("配额信息", { $ref: "#/components/schemas/WorkflowChargeData" }),
},
},
"/api/easo/pipelines/{pipelineId}": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流详情与 DSL 节点图",
description: "查询指定工作流的完整配置、触发器与节点链路图谱(code-js2, loop, sql 等)。",
operationId: "getWorkflowDetail",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: standardResponse("工作流完整详情", { $ref: "#/components/schemas/WorkflowDetailData" }),
},
},
"/api/easo/pipelines/state/{pipelineId}": {
put: {
tags: ["Workflows & Pipelines"],
summary: "启用或停用工作流",
description: "切换工作流运行状态(1: 启用, 0: 停用)。",
operationId: "toggleWorkflowState",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
{ name: "state", in: "query", required: true, schema: { type: "integer", enum: [0, 1] } },
],
responses: {
"200": {
description: "状态更新成功",
},
},
},
},
"/api/easo/jobs/running": {
get: {
tags: ["Jobs & Execution"],
summary: "获取运行中的任务实例",
description: "查询工作流正在执行的调试(DEBUG)或生产(PROD)任务列表。",
operationId: "listRunningJobs",
parameters: [
{ name: "pipelineId", in: "query", required: true, schema: { type: "string" } },
{ name: "runType", in: "query", schema: { type: "string", enum: ["DEBUG", "PROD"], default: "DEBUG" } },
],
responses: standardResponse("任务实例列表", {
type: "array",
items: { $ref: "#/components/schemas/WorkflowJobItem" },
}),
},
},
"/api/easo/dsl/all": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取企业全部 DSL 规则配置",
description: "查询企业下所有生效的 DSL 脚本规则。",
operationId: "listAllDsl",
responses: standardResponse("DSL 规则列表", {
type: "array",
items: { $ref: "#/components/schemas/WorkflowDslItem" },
}),
},
},
"/api/easo/common/staffs": {
get: {
tags: ["Staffs & Webhooks"],
summary: "获取企业员工通讯录列表",
description: "查询企业内部或外部员工名单,用于工作流执行人与节点通知映射。",
operationId: "listCommonStaffs",
parameters: [
{ name: "external", in: "query", schema: { type: "boolean", default: false } },
],
responses: standardResponse("员工列表", {
type: "array",
items: { $ref: "#/components/schemas/StaffItem" },
}),
},
},
"/api/webhook/{pipelineId}": {
get: {
tags: ["Staffs & Webhooks"],
summary: "获取工作流 Webhook 触发配置",
description: "查询指定工作流的 Webhook URL 入口与密钥配置。",
operationId: "getWebhookInfo",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: standardResponse("Webhook 配置", { $ref: "#/components/schemas/WebhookInfoData" }),
},
},
"/api/easo/pipelines/{pipelineId}/sampleData": {
post: {
tags: ["Workflows & Pipelines"],
summary: "提取工作流调试/采样数据",
description: "触发工作流节点采样数据提取,用于脚本调试与输入校验。",
operationId: "sampleWorkflowData",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: {
"200": {
description: "采样数据",
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: { type: "object" },
type: { type: "string" },
},
},
},
},
},
},
},
},
},
components: {
schemas: {
ErrorResponse: {
type: "object",
properties: {
code: { type: "string" },
message: { type: "string" },
details: { type: "object" },
},
},
CorporationItem: {
type: "object",
properties: {
id: { type: "string", description: "企业 ID" },
name: { type: "string", description: "企业名称" },
staffId: { type: "string", description: "员工 ID" },
role: { type: "string", description: "角色权限" },
},
},
PlatformItem: {
type: "object",
properties: {
id: { type: "string", description: "自建应用 ID" },
name: { type: "string", description: "应用名称" },
code: { type: "string", description: "应用标识 Code" },
icon: { type: "string" },
status: { type: "string" },
},
},
WorkflowPageData: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/WorkflowItem" },
},
total: { type: "integer" },
number: { type: "integer" },
pageSize: { type: "integer" },
},
},
WorkflowItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
description: { type: "string" },
state: { type: "integer", description: "1: 启用, 0: 停用" },
platformId: { type: "string" },
updatedAt: { type: "string" },
},
},
WorkflowStatsData: {
type: "object",
properties: {
totalCount: { type: "integer" },
successCount: { type: "integer" },
failCount: { type: "integer" },
},
},
WorkflowChargeData: {
type: "object",
properties: {
used: { type: "integer" },
total: { type: "integer" },
remaining: { type: "integer" },
},
},
WorkflowDetailData: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
state: { type: "integer" },
nodes: { type: "array", items: { type: "object" }, description: "节点列表 (含 code-js2, loop, sql 等)" },
links: { type: "array", items: { type: "object" }, description: "节点连线" },
},
},
WorkflowJobItem: {
type: "object",
properties: {
jobId: { type: "string" },
pipelineId: { type: "string" },
status: { type: "string" },
startTime: { type: "string" },
},
},
WorkflowDslItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
content: { type: "string" },
},
},
StaffItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
email: { type: "string" },
cellphone: { type: "string" },
},
},
WebhookInfoData: {
type: "object",
properties: {
webhookUrl: { type: "string" },
token: { type: "string" },
},
},
},
},
};
mkdirSync(dirname(outputFile), { recursive: true });
writeFileSync(outputFile, `${JSON.stringify(spec, null, 2)}\n`);
console.log(`✓ Generated raw downstream OpenAPI: ${outputFile}`);
+70 -2
View File
@@ -15,6 +15,32 @@ description: 合思/易快报 (ekuaibao) 企业 SaaS CLI 命令行工具与底
- **有状态 / 无状态双模式**:
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
- **无状态 (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 paths
# 切换为无状态模式 (Stateless)
hose-use config mode stateless
@@ -84,7 +113,27 @@ hose-use workflow toggle <pipelineId> --state=1
hose-use platform list
```
### 5. 诊断与 MCP 服务 (`hose-use probe` / `hose-use mcp`)
### 5. 单据与费用明细检索 (`hose-use bill`)
```bash
# 查看企业单据与报销列表 (支持分页/阶段/状态过滤)
hose-use bill list
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 字典自动还原)
hose-use bill get n0GMIM0dkQmKbS
hose-use bill get ID01TRzg7HMLcb
# 查看企业全部单据实体与数据模型字典
hose-use bill schema
```
### 6. 诊断与 MCP 服务 (`hose-use probe` / `hose-use mcp`)
```bash
# 连通性与 EASO 平台鉴权诊断
@@ -95,7 +144,26 @@ hose-use probe --corp=uzU7pcWfScck00
hose-use mcp serve
```
### 6. 自更新与版本历史 (`hose-use update`)
### 7. OpenAPI 规范导出 (`hose-use openapi`)
```bash
# 查看包装层 API 路径与概要一览
hose-use openapi paths
# 查看合思原生下游全量 API 路径
hose-use openapi --raw paths
# 查看 OpenAPI 规范元数据概览
hose-use openapi info
# 输出包装层标准 OpenAPI 3.1.0 JSON (适合导入 Postman/Swagger/Agent)
hose-use openapi
# 输出原生下游全量 OpenAPI 3.1.0 JSON
hose-use openapi --raw
```
### 8. 自更新与版本历史 (`hose-use update`)
```bash
# 检查最新可用版本与 Release Notes
+58 -7
View File
@@ -3,6 +3,7 @@ import {
fullSmsLogin,
fullBrowserSyncLogin,
sendSmsVerificationCode,
importCredentials,
importF12Credentials,
parseHeadersOrCurl,
refreshAccountCorporations,
@@ -14,7 +15,7 @@ import {
} from "../../core/auth/account-store.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.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 };
}
const summary = printKeyValue({
const pairs: Record<string, unknown> = {
"当前活跃账号": activeAccount?.accountId || "未登录",
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
"当前员工工号": currentCorp?.credentials.staffId || "-",
"凭证来源类型": currentCorp?.source || "-",
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
"凭证来源类型": formatSourceLabel(currentCorp?.source),
"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 {
stdout: `====== 当前登录与企业状态 ======\n${summary}\n`,
@@ -209,7 +238,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
let name = stringOption(parsed.options, ["name"]);
if (!raw && !accessToken) {
raw = await prompt("请粘贴 F12 抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
raw = await prompt("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
}
if (raw) {
@@ -227,7 +256,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
}
const imported = await importF12Credentials({
const imported = await importCredentials({
accessToken,
corpId,
staffId,
@@ -238,8 +267,30 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
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 {
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: "",
exitCode: 0,
};
+201
View File
@@ -0,0 +1,201 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { stringOption, numberOption } from "../parser.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import {
searchAndFormatBills,
getBillByCodeOrId,
getFieldDictionary,
} from "../../domains/bill/tools.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。"
);
}
const client = await createEkbClient(corp);
const action = parsed.action?.toLowerCase();
const corpId = corp.corpId || corp.id;
switch (action) {
case "list":
case "search":
case undefined: {
const code = stringOption(parsed.options, ["code", "c"]);
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
const stage = stringOption(parsed.options, ["stage"]);
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const result = await searchAndFormatBills(client, corpId, {
code,
keyword,
stage,
state,
count,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
total: result.total,
returned: result.returned,
items: result.items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
const rows = result.items.map((b, idx) => [
idx + 1,
b.billCode,
b.billName,
b.stage || "-",
b.state || "-",
b.amount || "-",
b.submitDate || b.createTime || "-",
]);
const tableOutput = printTable(headers, rows);
const title = `====== 单据与费用明细列表 (企业: ${corp.name} | 总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
return {
stdout: title + tableOutput + tip,
stderr: "",
exitCode: 0,
};
}
case "get":
case "show":
case "find": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
}
const bills = await getBillByCodeOrId(client, corpId, target);
if (bills.length === 0) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
count: bills.length,
bills,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const outputs: string[] = [];
for (let i = 0; i < bills.length; i++) {
const b = bills[i];
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
outputs.push(` 单据 ID : ${b.billId}`);
outputs.push(` 单据名称 : ${b.billName}`);
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
outputs.push(` 创建时间 : ${b.createTime}`);
outputs.push(` 更新时间 : ${b.updateTime}`);
outputs.push(`\n --- 结构化表单字段明细 ---`);
const detailEntries = Object.entries(b.details);
if (detailEntries.length === 0) {
outputs.push(` (无额外字段数据)`);
} else {
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
for (const [k, v] of detailEntries) {
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
}
}
}
return {
stdout: outputs.join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
case "schema":
case "schemas":
case "entities": {
const { entities } = await getFieldDictionary(client, corpId, true);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
totalEntities: entities.length,
entities,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
const rows = entities.map((e, idx) => [
idx + 1,
e.id,
e.name || "-",
e.type || "-",
e.fields.length,
]);
const tableOutput = printTable(headers, rows);
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
return {
stdout: title + tableOutput + "\n",
stderr: "",
exitCode: 0,
};
}
default:
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, schema`);
}
}
+48 -1
View File
@@ -2,6 +2,9 @@ import {
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
resolveEnterprisesDirs,
resolveWritableEnterprisesDir,
getEnterprisesDirCandidates,
} from "../../core/config/loader.js";
import { printJson, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -17,6 +20,10 @@ export async function handleConfigCommand(
case "get":
case "list":
return handleShow(parsed, runtime);
case "paths":
case "path":
case "dirs":
return handlePaths(parsed, runtime);
case "mode":
return handleMode(parsed, runtime);
case "set":
@@ -24,7 +31,7 @@ export async function handleConfigCommand(
default:
return {
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,
};
}
@@ -125,3 +132,43 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
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
View File
@@ -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";
export async function handleCorpsCommand(
@@ -29,10 +29,13 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
if (runtime.jsonMode) {
return {
stdout: printJson({
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
}),
stdout: printJson(
{
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
@@ -48,11 +51,12 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
c.name,
c.staffId,
c.source || "manual",
formatExpiresAt(c.expiresAt),
c.accountId || "-",
]);
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "来源", "所属账号"],
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
rows
);
@@ -80,7 +84,7 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
const current = runtime.corpContext.getCurrent();
if (runtime.jsonMode) {
return { stdout: printJson(current), stderr: "", exitCode: 0 };
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
@@ -97,17 +101,45 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
}
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,
"企业名称": current.name,
"员工工号": 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.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 {
stdout: `====== 当前激活企业 ======\n${output}\n`,
+111
View File
@@ -0,0 +1,111 @@
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core/embedded-openapi.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleOpenApiCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const isRaw =
booleanOption(parsed.options, ["raw"]) ||
parsed.action === "raw" ||
parsed.args[0] === "raw";
const type: OpenApiType = isRaw ? "raw" : "wrapped";
const action = parsed.action?.toLowerCase();
switch (action) {
case "paths":
case "list":
case "ls": {
const paths = listOpenApiPaths(type);
if (runtime.jsonMode) {
return {
stdout: printJson({ type, count: paths.length, paths }),
stderr: "",
exitCode: 0,
};
}
const rows = paths.map((p) => [
p.method,
p.path,
p.summary || "-",
p.tags.join(", ") || "-",
]);
const table = printTable(["Method", "Path", "Summary", "Tags"], rows);
const title = isRaw
? "====== 合思/易快报 原生下游 OpenAPI 接口列表 ======"
: "====== hose-use 包装层 OpenAPI 接口列表 ======";
return {
stdout: `${title}\n\n${table}\n\n提示: 运行 hose-use openapi ${isRaw ? "--raw " : ""}可直接输出完整 OpenAPI 3.1.0 JSON\n`,
stderr: "",
exitCode: 0,
};
}
case "info":
case "summary": {
const schema = getOpenApiSchema(type);
const info = (schema.info as Record<string, unknown>) || {};
const servers = ((schema.servers as Array<{ url: string; description?: string }>) || []).map(
(s) => `${s.url} (${s.description || "-"})`
);
const tags = ((schema.tags as Array<{ name: string; description?: string }>) || []).map(
(t) => `${t.name}: ${t.description || ""}`
);
const paths = listOpenApiPaths(type);
const infoObj = {
title: info.title,
version: info.version,
description: info.description,
type,
totalEndpoints: paths.length,
servers,
tags,
};
if (runtime.jsonMode) {
return {
stdout: printJson(infoObj),
stderr: "",
exitCode: 0,
};
}
const out = printKeyValue({
"规范标题": info.title,
"规范版本": info.version,
"规范类型": isRaw ? "原始下游原生 API (Raw Spec)" : "包装层工具 API (Wrapped Spec)",
"接口总数": paths.length,
"描述信息": info.description,
"服务器列表": servers.join("\n "),
"标签分组": tags.join("\n "),
});
return {
stdout: `====== OpenAPI 规范概览 ======\n${out}\n`,
stderr: "",
exitCode: 0,
};
}
case "dump":
case "export":
case "raw":
case undefined:
default: {
const schema = getOpenApiSchema(type);
return {
stdout: `${JSON.stringify(schema, null, 2)}\n`,
stderr: "",
exitCode: 0,
};
}
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
if (runtime.jsonMode) {
return { stdout: printJson(platforms), stderr: "", exitCode: 0 };
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (platforms.length === 0) {
+15 -3
View File
@@ -1,6 +1,6 @@
import { createClientsForCorp } from "../helpers.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";
export async function handleProbeCommand(
@@ -79,14 +79,26 @@ export async function handleProbeCommand(
return { stdout: printJson(results), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
const probePairs: Record<string, unknown> = {
"企业名称": currentCorp.name,
"企业 ID": currentCorp.id,
"员工工号": 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" ? "🟢 正常" : "🔴 异常",
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
"自建应用扫描": (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 {
stdout: `====== 诊断结果 (Enterprise Probe) ======\n${summary}\n`,
+4 -4
View File
@@ -54,7 +54,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
const result = await listAllWorkflows(clients, { page, pageSize });
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 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);
if (runtime.jsonMode) {
return { stdout: printJson(detail), stderr: "", exitCode: 0 };
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
@@ -148,7 +148,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
});
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 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);
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
+5 -3
View File
@@ -1,10 +1,10 @@
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 { CorpConfig } from "../core/config/types.js";
import { createEkbClient } from "../core/auth/ekb.js";
import { getEasoClient } from "../core/auth/easo.js";
import { CliRuntime } from "./types.js";
import { CliRuntime, OutputOptions } from "./types.js";
export function initCorpRuntime(
options: {
@@ -12,6 +12,7 @@ export function initCorpRuntime(
stateless?: boolean;
stateful?: boolean;
jsonMode?: boolean;
outputOptions?: OutputOptions;
} = {}
): CliRuntime {
const corps = loadCorpConfigs();
@@ -31,7 +32,7 @@ export function initCorpRuntime(
let selectedCorp: CorpConfig | null = null;
try {
selectedCorp = corpContext.resolve(options.corpId);
selectedCorp = corpContext.resolve(options.corpId, getEnterprisesDirCandidates());
} catch {
selectedCorp = null;
}
@@ -40,6 +41,7 @@ export function initCorpRuntime(
corpContext,
selectedCorp,
jsonMode: options.jsonMode ?? false,
outputOptions: options.outputOptions,
};
}
+54 -7
View File
@@ -1,4 +1,29 @@
import type { CliParsedArgs } from "./types.js";
import type { CliParsedArgs, OutputOptions } from "./types.js";
const KNOWN_BOOLEAN_FLAGS = new Set([
"raw",
"json",
"j",
"help",
"h",
"version",
"v",
"force",
"f",
"stateless",
"stateful",
"check",
"check-only",
"changelog",
"log",
"local",
"workspace",
"external",
"full",
"allow-full",
"allowFull",
"summary",
]);
export function parseArgs(rawArgs: string[]): CliParsedArgs {
const options: Record<string, string | boolean | number> = {};
@@ -20,12 +45,16 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
options[key] = val;
} else {
const key = arg.slice(2);
const next = rawArgs[i + 1];
if (next && !next.startsWith("-")) {
options[key] = next;
i++;
} else {
if (KNOWN_BOOLEAN_FLAGS.has(key)) {
options[key] = true;
} else {
const next = rawArgs[i + 1];
if (next && !next.startsWith("-")) {
options[key] = next;
i++;
} else {
options[key] = true;
}
}
}
continue;
@@ -36,7 +65,17 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
if (flag === "h") options.help = true;
else if (flag === "j") options.json = 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;
}
@@ -96,3 +135,11 @@ export function numberOption(
}
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"]),
};
}
+108
View File
@@ -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");
});
});
});
+89 -8
View File
@@ -1,7 +1,78 @@
import { writeFileSync } from "node:fs";
import { VERSION } from "../version.js";
import type { OutputOptions } from "./types.js";
export function printJson(data: unknown): string {
return JSON.stringify(data, null, 2);
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
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 {
@@ -46,33 +117,43 @@ export function printHelp(): string {
核心命令域:
auth 认证与凭证管理 (login, status, refresh, import, accounts)
corps 多企业租户管理 (list, switch, current)
config 全局运行模式 (show, mode <stateful|stateless>, set)
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
workflow 工作流管理 (list, get, find, toggle)
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
platform 自建应用管理 (list)
skill Agent Skill 管理 (install, status, dump)
probe 连通性诊断 (probe [corpId])
update 版本自更新与发布记录 (update, update check, update --changelog)
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
mcp MCP Server 运行 (serve)
version 查看版本信息
全局选项:
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--help, -h 查看帮助信息
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--help, -h 查看帮助信息
常用示例:
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
hose-use auth status # 查看当前登录状态与活跃企业
hose-use config paths # 查看多级企业配置目录链
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use corps list # 列出名下所有企业
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
hose-use workflow list # 汇总查看全部工作流
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
hose-use bill list # 查看当前企业单据与报销列表
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
hose-use probe # 诊断当前企业鉴权连通性
hose-use skill install # 安装 Agent 技能到用户目录
hose-use update # 自动检查并升级到最新版本
hose-use update --changelog # 查看版本发布历史
hose-use openapi paths # 查看所有 API 路径与概要一览
hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范
`.trim();
}
+64 -4
View File
@@ -1,6 +1,6 @@
import { VERSION } from "../version.js";
import { parseArgs, stringOption, booleanOption } from "./parser.js";
import { printHelp, printJson } from "./printer.js";
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
import { initCorpRuntime } from "./helpers.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleCorpsCommand } from "./commands/corps.js";
@@ -11,9 +11,56 @@ import { handleSkillCommand } from "./commands/skill.js";
import { handleProbeCommand } from "./commands/probe.js";
import { handleMcpCommand } from "./commands/mcp.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleOpenApiCommand } from "./commands/openapi.js";
import { handleBillCommand } from "./commands/bill.js";
import type { CliResult, CliRunOptions } from "./types.js";
export async function runCli(
let runQueue = Promise.resolve<any>(undefined);
export function runCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
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[],
options: CliRunOptions = {}
): Promise<CliResult> {
@@ -31,12 +78,14 @@ export async function runCli(
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
const statelessOption = booleanOption(parsed.options, ["stateless"]);
const statefulOption = booleanOption(parsed.options, ["stateful"]);
const outputOpts = outputOptions(parsed.options);
const runtime = initCorpRuntime({
corpId: corpIdOption,
stateless: statelessOption,
stateful: statefulOption,
jsonMode,
outputOptions: outputOpts,
});
try {
@@ -54,6 +103,13 @@ export async function runCli(
case "workflows":
case "wf":
return await handleWorkflowCommand(parsed, runtime);
case "bill":
case "bills":
case "fee":
case "fees":
case "invoice":
case "invoices":
return await handleBillCommand(parsed, runtime);
case "platform":
case "platforms":
case "app":
@@ -70,6 +126,10 @@ export async function runCli(
case "self-update":
case "changelog":
return await handleUpdateCommand(parsed, runtime, options);
case "openapi":
case "schema":
case "spec":
return await handleOpenApiCommand(parsed, runtime);
case "mcp":
case "serve":
return await handleMcpCommand(parsed, options);
@@ -83,7 +143,7 @@ export async function runCli(
};
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
if (jsonMode) {
return {
stdout: printJson({ error: true, message: errorMsg }),
+7
View File
@@ -21,8 +21,15 @@ export interface CliResult {
exitCode: number;
}
export interface OutputOptions {
allowFull?: boolean;
outputFile?: string;
summary?: boolean;
}
export interface CliRuntime {
corpContext: CorpContext;
selectedCorp: CorpConfig | null;
jsonMode: boolean;
outputOptions?: OutputOptions;
}
+148 -7
View File
@@ -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;
}
/**
* 校验并导入单个 F12 抓包/手动凭证,保存到企业配置
* 校验并导入单个抓包/手动凭证,自动探测官方 Session 平台类型并保存到企业配置
*/
export async function importF12Credentials(
export async function importCredentials(
params: F12ImportParams
): Promise<CorpConfig> {
const { accessToken, corpId, staffId } = params;
@@ -279,8 +301,25 @@ export async function importF12Credentials(
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
}
// 验证凭证有效性并尝试自动获取企业名称
let corpName = params.name;
// 1. 验证凭证有效性并提取官方服务端 Session 元数据
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 {
const res = await ky
.get(`${baseUrl}/api/account/v2/session`, {
@@ -290,20 +329,102 @@ export async function importF12Credentials(
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");
}
} catch (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 = {
id: corpId,
name: corpName || `企业-${corpId}`,
baseUrl,
source: "f12",
source,
staffName,
credentials: {
accessToken,
corpId,
@@ -311,6 +432,23 @@ export async function importF12Credentials(
},
auth: {
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;
}
// 保持历史命名兼容
export const importF12Credentials = importCredentials;
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
/**
+143
View File
@@ -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
View File
@@ -1,30 +1,96 @@
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { homedir } from "os";
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "./enterprises";
const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json");
const ENTERPRISES_DIR = "enterprises";
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 {
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 {
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 {
const file = resolveGlobalConfigFile();
try {
const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
return GlobalConfigSchema.parse(JSON.parse(content));
if (existsSync(file)) {
const content = readFileSync(file, "utf-8");
return GlobalConfigSchema.parse(JSON.parse(content));
}
} catch {
return {
stateful: true,
defaultCorpId: undefined,
defaultAccountId: undefined,
};
// 容错返回默认
}
return {
stateful: true,
defaultCorpId: undefined,
defaultAccountId: undefined,
};
}
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
@@ -33,50 +99,61 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
...current,
...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;
}
export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] {
let files: string[];
try {
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 [];
}
export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs();
const byId = new Map<string, CorpConfig>();
const configs: CorpConfig[] = [];
for (const file of files) {
for (const dir of dirs) {
try {
const content = readFileSync(join(dir, file), "utf-8");
const parsed = JSON.parse(content);
configs.push(CorpConfigSchema.parse(parsed));
const files = readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.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) {
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 {
ensureDir(dir);
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
const targetDir = dir || resolveWritableEnterprisesDir();
ensureDir(targetDir);
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");
return filePath;
}
export function saveMultipleCorpConfigs(
configs: CorpConfig[],
dir: string = ENTERPRISES_DIR
dir?: string
): string[] {
return configs.map((config) => saveCorpConfig(config, dir));
}
+16 -8
View File
@@ -9,6 +9,7 @@ export interface CorpSummary {
staffId: string;
baseUrl?: string;
current: boolean;
expiresAt?: number;
}
export function resolveCorpConfig(
@@ -17,7 +18,8 @@ export function resolveCorpConfig(
stateful: boolean;
defaultCorpId?: string;
corpId?: string;
}
},
candidateDirs?: string[]
): CorpConfig {
const requestedCorpId = options.corpId?.trim() || undefined;
const configuredCorpId = options.stateful
@@ -50,7 +52,8 @@ export function resolveCorpConfig(
const firstCorp = corps[0];
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 {
@@ -109,12 +112,16 @@ export class CorpContext {
return this.corps.get(corpId);
}
resolve(corpId?: string): CorpConfig {
return resolveCorpConfig(Array.from(this.corps.values()), {
stateful: this.stateful,
defaultCorpId: this.defaultCorpId,
corpId,
});
resolve(corpId?: string, candidateDirs?: string[]): CorpConfig {
return resolveCorpConfig(
Array.from(this.corps.values()),
{
stateful: this.stateful,
defaultCorpId: this.defaultCorpId,
corpId,
},
candidateDirs
);
}
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
@@ -145,6 +152,7 @@ export class CorpContext {
staffId: corp.credentials.staffId,
baseUrl: corp.baseUrl,
current: corp.id === this.current?.id,
expiresAt: corp.auth?.expiresAt || corp.session?.expTime,
}));
}
}
+29 -2
View File
@@ -1,6 +1,13 @@
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 const CorpCredentialsSchema = z.object({
@@ -15,17 +22,37 @@ export const CorpAuthConfigSchema = z.object({
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({
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
name: z.string().describe("企业名称"),
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
userId: z.string().optional().describe("所属用户 ID"),
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
staffName: z.string().optional().describe("员工真实姓名"),
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("所属主账号标识(如手机号)"),
credentials: CorpCredentialsSchema,
auth: CorpAuthConfigSchema.optional(),
session: CorpSessionInfoSchema.optional().describe("官方服务端 Session 与操作人元数据"),
});
export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, test } from "bun:test";
import { getOpenApiSchema, listOpenApiPaths } from "./embedded-openapi.js";
describe("embedded OpenAPI", () => {
test("wrapped OpenAPI contains paths and components", () => {
const wrapped = getOpenApiSchema("wrapped");
expect(wrapped.openapi).toBe("3.1.0");
expect(wrapped.info).toBeDefined();
expect(wrapped.paths).toBeDefined();
expect(Object.keys(wrapped.paths as object).length).toBeGreaterThan(0);
const paths = listOpenApiPaths("wrapped");
expect(paths.length).toBeGreaterThan(0);
expect(paths.some((p) => p.path === "/api/auth/login")).toBe(true);
expect(paths.some((p) => p.path === "/api/workflows")).toBe(true);
});
test("raw downstream OpenAPI contains downstream paths", () => {
const raw = getOpenApiSchema("raw");
expect(raw.openapi).toBe("3.1.0");
expect(raw.info).toBeDefined();
expect(raw.paths).toBeDefined();
expect(Object.keys(raw.paths as object).length).toBeGreaterThan(0);
const paths = listOpenApiPaths("raw");
expect(paths.length).toBeGreaterThan(0);
expect(paths.some((p) => p.path === "/api/common/security/getPublicKey")).toBe(true);
expect(paths.some((p) => p.path === "/api/open/oauth2/token")).toBe(true);
expect(paths.some((p) => p.path === "/api/easo/pipelines/logs")).toBe(true);
});
});
+38
View File
@@ -0,0 +1,38 @@
import wrappedOpenApi from "../../dist/openapi.json" with { type: "json" };
import rawOpenApi from "../../dist/raw-hose-openapi.json" with { type: "json" };
export type OpenApiType = "wrapped" | "raw";
export function getOpenApiSchema(type: OpenApiType = "wrapped"): Record<string, unknown> {
if (type === "raw") {
return rawOpenApi as Record<string, unknown>;
}
return wrappedOpenApi as Record<string, unknown>;
}
export function listOpenApiPaths(type: OpenApiType = "wrapped"): Array<{
path: string;
method: string;
summary: string;
tags: string[];
}> {
const schema = getOpenApiSchema(type);
const paths = (schema.paths as Record<string, Record<string, any>>) || {};
const results: Array<{ path: string; method: string; summary: string; tags: string[] }> = [];
for (const [pathKey, methods] of Object.entries(paths)) {
if (typeof methods !== "object" || methods === null) continue;
for (const [method, def] of Object.entries(methods)) {
if (["get", "post", "put", "delete", "patch"].includes(method.toLowerCase()) && typeof def === "object") {
results.push({
path: pathKey,
method: method.toUpperCase(),
summary: def.summary || def.description || "",
tags: def.tags || [],
});
}
}
}
return results;
}
+1
View File
@@ -7,6 +7,7 @@
| 域 | 说明 | 详细文档 |
|---|---|---|
| `platform/` | 自建应用(DataLink Platform)与工作流(EASO/Piper) | [README.platform.md](./platform/README.platform.md) |
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
## 分层规则
+24
View File
@@ -0,0 +1,24 @@
# Bill 域说明
本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票与数据实体元数据字典的检索与格式化。
## 文件结构
```text
src/domains/bill/
├── api.ts # 传输层:调用 /api/v2/invoice/search, /api/v2/invoice, /api/v2/datalink/entity/search
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与 MCP tools
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
├── bill.test.ts # 单元测试
└── README.bill.md # 本说明文件
```
## 核心能力
1. **单据检索与分页 (`searchAndFormatBills`)**:
- 跨单据池查询费用明细、报销单、借款单与发票。
- 支持按单号(`code`)、阶段(`stage`)、状态(`state`)、关键字(`keyword`)过滤。
2. **按单号/ID 精确查询 (`getBillByCodeOrId`)**:
- 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。
3. **DataLink 字段元数据字典 (`getFieldDictionary`)**:
- 自动拉取企业全部实体模型定义,将混淆代码字段(如 `E_ae10..._payMoney`)还原为人类友好的中文字段名(如 `报销金额`)。
+71
View File
@@ -0,0 +1,71 @@
import { KyInstance } from "ky";
import {
RawBillSearchResponseSchema,
RawBillBatchGetResponseSchema,
EntityListResponseSchema,
type RawBillSearchResponse,
type RawBillItem,
type EntityMeta,
} from "./types.js";
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
export async function searchRawBills(
client: KyInstance,
corpId: string,
options: { start?: number; count?: number } = {}
): Promise<RawBillSearchResponse> {
const response = await client.post("api/v2/invoice/search", {
searchParams: { corporationId: corpId, corpId },
json: {
limit: {
start: options.start ?? 0,
count: options.count ?? 50,
},
},
});
const json = await response.json();
return RawBillSearchResponseSchema.parse(json);
}
// ── 按 ID 列表精确拉取单据详情 API ─────────────────────────────────────────────
export async function getRawBillsByIds(
client: KyInstance,
corpId: string,
ids: string[]
): Promise<RawBillItem[]> {
if (ids.length === 0) return [];
const response = await client.post("api/v2/invoice", {
searchParams: { corporationId: corpId, corpId },
json: { ids },
});
const json = await response.json();
const parsed = RawBillBatchGetResponseSchema.parse(json);
return parsed.items;
}
// ── 单据实体与字段元数据字典 API ───────────────────────────────────────────────
export async function listEntitySchemas(
client: KyInstance,
corpId: string,
options: { start?: number; count?: number } = {}
): Promise<EntityMeta[]> {
const response = await client.post("api/v2/datalink/entity/search", {
searchParams: { corporationId: corpId, corpId },
json: {
limit: {
start: options.start ?? 0,
count: options.count ?? 100,
},
},
});
const json = await response.json();
const parsed = EntityListResponseSchema.parse(json);
return parsed.items;
}
+69
View File
@@ -0,0 +1,69 @@
import { describe, it, expect } from "bun:test";
import { formatSingleBill } from "./tools.js";
import { RawBillItemSchema, EntitySchema } from "./types.js";
describe("Bill Domain", () => {
it("validates EntitySchema", () => {
const rawEntity = {
id: "ae1037940b1c304017c0",
code: "FEE_DETAIL",
name: "费用明细",
type: "EXPENSE",
active: true,
fields: [
{
name: "E_ae1037940b1c304017c0_payMoney",
type: "money",
label: "支付金额",
optional: false,
formula: false,
},
],
};
const parsed = EntitySchema.parse(rawEntity);
expect(parsed.id).toBe("ae1037940b1c304017c0");
expect(parsed.fields[0].label).toBe("支付金额");
});
it("validates RawBillItemSchema and formats fields with dictionary", () => {
const rawBill = {
id: "ID01TRzg7HMLcb",
code: "n0GMIM0dkQmKbS",
name: "项目&100",
corporationId: "ID01ofWoOC1wiX",
ownerId: "ID01ofWoOC1wiX:ID01ojZ2n2e0PR",
createTime: 1781682826000,
updateTime: 1781682870000,
form: {
E_test_code: "n0GMIM0dkQmKbS",
E_test_title: "测试单据标题",
E_test_stage: "expense",
E_test_state: "paid",
E_test_amount: {
standard: "100.00",
standardUnit: "元",
standardSymbol: "¥",
standardStrCode: "CNY",
},
E_test_submitterId: "staff-123",
E_test_customField: "VIP客户",
},
};
const parsed = RawBillItemSchema.parse(rawBill);
expect(parsed.id).toBe("ID01TRzg7HMLcb");
const dict = new Map<string, { label: string; type: string }>();
dict.set("E_test_customField", { label: "客户等级", type: "text" });
const formatted = formatSingleBill(parsed, dict);
expect(formatted.billId).toBe("ID01TRzg7HMLcb");
expect(formatted.billCode).toBe("n0GMIM0dkQmKbS");
expect(formatted.title).toBe("测试单据标题");
expect(formatted.stage).toBe("expense");
expect(formatted.state).toBe("paid");
expect(formatted.amount).toBe("¥100.00 CNY");
expect(formatted.details["客户等级"]).toBe("VIP客户");
});
});
+382
View File
@@ -0,0 +1,382 @@
import { z } from "zod";
import { KyInstance } from "ky";
import { searchRawBills, getRawBillsByIds, listEntitySchemas } from "./api.js";
import {
type RawBillItem,
type FormattedBill,
type BillPageResult,
type EntityMeta,
type BillQueryParams,
} from "./types.js";
import { CorpContext } from "../../core/config/manager.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 CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
export async function getFieldDictionary(
client: KyInstance,
corpId: string,
forceRefresh = false
): Promise<{ dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }> {
const cached = schemaCache.get(corpId);
if (!forceRefresh && cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached;
}
const entities = await listEntitySchemas(client, corpId, { start: 0, count: 100 });
const dictionary = new Map<string, { label: string; type: string }>();
for (const entity of entities) {
for (const field of entity.fields) {
if (field.name && field.label) {
dictionary.set(field.name, { label: field.label, type: field.type });
}
}
}
const result = { timestamp: Date.now(), dictionary, entities };
schemaCache.set(corpId, result);
return result;
}
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
export function formatSingleBill(
item: RawBillItem,
dictionary: Map<string, { label: string; type: string }>
): FormattedBill {
const rawForm = item.form || {};
let billCode = item.code || "";
let billName = item.name || "";
let title: string | undefined;
let stage: string | undefined;
let state: string | undefined;
let amountStr: string | undefined;
let submitterId: string | undefined;
let submitDateStr: string | undefined;
const readableDetails: Record<string, any> = {};
for (const [k, v] of Object.entries(rawForm)) {
if (v === null || v === undefined || v === "") continue;
// 提取核心通用业务字段
if (k.endsWith("_code") && typeof v === "string") billCode = billCode || v;
if (k.endsWith("_title") && typeof v === "string") title = v;
if (k.endsWith("_stage") && typeof v === "string") stage = v;
if (k.endsWith("_state") && typeof v === "string") state = v;
if (k.endsWith("_submitterId") && typeof v === "string") submitterId = v;
// 格式化金额
if (k.endsWith("_amount") || k.endsWith("_expenseMoney") || k.endsWith("_payMoney")) {
if (typeof v === "object" && v !== null && (v as any).standard) {
const money = v as any;
const formatted = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
if (!amountStr || k.endsWith("_amount")) {
amountStr = formatted;
}
}
}
// 格式化提交时间
if (k.endsWith("_submitDate") && typeof v === "number" && v > 1000000000000) {
submitDateStr = new Date(v).toLocaleString("zh-CN");
}
// 字典 Label 还原
const meta = dictionary.get(k);
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
let readableKey = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || bareKey);
// 格式化字段值
let formattedVal = v;
if (typeof v === "number" && v > 1000000000000 && v < 2500000000000 && !k.endsWith("_code") && !k.endsWith("_No")) {
formattedVal = `${new Date(v).toLocaleString("zh-CN")}`;
} else if (typeof v === "object" && v !== null && (v as any).standard) {
const money = v as any;
formattedVal = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
}
readableDetails[readableKey] = formattedVal;
}
const createTimeStr = item.createTime > 0
? new Date(item.createTime).toLocaleString("zh-CN")
: "";
const updateTimeStr = item.updateTime > 0
? new Date(item.updateTime).toLocaleString("zh-CN")
: "";
return {
billId: item.id,
billCode: billCode || item.id,
billName: billName || item.id,
title,
stage,
state,
amount: amountStr,
submitterId,
submitDate: submitDateStr,
corporationId: item.corporationId || "",
ownerId: item.ownerId || "",
createTime: createTimeStr,
updateTime: updateTimeStr,
details: readableDetails,
};
}
// ── 业务操作:按单号或 ID 精确查询单据 ─────────────────────────────────────────
export async function getBillByCodeOrId(
client: KyInstance,
corpId: string,
queryCodeOrId: string
): Promise<FormattedBill[]> {
const cleanQuery = queryCodeOrId.trim();
if (!cleanQuery) return [];
const { dictionary } = await getFieldDictionary(client, corpId);
// 1. 如果传入的是 ID 格式(如 ID01...),先尝试走精准 ID 批量接口
if (cleanQuery.startsWith("ID01")) {
try {
const items = await getRawBillsByIds(client, corpId, [cleanQuery]);
if (items.length > 0) {
return items.map((it) => formatSingleBill(it, dictionary));
}
} catch {
// 忽略错误,继续回退到 search 检索
}
}
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50 });
const matched = searchRes.items.filter((item) => {
if (item.id === cleanQuery) return true;
if (item.code === cleanQuery) return true;
for (const [k, v] of Object.entries(item.form || {})) {
if (typeof v === "string" && v.trim() === cleanQuery) {
if (k.endsWith("_code") || k.endsWith("_flowCode") || k.endsWith("_linkId") || k.endsWith("_detailId")) {
return true;
}
}
}
return false;
});
return matched.map((it) => formatSingleBill(it, dictionary));
}
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
export async function searchAndFormatBills(
client: KyInstance,
corpId: string,
params: BillQueryParams = {}
): Promise<BillPageResult> {
const { dictionary } = await getFieldDictionary(client, corpId);
const searchRes = await searchRawBills(client, corpId, {
start: params.start ?? 0,
count: params.count ?? 50,
});
let filtered = searchRes.items;
// 客户端辅助精确过滤
if (params.code) {
const target = params.code.trim();
filtered = filtered.filter((it) => {
if (it.code === target) return true;
for (const [k, v] of Object.entries(it.form || {})) {
if (k.endsWith("_code") && v === target) return true;
if (k.endsWith("_flowCode") && v === target) return true;
}
return false;
});
}
if (params.id) {
const target = params.id.trim();
filtered = filtered.filter((it) => it.id === target);
}
if (params.stage) {
const target = params.stage.trim().toLowerCase();
filtered = filtered.filter((it) => {
for (const [k, v] of Object.entries(it.form || {})) {
if (k.endsWith("_stage") && String(v).toLowerCase() === target) return true;
}
return false;
});
}
if (params.state) {
const target = params.state.trim().toLowerCase();
filtered = filtered.filter((it) => {
for (const [k, v] of Object.entries(it.form || {})) {
if (k.endsWith("_state") && String(v).toLowerCase() === target) return true;
}
return false;
});
}
if (params.keyword) {
const kw = params.keyword.trim().toLowerCase();
filtered = filtered.filter((it) => {
if (it.name?.toLowerCase().includes(kw)) return true;
if (it.code?.toLowerCase().includes(kw)) return true;
for (const v of Object.values(it.form || {})) {
if (typeof v === "string" && v.toLowerCase().includes(kw)) return true;
}
return false;
});
}
const formattedItems = filtered.map((it) => formatSingleBill(it, dictionary));
return {
total: searchRes.count,
returned: formattedItems.length,
items: formattedItems,
};
}
// ── MCP Tools 适配 ────────────────────────────────────────────────────────────
export const billTools = [
{
name: "bill_search",
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称)",
parameters: z.object({
code: z.string().optional().describe("按单据编号/单号过滤(如 jO1it3cIufDjNS)"),
keyword: z.string().optional().describe("按关键字模糊搜索标题、名称或内容"),
stage: z.string().optional().describe("按阶段过滤(如 expense 报销, loan 借款, payment 付款)"),
state: z.string().optional().describe("按审批/支付状态过滤(如 paid 已支付, approving 审批中, draft 草稿)"),
count: z.number().optional().default(20).describe("拉取记录数"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { code?: string; keyword?: string; stage?: string; state?: string; count?: number }
) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createEkbClient(corp);
const result = await searchAndFormatBills(client, corp.corpId || corp.id, params);
return {
corpId: corp.corpId || corp.id,
corpName: corp.name,
...result,
};
},
},
{
name: "bill_get",
description: "根据单据编号(单号)或单据 ID 精确查询单据详细信息与格式化表单明细",
parameters: z.object({
code: z.string().describe("单据编号(如 jO1it3cIufDjNS)或 单据 ID(如 ID01V0zDDjZNHp)"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { code: string }
) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createEkbClient(corp);
const bills = await getBillByCodeOrId(client, corp.corpId || corp.id, params.code);
if (bills.length === 0) {
return {
found: false,
message: `未找到单号或 ID 为 [${params.code}] 的单据`,
code: params.code,
};
}
return {
found: true,
count: bills.length,
bills,
};
},
},
{
name: "bill_schema",
description: "获取企业全部单据实体的数据模型、表单定义与中文字段 Label 字典",
parameters: z.object({}),
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createEkbClient(corp);
const { entities } = await getFieldDictionary(client, corp.corpId || corp.id, true);
return {
corpId: corp.corpId || corp.id,
totalEntities: entities.length,
entities: entities.map((e) => ({
id: e.id,
name: e.name,
type: e.type,
fieldCount: e.fields.length,
fields: e.fields.map((f) => ({
name: f.name,
label: f.label,
type: f.type,
})),
})),
};
},
},
];
+105
View File
@@ -0,0 +1,105 @@
import { z } from "zod";
// ── 字段元数据(DataLink Field Meta)──────────────────────────────────────────
export const FieldMetaSchema = z.object({
name: z.string(),
type: z.string().default("text"),
label: z.string().default(""),
regex: z.string().optional().default(""),
source: z.string().optional().default("dataLink"),
formula: z.boolean().optional().default(false),
optional: z.boolean().optional().default(true),
calculation: z.record(z.string(), z.any()).optional(),
});
export const EntitySchema = z.object({
id: z.string(),
code: z.string().optional().default(""),
name: z.string().default(""),
type: z.string().default(""),
active: z.boolean().default(true),
fields: z.array(FieldMetaSchema).default([]),
});
export const EntityListResponseSchema = z.object({
items: z.array(EntitySchema).default([]),
});
// ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)─────────────────────
export const RawBillMoneySchema = z.object({
standard: z.string().or(z.number()).transform((v) => String(v)),
standardUnit: z.string().optional().default("元"),
standardScale: z.number().optional().default(2),
standardSymbol: z.string().optional().default("¥"),
standardNumCode: z.string().optional().default("156"),
standardStrCode: z.string().optional().default("CNY"),
});
export const RawBillItemSchema = z.object({
id: z.string(),
code: z.string().default(""),
name: z.string().default(""),
entityId: z.string().optional().default(""),
active: z.boolean().optional().default(true),
ownerId: z.string().optional().default(""),
corporationId: z.string().optional().default(""),
createTime: z.number().default(0),
updateTime: z.number().default(0),
form: z.record(z.string(), z.any()).default({}),
});
export const RawBillSearchResponseSchema = z.object({
count: z.number().default(0),
items: z.array(RawBillItemSchema).default([]),
});
export const RawBillBatchGetResponseSchema = z.object({
items: z.array(RawBillItemSchema).default([]),
});
// ── 格式化后的单据输出(Formatted Bill)───────────────────────────────────────
export const FormattedBillSchema = z.object({
billId: z.string(),
billCode: z.string(),
billName: z.string(),
title: z.string().optional(),
stage: z.string().optional(),
state: z.string().optional(),
amount: z.string().optional(),
submitterId: z.string().optional(),
submitDate: z.string().optional(),
corporationId: z.string(),
ownerId: z.string().optional(),
createTime: z.string(),
updateTime: z.string(),
details: z.record(z.string(), z.any()),
});
export const BillPageResultSchema = z.object({
total: z.number(),
returned: z.number(),
items: z.array(FormattedBillSchema),
});
// ── 类型导出 ──────────────────────────────────────────────────────────────────
export type FieldMeta = z.infer<typeof FieldMetaSchema>;
export type EntityMeta = z.infer<typeof EntitySchema>;
export type RawBillMoney = z.infer<typeof RawBillMoneySchema>;
export type RawBillItem = z.infer<typeof RawBillItemSchema>;
export type RawBillSearchResponse = z.infer<typeof RawBillSearchResponseSchema>;
export type FormattedBill = z.infer<typeof FormattedBillSchema>;
export type BillPageResult = z.infer<typeof BillPageResultSchema>;
export interface BillQueryParams {
code?: string;
id?: string;
keyword?: string;
stage?: string;
state?: string;
start?: number;
count?: number;
}
+156
View File
@@ -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()]);
}
});
});
+248 -25
View File
@@ -5,6 +5,8 @@ import {
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { loadCorpConfigs } from "./core/config/loader.js";
import { CorpContext } from "./core/config/manager.js";
import { createEkbClient } from "./core/auth/ekb.js";
@@ -12,6 +14,118 @@ import { getEasoClient } from "./core/auth/easo.js";
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
import { authTools } from "./core/auth/tools.js";
import { platformTools } from "./domains/platform/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): {
content: Array<{ type: "text"; text: string }>;
@@ -45,22 +159,19 @@ function formatError(error: unknown): {
};
}
console.error(error);
return {
content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }],
isError: true,
};
}
async function main() {
// 加载企业配置
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps);
export function createServer(options: { mode?: HoseMcpMode } = {}) {
const mode = options.mode ?? resolveMcpMode();
const server = new Server(
{
name: "ekb-mcp",
version: "0.1.0",
name: "hose-use",
version: VERSION,
},
{
capabilities: {
@@ -69,26 +180,89 @@ async function main() {
}
);
// 聚合所有工具
const allTools = [...authTools, ...platformTools];
const fineGrainedTools = [...authTools, ...platformTools, ...billTools];
// 注册工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: allTools.map((t) => ({
name: t.name,
description: t.description,
inputSchema: (t.parameters as any).toJSONSchema(),
})),
};
const tools: Array<{ name: string; description?: string; inputSchema: any }> = [];
// 单工具网关
if (mode === "single" || mode === "all") {
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) => {
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 {
// 1. 检查 Auth 工具
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps);
// Auth 工具
const authTool = authTools.find((t) => t.name === name);
if (authTool) {
const parsed = authTool.parameters.safeParse(args || {});
@@ -109,21 +283,41 @@ async function main() {
};
}
// 2. 检查 Domain 业务工具(需要当前企业上下文)
// Bill 工具
const billTool = billTools.find((t) => t.name === name);
if (billTool) {
const parsed = billTool.parameters.safeParse(args || {});
if (!parsed.success) {
return {
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
isError: true,
};
}
const result = await billTool.handler({ corpContext }, parsed.data as never);
return {
content: [
{
type: "text",
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
},
],
};
}
// Platform 业务工具
const currentCorp = corpContext.getCurrent();
if (!currentCorp) {
return {
content: [
{
type: "text",
text: "未配置企业,请先调用 import_f12_corp 导入凭证,或执行 bun run login 登录",
text: "未配置企业,请先调用 auth login 登录或 auth import 导入凭证",
},
],
isError: true,
};
}
// Platform 工具
const platformTool = platformTools.find((t) => t.name === name);
if (platformTool) {
const parsed = platformTool.parameters.safeParse(args || {});
@@ -153,7 +347,7 @@ async function main() {
content: [
{
type: "text",
text: `未知工具: ${name}`,
text: `未知工具: ${name}。在单工具网关模式下,请通过 ${HOSE_CLI_TOOL_NAME} 调用。`,
},
],
isError: true,
@@ -163,9 +357,38 @@ async function main() {
}
});
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("EKB MCP Server running on stdio");
return server;
}
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
View File
@@ -1 +1 @@
export const VERSION = "0.2.1";
export const VERSION = "0.4.2";