Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d532fc719 | ||
|
|
0c745fdb0c | ||
|
|
fd24e844b0 | ||
|
|
88c57558e1 | ||
|
|
fbdfbaa8d3 | ||
|
|
27c86e052a | ||
|
|
3864f0ffd0 | ||
|
|
5a0c277993 | ||
|
|
fb11fedb76 | ||
|
|
c15d622ba2 | ||
|
|
2b220bc5d9 | ||
|
|
2d744d283b | ||
|
|
76f7832522 | ||
|
|
c60d49fb8c | ||
|
|
d0af46b445 | ||
|
|
bd585db889 | ||
|
|
a0ec7f95a7 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.10",
|
||||
"version": "0.8.12",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -4,37 +4,44 @@
|
||||
|
||||
## 项目定位
|
||||
|
||||
合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 适配能力):
|
||||
合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 与本地 HTTP 网关适配能力):
|
||||
|
||||
- **CLI 工具 (`hose-use` / `hose-aipro`)**:面向运维/实施/开发者的高性能交互与自动化命令行
|
||||
- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务 API 与换票能力
|
||||
- **MCP Server (`src/server.ts`)**:精简核心适配器(保留核心切换与扫描能力)
|
||||
- **Agent Skill (`skills/hose-use`)**:内嵌 AI 智能体技能标准定义(支持 `hose-use skill install` 一键分发)
|
||||
- **CLI 工具 (`hose-use` / `hose-aipro`)**:面向运维/实施/开发者与 AI Agent 的高性能交互与确定性审批命令行
|
||||
- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务编排、API 传输、SQLite 持久化与换票能力
|
||||
- **MCP Server (`src/server.ts`)**:极简核心单工具网关(`hose_cli` -> `runCli`)
|
||||
- **本地 HTTP Daemon (`src/http/`)**:常驻 HTTP API 网关与交互式 OpenAPI 文档服务
|
||||
- **构建与分发内嵌层 (`src/packaging/`)**:OpenAPI 规范与 Agent Skill (`skills/hose-use`) 内嵌分发、二进制运行态自省
|
||||
|
||||
## 架构总览
|
||||
|
||||
```text
|
||||
CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
│ │
|
||||
└──────────┬─────────┘
|
||||
▼
|
||||
domains/ (业务编排与平台引擎)
|
||||
│
|
||||
▼
|
||||
core/ (认证、配置与 HTTP 基础设施)
|
||||
├── auth/ Token 登录、换票与缓存
|
||||
├── config/ 多账号与企业配置管理
|
||||
└── http/ HTTP 客户端工厂
|
||||
CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/http/)
|
||||
│ │ │ │
|
||||
└─────────────────────┴───────────┬───────────┴───────────────────┘
|
||||
▼
|
||||
cli/registry.ts & cli/commands/* (命令分发与视图渲染)
|
||||
│
|
||||
▼
|
||||
domains/ (14 个业务子域:编排 tools/services + 传输 api)
|
||||
│
|
||||
▼
|
||||
core/ (严格基础设施白名单)
|
||||
├── auth/ Token 登录、双通道续期、多账号与跨进程 Token 缓存
|
||||
├── config/ 多账号与企业配置管理(0600 权限与字段归一化)
|
||||
├── http/ 语义化 HTTP 客户端工厂(Session / OpenAPI / Unity / Piper)
|
||||
├── cache/ L1 内存 + L2 SQLite 多级协同缓存
|
||||
├── db/ 统一 SQLite 连接单例与结构化版本迁移 (migrations)
|
||||
└── errors.ts 统一异常语义体系 (EkbError 子类)
|
||||
```
|
||||
|
||||
核心原则:
|
||||
|
||||
- `server.ts` 只做 MCP 协议适配(tools 注册、参数解析、结果序列化)
|
||||
- 业务编排统一放在 `domains/*/tools.ts`
|
||||
- `domains/*/api.ts` 只负责 HTTP 请求和响应校验
|
||||
- `core/auth/` 负责各子域的 Token 获取与刷新
|
||||
- `core/config/` 负责本地认证配置读写
|
||||
- `core/errors.ts` 负责统一异常语义
|
||||
- `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`)
|
||||
- `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表
|
||||
- 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts`
|
||||
- `domains/*/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入
|
||||
- `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/`
|
||||
- 所有本地 SQLite 持久化(审批引擎、多级缓存、事件轮询去重、工作流错误指纹)统一收敛至 `core/db/` 并通过版本迁移管理
|
||||
|
||||
## 文档索引
|
||||
|
||||
@@ -52,35 +59,37 @@ CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
新增或调整功能时,优先遵循下面这条链路:
|
||||
|
||||
1. 先明确 `domains/` 的业务边界
|
||||
2. 再实现 `core/auth/` 或复用现有认证层
|
||||
3. 再接入 `server.ts` 注册 MCP tools
|
||||
2. 再实现 `core/auth/` 或复用现有认证与 `core/db/` 基础设施
|
||||
3. 再接入 `src/cli/commands/*` 并在 `src/cli/registry.ts` 注册
|
||||
4. 最后更新对应层级文档,而不是把细节补到根目录
|
||||
|
||||
同步更新顺序:
|
||||
|
||||
1. `domains/*/api.ts` — 传输层
|
||||
2. `domains/*/tools.ts` — 业务层
|
||||
3. `server.ts` — 注册 tools
|
||||
2. `domains/*/tools.ts` / `services.ts` — 业务编排层
|
||||
3. `cli/commands/*` & `cli/registry.ts` — CLI 命令层
|
||||
4. 对应目录下的 `README*.md`
|
||||
5. 只有在总纲真的变化时,才更新本文件
|
||||
|
||||
## 分层导入约束
|
||||
## 分层导入约束(由 `src/cli/architecture-boundaries.test.ts` 自动化强制卡点)
|
||||
|
||||
以下导入关系严格禁止:
|
||||
|
||||
| 禁止方向 | 说明 |
|
||||
|---|---|
|
||||
| `server.ts -> domains/*/api.ts` | Server 不得直接调用 API 层 |
|
||||
| `(cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts) -> domains/*/api.ts` | 任何入口层不得绕过 `tools.ts`/`services.ts` 直接调用 API 传输层 |
|
||||
| `domains/** -> (cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | 域层必须保持纯 SDK 零 UI/入口绑定 |
|
||||
| `core/** -> (domains/** \| cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | Core 基础设施层严禁向上反向依赖业务域或入口层 |
|
||||
|
||||
正确路径:
|
||||
|
||||
- `server.ts -> domains/*/tools.ts -> domains/*/api.ts -> core/http/*`
|
||||
- `domains/*/tools.ts -> core/auth/*`
|
||||
- `entrypoints -> cli/registry.ts -> cli/commands/* -> domains/*/(tools|services).ts -> domains/*/api.ts -> core/http/*`
|
||||
- `domains/*/(tools|services).ts -> core/{auth,cache,config,db,errors,http}`
|
||||
|
||||
## 异常规则
|
||||
|
||||
- `domains/` 层只抛 `EkbError` 子类(定义在 `core/errors.ts`)
|
||||
- `server.ts` 统一负责 MCP error 映射
|
||||
- `domains/` 层只抛 `EkbError` 子类(定义在 `core/errors.ts`:`NotLoggedInError`, `AuthenticationError`, `PermissionError`, `NotFoundError`, `ValidationError`, `BusinessError`, `EkbApiError`)
|
||||
- `src/cli/errors.ts` 统一按 `EkbError` 子类与状态码映射 CLI 退出码与下一步恢复建议
|
||||
- tools 文件里不要重复做局部异常体系
|
||||
|
||||
## 文档规则
|
||||
@@ -100,7 +109,7 @@ CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
2. **分支命名规范**:
|
||||
- 特性分支:`feat/<feature-name>` 或 `codex/issue-<id>-<name>`
|
||||
- 发布分支:`codex/release-v<X.Y.Z>` 或 `release/v<X.Y.Z>`
|
||||
- 维护优化:`chore/<task-name>` 或 `fix/<issue-name>`
|
||||
- 维护优化:`chore/<task-name>`、`refactor/<task-name>` 或 `fix/<issue-name>`
|
||||
3. **Pull Request 提交流程**:
|
||||
- 本地必须验证:`bun test && bun run check`(全绿方可提交);
|
||||
- 推送分支至远端:`git push origin <branch>`;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.10)
|
||||
# hose-use (v0.8.12)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+760
-642
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.10",
|
||||
"version": "0.8.12",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.10
|
||||
version: 0.8.12
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.10",
|
||||
"version": "0.8.12",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
+18
-12
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.10
|
||||
version: 0.8.12
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.10)
|
||||
# hose-use (v0.8.12)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -84,18 +84,18 @@ metadata:
|
||||
| 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) |
|
||||
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 | `hose-use bill schema` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 / 单据模板联动规格 | `hose-use bill schema`, `hose-use bill spec <specificationId>` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
|
||||
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
|
||||
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用与数据模型 (开放平台业务对象/字段定义/底层记录) | `hose-use platform list`, `hose-use platform entities <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用单条记录操作 (详情/停启用/字段编辑/台账重算) | `hose-use platform record <get|toggle|edit|recompute>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用与数据模型 (开放平台业务对象/字段定义/全量记录/健康度体检) | `hose-use platform list`, `hose-use platform entities <应用>`, `hose-use platform records <应用> <对象> --all`, `hose-use platform audit <应用> <对象>` | [references/workflow.md](references/workflow.md) |
|
||||
| 自建应用单条/批量记录安全操作 (详情/停启用/安全合并编辑/批量补丁/台账重算) | `hose-use platform record <get|toggle|edit|batch-edit|recompute>` | [references/workflow.md](references/workflow.md) |
|
||||
| 跨自建应用工作流聚合检索与节点扫描 | `hose-use workflow list`, `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 桌面端全站主导航与一级模块树 | `hose-use menu list`, `hose-use menu tree` | [references/workflow.md](references/workflow.md) |
|
||||
| 模糊搜索已保存的企业与员工信息 | `hose-use corps search <关键词>` | [references/auth.md](references/auth.md) |
|
||||
| 特定任务节点扫描 (如脚本/Webhook) | `hose-use workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、发布与开通切换 | `hose-use workflow get`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、单次运行排障、发布与开通切换 | `hose-use workflow get`, `hose-use workflow job <jobId>`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断(禁用/SKIP风险/联动覆盖) | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
|
||||
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) |
|
||||
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.md) |
|
||||
@@ -165,6 +165,7 @@ hose-use role groups # 查看角色组及其
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
hose-use permission get # 查看角色权限开关(只读)
|
||||
hose-use bill schema # 查询单据实体元数据字典
|
||||
hose-use bill spec ID01TxgE3fhD6n # 查看单据模板字段配置、赋值优先级与联动规则
|
||||
|
||||
# 4. 待办与消息
|
||||
hose-use task submitted # 查看我发起的单据
|
||||
@@ -178,20 +179,25 @@ hose-use app list # 查看应用管理列
|
||||
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
|
||||
hose-use platform list # 列出企业可见的自建应用平台
|
||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||
hose-use platform records 新转转集团 合同 # 查看业务对象的底层数据记录
|
||||
hose-use platform record get 新转转集团 合同 <记录ID> # 获取单条记录完整字段与属性详情
|
||||
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
|
||||
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
|
||||
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
|
||||
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' --yes # 编辑记录字段
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"我方签约主体":"ID01..."}' --dry-run # Read-Modify-Write 安全合并预览
|
||||
hose-use platform record batch-edit 新转转集团 合同 --ids=id1,id2 --data='{"字段":"值"}' --dry-run # 批量安全更新预览
|
||||
hose-use platform record recompute 新转转集团 合同 <记录ID> --yes # 重新计算记录关联的全部台账
|
||||
hose-use menu list # 查看桌面端主框架一级导航树
|
||||
hose-use workflow list # 聚合扫描全部自建应用下的工作流
|
||||
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
|
||||
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断(含联动覆盖/SKIP守卫检查)
|
||||
hose-use workflow logs wf_01k83y... --has-error # 筛选包含报错节点(含被 SKIP 吞掉错误)的运行历史
|
||||
hose-use workflow job 892809886382563347 --failed # 一键定位单次运行失败节点、入参出参与错误原因
|
||||
hose-use workflow job 892809886382563347 --parent=<executionId> # 下钻查看循环/分支容器内子节点执行明细
|
||||
hose-use workflow job 892809886382563347 --logs=<executionId> # 查看指定节点(如 MVEL 脚本)底层执行日志
|
||||
hose-use workflow save wf_01k83y... --file=workflow.json --yes # 按完整快照保存草稿并做版本保护
|
||||
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json --yes
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow logs wf_01k83y... --state=FAILED # 查看运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
|
||||
|
||||
|
||||
@@ -154,7 +154,7 @@ hose-use bill download S26000001 --output-dir ./downloads
|
||||
hose-use bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json
|
||||
```
|
||||
|
||||
## 5. 单据实体元数据字典 (`bill schema`)
|
||||
## 5. 单据实体元数据字典 (`bill schema`) 与单据模板规格诊断 (`bill spec`)
|
||||
|
||||
用于探查当前企业所有单据实体、字段类型与扩展属性定义:
|
||||
|
||||
@@ -163,6 +163,15 @@ hose-use bill schema
|
||||
hose-use bill schema --json
|
||||
```
|
||||
|
||||
当需要查看某个具体单据/申请模板(如工作流 `flow-create-task` 节点绑定的 `specificationId`)的完整字段列表、必填属性、赋值优先级(`priorityList`)以及字段联动覆盖规则(`assignmentRule` / `isLinkageAssignment`)时,使用 `bill spec`(同义别名:`feetype spec`):
|
||||
|
||||
```bash
|
||||
hose-use bill spec ID01TxgE3fhD6n
|
||||
hose-use bill spec ID01TxgE3fhD6n --json
|
||||
```
|
||||
|
||||
该命令会自动标记所有配置了 `LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN`(自动联动高于手动填写/工作流传入)的业务对象字段,帮助快速排查“工作流传入字段被单据模板联动静默清空或覆盖”的隐蔽问题。
|
||||
|
||||
---
|
||||
|
||||
## 6. 上下文防爆保护与安全转储
|
||||
|
||||
@@ -42,46 +42,65 @@ hose-use platform entities 新转转集团
|
||||
hose-use platform schema 新转转集团 合同
|
||||
hose-use platform schema 新转转集团 合同 --keyword="金额"
|
||||
|
||||
# 检索业务对象的底层真实数据记录
|
||||
# 检索业务对象的底层真实数据记录(支持 --all 自动翻页拉取全量记录)
|
||||
hose-use platform records 新转转集团 合同 --limit=5
|
||||
hose-use platform records 新转转集团 合同 --keyword="技术服务" --fields "合同编号,金额,经办人" --json
|
||||
hose-use platform records 新转转集团 支付计划表 --all --json -o /tmp/payment_plans.json
|
||||
```
|
||||
|
||||
### 2.1 业务对象记录操作 (`platform record`)
|
||||
### 2.1 业务对象记录操作 (`platform record`) 与安全全量合并 (Read-Modify-Write)
|
||||
|
||||
支持对业务对象单条记录进行精准详情查看、停用/启用状态翻转、表单字段更新以及台账重新计算:
|
||||
> **关键防坑说明**:合思 DataLink `PUT /api/v2.2/datalink/platformDataLink/$id` 是**整单覆盖接口**,而非局部 PATCH。若只传修改的 1 个字段,未传字段会被清空、对象引用若未提取 `.id` 会报 417、`visibility` 漏传会导致全员不可见。`hose-use platform record edit` 与 `batch-edit` 默认内置 **Read-Modify-Write 安全合并引擎**,自动拉取原记录与 Schema、归一化嵌套引用 ID、保留全部存量字段与 `visibility` 权限,并支持字段中英文短名自动解析。
|
||||
|
||||
```bash
|
||||
# 1. 查看单条记录详情 (包含基本信息、实体字段、关联台账与可见范围)
|
||||
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF
|
||||
# 1. 查看单条记录详情 (支持直接传 recordId 免传应用与业务对象)
|
||||
hose-use platform record get ID01TqE4yUG6hF
|
||||
hose-use platform record get 新转转集团 合同 ID01TqE4yUG6hF --json
|
||||
|
||||
# 2. 切换记录停用/启用状态 (默认自动翻转,支持 --state 显式指定)
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=false # 停用
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=true # 启用
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --dry-run
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=false --yes # 停用
|
||||
hose-use platform record toggle 新转转集团 合同 ID01TqE4yUG6hF --state=true --yes # 启用
|
||||
|
||||
# 3. 编辑更新记录字段 (传入 JSON 字典或 --data)
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"name":"新名称","项目内容":"技术支持"}'
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF '{"name":"新名称"}'
|
||||
# 3. 安全编辑单条记录字段 (默认 Read-Modify-Write 安全合并,支持字段短名/中文标签)
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"我方签约主体":"ID01RnG3b79daL"}' --dry-run
|
||||
hose-use platform record edit 新转转集团 合同 ID01TqE4yUG6hF --data='{"我方签约主体":"ID01RnG3b79daL"}' --yes
|
||||
|
||||
# 4. 重新计算记录关联的全部台账
|
||||
hose-use platform record recompute 新转转集团 合同 ID01TqE4yUG6hF
|
||||
# 4. 批量安全编辑多条记录 (支持 --ids / --filter / --file,内置并发控制与逐条 diff 预览)
|
||||
hose-use platform record batch-edit 新转转集团 支付计划表 \
|
||||
--ids=ID01A,ID01B \
|
||||
--data='{"我方签约主体":"ID01RnG3b79daL"}' \
|
||||
--dry-run
|
||||
hose-use platform record batch-edit 新转转集团 支付计划表 --file=./patches.json --yes
|
||||
|
||||
# 5. 重新计算记录关联的全部台账
|
||||
hose-use platform record recompute 新转转集团 合同 ID01TqE4yUG6hF --yes
|
||||
```
|
||||
|
||||
### 2.2 业务对象健康度巡检 (`platform audit`)
|
||||
|
||||
一键扫描指定业务对象全量记录的三大高频隐患,并自动生成可直接用于修复的 `suggestedPatches`:
|
||||
1. **必填/关键字段缺失 (`MISSING_FIELD`)**:检测 Schema 必填字段或 `--check-fields` 指定字段为空的记录;
|
||||
2. **引用已停用档案 (`DISABLED_REFERENCE`)**:检测引用字段指向 `active: false` 档案的记录;
|
||||
3. **跨台账冗余字段失步 (`CROSS_LEDGER_MISSING_SYNC` / `CROSS_LEDGER_MISMATCH`)**:当子台账(如《支付计划表》)关联父台账(如《合同流程》)且存在同名冗余字段(如 `我方签约主体`)时,自动比对子表与父表值是否一致,若父表有值而子表缺失则自动生成修复补丁。
|
||||
|
||||
```bash
|
||||
hose-use platform audit 新转转集团 支付计划表 --check-fields="我方签约主体"
|
||||
hose-use platform audit 新转转集团 支付计划表 --check-fields="我方签约主体" --active-only --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 跨应用工作流聚合检索 (`workflow list`)
|
||||
|
||||
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描:
|
||||
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描(同时支持 `--platform-id` 与 `--app-id`):
|
||||
|
||||
```bash
|
||||
# 查看所有自建应用下的全部工作流汇总
|
||||
hose-use workflow list
|
||||
|
||||
# 查看指定自建应用下的工作流
|
||||
hose-use workflow list --app-id=app_01j72x...
|
||||
hose-use workflow list --app-id=ID01RKbEvQsWbd
|
||||
```
|
||||
|
||||
---
|
||||
@@ -126,13 +145,34 @@ hose-use workflow toggle wf_01k83y... --disable
|
||||
|
||||
## 7. 工作流静态分析 (`workflow analyze`)
|
||||
|
||||
从应用中心的具体自建应用进入工作流详情后,CLI 可以读取同一份详情并生成递归节点树、代码表达式引用依赖和明显配置诊断;该命令只读,不执行工作流:
|
||||
读取工作流详情并生成递归节点树、代码表达式引用依赖和静态风险诊断(只读,不执行工作流)。内置以下核心风险检测:
|
||||
- `WORKFLOW_DISABLED`:工作流处于停用状态(`state === 0`);
|
||||
- `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`:循环容器(`every`)内的创单节点(`flow-create-task`)配置了 `onError.defaultAction === "SKIP"`,且后续台账更新节点(`ekuaibao-datalink-edit`)未守卫创单节点的 `$status`,会导致创单失败时仍将台账状态改成“创建成功”;
|
||||
- `LINKAGE_PRIORITY_OVERRIDE`:创单节点绑定了 `dataLink` 台账字段,同时目标单据模板对应字段开启了自动联动赋值且优先级 `LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN`,导致单据模板联动静默覆盖工作流显式传入的值。
|
||||
|
||||
```bash
|
||||
hose-use workflow analyze wf_01k83y... --json
|
||||
hose-use workflow analyze 886351399301758976 --json
|
||||
```
|
||||
|
||||
## 8. 工作流草稿保存 (`workflow save`)
|
||||
## 8. 工作流单次运行实例排障 (`workflow job`)
|
||||
|
||||
当工作流执行报错、或因为子节点配置了 `SKIP` 导致外层状态显示为 `COMPLETED` 但内部实际创单失败时,使用 `workflow job` 下钻单次运行实例:
|
||||
|
||||
```bash
|
||||
# 1. 查看 Job 概览与顶层节点执行树
|
||||
hose-use workflow job 892809886382563347
|
||||
|
||||
# 2. 直接列出该次运行中所有报错节点、错误原因(outputs.error)及入参快照(含关联业务对象 ID)
|
||||
hose-use workflow job 892809886382563347 --failed --json
|
||||
|
||||
# 3. 展开循环(every)或分支(switch)容器内的子节点迭代明细
|
||||
hose-use workflow job 892809886382563347 --parent=892809893789696012
|
||||
|
||||
# 4. 查看指定节点(如 MVEL 代码节点)的底层控制台输出与异常堆栈
|
||||
hose-use workflow job 892809886382563347 --logs=892809893789696012
|
||||
```
|
||||
|
||||
## 9. 工作流草稿保存 (`workflow save`)
|
||||
|
||||
Web 端“保存更新”是对完整 pipeline 的 PUT,而不是单节点 PATCH。推荐先导出详情,再修改 JSON,最后按版本保护保存:
|
||||
|
||||
@@ -144,21 +184,21 @@ hose-use workflow save <pipelineId> --file=workflow.json
|
||||
|
||||
命令会先重新读取远端版本;若 `version` 或 `tasksVersion` 已变化会拒绝覆盖。确认需要强制覆盖时显式使用 `--force-write`。
|
||||
|
||||
## 9. 本地节点草稿修改 (`workflow patch`)
|
||||
## 10. 本地节点草稿修改 (`workflow patch`)
|
||||
|
||||
网页编辑器最终提交的是完整 pipeline,因此节点修改先在完整 JSON 草稿上完成,再交给 `workflow save` 做版本保护和服务端持久化:
|
||||
|
||||
```bash
|
||||
hose-use workflow patch <pipelineId> \\
|
||||
--file=workflow.json \\
|
||||
--path=tasks.1.form.title \\
|
||||
--value="新的标题" \\
|
||||
hose-use workflow patch <pipelineId> \
|
||||
--file=workflow.json \
|
||||
--path=tasks.1.form.title \
|
||||
--value="新的标题" \
|
||||
--output=workflow.patched.json
|
||||
```
|
||||
|
||||
数组也可以使用 `tasks[1].form.title`。需要写入数字、布尔值或对象时加 `--value-json`;使用 `--in-place` 才会覆盖输入文件。该命令只修改本地草稿,不直接触发远端写入。
|
||||
|
||||
## 10. 工作流版本历史 (`workflow history`)
|
||||
## 11. 工作流版本历史 (`workflow history`)
|
||||
|
||||
服务端每次完整保存都会生成一个版本快照,可用以下命令读取审计历史:
|
||||
|
||||
@@ -166,11 +206,12 @@ hose-use workflow patch <pipelineId> \\
|
||||
hose-use workflow history <pipelineId> --json
|
||||
```
|
||||
|
||||
## 11. 运行日志与错误管道提醒
|
||||
## 12. 运行日志与错误管道提醒 (`workflow logs` / `workflow check`)
|
||||
|
||||
查询单个工作流的运行日志:
|
||||
查询单个工作流的运行日志(表格默认展示 `successTaskCount`、`errorTaskCount`、`hasError`;即使工作流整体状态因 `SKIP` 显示为 `COMPLETED`,也可通过 `--has-error` 精准揪出内部含报错节点的运行记录):
|
||||
|
||||
```bash
|
||||
hose-use workflow logs <pipelineId> --has-error
|
||||
hose-use workflow logs <pipelineId> --state=FAILED --json
|
||||
```
|
||||
|
||||
@@ -181,9 +222,7 @@ hose-use workflow check --json
|
||||
hose-use workflow check --json --fail-on-alert
|
||||
```
|
||||
|
||||
默认状态文件为 `~/.config/hose-use/workflow-alerts-<corp>.json`,可用 `--state-file` 指定。`--fail-on-alert` 适合被常驻服务或外部调度器检测;它只改变退出码,不自动向外部人员发送消息。
|
||||
|
||||
## 12. 发布工作流 (`workflow publish`)
|
||||
## 13. 发布工作流 (`workflow publish`)
|
||||
|
||||
网页端发布动作对应 Piper 的状态接口:`PUT /api/easo/pipelines/state/{pipelineId}?state=1`。CLI 提供同等入口:
|
||||
|
||||
@@ -192,3 +231,23 @@ hose-use workflow publish <pipelineId>
|
||||
```
|
||||
|
||||
建议先执行 `workflow save`,确认保存成功后再执行 `workflow publish`;发布只切换启用状态,不替代完整配置保存。
|
||||
|
||||
---
|
||||
|
||||
## 14. 工作流排障与创单排错三大黄金法则(必读)
|
||||
|
||||
在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则:
|
||||
|
||||
### 法则一:先跑 `workflow analyze <pipelineId>` 排除停用与静默吞错
|
||||
- 检查是否命中 `WORKFLOW_DISABLED`(许多名为“【生产】xxx”的工作流实际处于 `state: 0` 停用状态,切勿被名称误导);
|
||||
- 检查是否命中 `UNSAFE_SKIP_WITHOUT_STATUS_GUARD`(`every` 循环中 `flow-create-task` 配置了失败跳过 `SKIP`,导致外层 Job 状态变为 `COMPLETED`,且后续 `ekuaibao-datalink-edit` 无视创单失败直接把台账改成“已发起”)。
|
||||
|
||||
### 法则二:用 `workflow logs --has-error` 与 `workflow job <jobId> --failed` 直击真实报错与源记录 ID
|
||||
- 不要只看 `--state=FAILED`!只要节点配置了 `SKIP`,Job 顶层 `state` 就会是 `COMPLETED`,必须用 `hose-use workflow logs <pipelineId> --has-error` 找出 `errorTaskCount > 0` 的 `jobId`;
|
||||
- 拿到 `jobId` 后,立即执行 `hose-use workflow job <jobId> --failed --json`,从 `outputs.error` 读取精确报错(例如 `我方签约主体未填写`),并从 `inputs.form` 中提取触发本次创单的源业务对象记录 ID。
|
||||
|
||||
### 法则三:遇到“工作流明明传了字段但创单仍报未填”,立即用 `bill spec <specificationId>` 检查联动覆盖优先级
|
||||
- 当工作流 `flow-create-task` 已经给某字段(如 `u_我方签约主体`)传了值,但仍报该字段未填写时,根因往往在**单据模板字段的赋值优先级 (`priorityList`) 与联动规则 (`assignmentRule`)**:
|
||||
- 执行 `hose-use bill spec <specificationId>`(或直接看 `workflow analyze` 的 `LINKAGE_PRIORITY_OVERRIDE` 告警);
|
||||
- 若单据模板中某业务对象字段(如 `u_关联合同流程`)开启了联动赋值,且目标字段的优先级为 `LINKAGE_ASSIGNMENT (自动联动) > MANUALLY_FILL_IN (手动填写/工作流传入)`,则单据保存时会用被关联主表(如《合同流程》)上的字段值强行覆盖工作流传入的值;若主表对应字段为空,工作流传入的值就会被清空!
|
||||
- 定位到缺失字段的台账记录后,使用 `hose-use platform audit <应用> <对象> --check-fields="..."` 巡检全量存量数据,并用 `hose-use platform record edit` / `batch-edit`(先 `--dry-run` 再 `--yes`)安全修复。
|
||||
+72
-1085
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
|
||||
const SRC_ROOT = join(import.meta.dir, "..");
|
||||
|
||||
function collectTsFiles(dir: string, includeTests = false): string[] {
|
||||
const results: string[] = [];
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const full = join(dir, entry);
|
||||
const stat = statSync(full);
|
||||
if (stat.isDirectory()) {
|
||||
results.push(...collectTsFiles(full, includeTests));
|
||||
} else if (full.endsWith(".ts") && (includeTests || !full.endsWith(".test.ts"))) {
|
||||
results.push(full);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function extractImportSpecifiers(source: string): string[] {
|
||||
const specifiers: string[] = [];
|
||||
const staticImportRe = /(?:import|export)\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g;
|
||||
const dynamicImportRe = /import\(\s*["']([^"']+)["']\s*\)/g;
|
||||
|
||||
for (const match of source.matchAll(staticImportRe)) {
|
||||
if (match[1]) specifiers.push(match[1]);
|
||||
}
|
||||
for (const match of source.matchAll(dynamicImportRe)) {
|
||||
if (match[1]) specifiers.push(match[1]);
|
||||
}
|
||||
return specifiers;
|
||||
}
|
||||
|
||||
function resolveImportRelativeToSrc(fromFile: string, specifier: string): string | null {
|
||||
if (!specifier.startsWith(".")) return null;
|
||||
const abs = resolve(dirname(fromFile), specifier).replace(/\.[jt]s$/, "");
|
||||
return relative(SRC_ROOT, abs);
|
||||
}
|
||||
|
||||
describe("Architecture Layering Boundaries", () => {
|
||||
test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/*/api directly", () => {
|
||||
const entrypointFiles = [
|
||||
...collectTsFiles(join(SRC_ROOT, "cli")),
|
||||
...collectTsFiles(join(SRC_ROOT, "http")),
|
||||
join(SRC_ROOT, "server.ts"),
|
||||
join(SRC_ROOT, "cli.ts"),
|
||||
join(SRC_ROOT, "aipro-cli.ts"),
|
||||
];
|
||||
|
||||
const violations: string[] = [];
|
||||
for (const file of entrypointFiles) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
const specifiers = extractImportSpecifiers(content);
|
||||
for (const spec of specifiers) {
|
||||
const targetRel = resolveImportRelativeToSrc(file, spec);
|
||||
if (targetRel && /^domains\/[^/]+\/api$/.test(targetRel)) {
|
||||
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
test("src/domains/ must remain pure SDK and never import from cli, http, or server entrypoints", () => {
|
||||
const domainFiles = collectTsFiles(join(SRC_ROOT, "domains"));
|
||||
const violations: string[] = [];
|
||||
|
||||
for (const file of domainFiles) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
const specifiers = extractImportSpecifiers(content);
|
||||
for (const spec of specifiers) {
|
||||
const targetRel = resolveImportRelativeToSrc(file, spec);
|
||||
if (
|
||||
targetRel &&
|
||||
(targetRel.startsWith("cli/") ||
|
||||
targetRel.startsWith("http/") ||
|
||||
targetRel === "server" ||
|
||||
targetRel === "cli" ||
|
||||
targetRel === "aipro-cli")
|
||||
) {
|
||||
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
test("src/core/ must never depend upward on domains, cli, http, or server entrypoints", () => {
|
||||
const coreFiles = collectTsFiles(join(SRC_ROOT, "core"));
|
||||
const violations: string[] = [];
|
||||
|
||||
for (const file of coreFiles) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
const specifiers = extractImportSpecifiers(content);
|
||||
for (const spec of specifiers) {
|
||||
const targetRel = resolveImportRelativeToSrc(file, spec);
|
||||
if (
|
||||
targetRel &&
|
||||
(targetRel.startsWith("domains/") ||
|
||||
targetRel.startsWith("cli/") ||
|
||||
targetRel.startsWith("http/") ||
|
||||
targetRel === "server" ||
|
||||
targetRel === "cli" ||
|
||||
targetRel === "aipro-cli")
|
||||
) {
|
||||
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
test("src/core/ must only contain whitelisted infrastructure modules", () => {
|
||||
const allowedTopLevel = new Set([
|
||||
"README.core.md",
|
||||
"auth",
|
||||
"cache",
|
||||
"config",
|
||||
"db",
|
||||
"errors.ts",
|
||||
"http",
|
||||
]);
|
||||
const entries = readdirSync(join(SRC_ROOT, "core"));
|
||||
const unexpected = entries.filter((entry) => !allowedTopLevel.has(entry));
|
||||
expect(unexpected).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
import type { ApprovalRunRecord } from "../../../domains/approval/index.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import { parseIntegerList, type AiProCommandResult, type AiProExecutionContext } from "./types.js";
|
||||
|
||||
export async function handleAiProScopes(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
}
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "scopes",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: runRecord?.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord ? `在会话 [${runRecord.shortId}] 查阅规约场景索引` : "查阅规约场景索引",
|
||||
});
|
||||
|
||||
const scopes = repo.listScopes().map((s) => ({
|
||||
索引号: s.index,
|
||||
适用场景: s.scope,
|
||||
}));
|
||||
return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAiProRules(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const rawIndexes =
|
||||
stringOption(parsed.options, ["indexes", "index", "i", "scope", "s"]) ||
|
||||
positional[1] ||
|
||||
positional[2];
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
}
|
||||
|
||||
const targetIndexes = parseIntegerList(rawIndexes);
|
||||
const uniqueIndexes = [...new Set(targetIndexes)].sort((a, b) => a - b);
|
||||
if (uniqueIndexes.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `请提供具名参数,例如:\n hose-aipro rules --run <runId> --indexes "[1]"\n hose-aipro rules --run <runId> --indexes "[1, 2]"\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const rulesMap = new Map<number, { 编号: number; 适用场景: string; 规则明细: string }>();
|
||||
const notFound: number[] = [];
|
||||
|
||||
for (const idx of uniqueIndexes) {
|
||||
const detail = repo.getScopeDetail(idx);
|
||||
if (!detail) {
|
||||
notFound.push(idx);
|
||||
continue;
|
||||
}
|
||||
for (const r of detail.rules) {
|
||||
if (!rulesMap.has(r.code)) {
|
||||
rulesMap.set(r.code, {
|
||||
编号: r.code,
|
||||
适用场景: detail.scope,
|
||||
规则明细: r.body,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (notFound.length > 0 && rulesMap.size === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到指定索引对应的规约场景: [${notFound.join(", ")}]\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.编号 - b.编号);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "rules",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: runRecord?.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord
|
||||
? `在会话 [${runRecord.shortId}] 查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`
|
||||
: `查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(flattenedRules, null, 2) + "\n",
|
||||
stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: [${notFound.join(", ")}]\n` : "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProPoints(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, service, runtime, operator, rawArgs, getClient } = ctx;
|
||||
const arg1 = positional[1] || stringOption(parsed.options, ["scope", "s", "index", "i"]);
|
||||
const arg2 = positional[2];
|
||||
|
||||
// 兼容双参数调用: 如果同时提供了单号和索引号,走单据绑定流
|
||||
if (arg1 && arg2) {
|
||||
const billSn = arg1;
|
||||
const scopeTarget = arg2;
|
||||
const context = await getClient();
|
||||
const result = await service.injectAuditPoints(context.client, context.corpId, billSn, {
|
||||
scope: scopeTarget ? (isNaN(Number(scopeTarget)) ? scopeTarget : Number(scopeTarget)) : undefined,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "bind",
|
||||
documentSn: result.bill.billCode,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
decision: "PENDING",
|
||||
summary: `绑定单据并挂载审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
sn: result.bill.billCode,
|
||||
scope: result.scope,
|
||||
runId: result.run.id,
|
||||
count: result.findings.length,
|
||||
findings: result.findings,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
|
||||
const rows = result.findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus,
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO] 单据 ${result.bill.billCode} 已挂载场景 [${result.scope}] 审核要点 (共 ${result.findings.length} 条) ======\n`;
|
||||
const tip =
|
||||
`\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` +
|
||||
`下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` +
|
||||
`最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`;
|
||||
|
||||
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetScope = arg1;
|
||||
if (!targetScope) {
|
||||
const allScopes = repo.listScopes("active");
|
||||
if (allScopes.length === 0) {
|
||||
return {
|
||||
stdout: "规约库中暂无生效规则。可使用 hose-use rule add <场景> <正文> 新增规则。\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const lines: string[] = [
|
||||
`====== [AI PRO] 规约审核要点总览 (共 ${allScopes.length} 个适用场景) ======\n`,
|
||||
];
|
||||
for (const s of allScopes) {
|
||||
const detail = repo.getScopeDetail(s.index);
|
||||
if (!detail) continue;
|
||||
lines.push(`▶ 场景 [${detail.index}] ${detail.scope} (包含 ${detail.ruleCount} 条规则):`);
|
||||
let count = 0;
|
||||
detail.rules.forEach((r) => {
|
||||
r.parsed.clauses.forEach((c) => {
|
||||
count++;
|
||||
lines.push(` ${count}. [${c.strictness}] (规则 #${r.code}) ${c.action}`);
|
||||
});
|
||||
});
|
||||
lines.push("");
|
||||
}
|
||||
lines.push(`提示: 输入 "hose-aipro points <索引号|场景名称>" 查看指定场景要点明细。\n`);
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const detail = repo.getScopeDetail(targetScope);
|
||||
if (!detail) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到索引号或场景为 "${targetScope}" 的规约场景。\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const points: Array<{ index: number; strictness: string; ruleCode: number; clauseText: string }> = [];
|
||||
let count = 0;
|
||||
for (const rule of detail.rules) {
|
||||
for (const clause of rule.parsed.clauses) {
|
||||
count++;
|
||||
points.push({
|
||||
index: count,
|
||||
strictness: clause.strictness,
|
||||
ruleCode: rule.code,
|
||||
clauseText: clause.action,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
index: detail.index,
|
||||
scope: detail.scope,
|
||||
ruleCount: detail.ruleCount,
|
||||
pointsCount: points.length,
|
||||
points,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "归属规则", "审核要点内容 (Clause)"];
|
||||
const rows = points.map((p) => [p.index, `[${p.strictness}]`, `#${p.ruleCode}`, p.clauseText]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO] 适用场景 [${detail.index}] ${detail.scope} - 审核要点清单 (共 ${points.length} 条要点) ======\n`;
|
||||
const tip =
|
||||
`\n说明: 审核要点为规约条款提取出的判定标准,纯规则元数据,与具体单据无关。\n` +
|
||||
`绑定单据: 运行 "hose-aipro bind <单号> ${detail.index}" 将此要点清单挂载到具体单据。\n`;
|
||||
|
||||
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAiProChecklist(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { targetSn, requireCorpId, service, repo, operator, rawArgs, runtime } = ctx;
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-aipro checklist <单号>");
|
||||
}
|
||||
|
||||
const activeCorpId = requireCorpId();
|
||||
const { run, findings } = service.getAuditChecklist(targetSn, activeCorpId);
|
||||
if (!run || findings.length === 0) {
|
||||
repo.logAiProAction({
|
||||
action: "checklist",
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "BLOCKED",
|
||||
summary: "查询审核清单阻断:单据尚未绑定任何审核要点",
|
||||
});
|
||||
|
||||
const errorMsg =
|
||||
`[审批链路阻断] 单据 [${targetSn}] 尚未绑定任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关安全卡点生效:在要点未绑定前,审批链路物理不通!\n` +
|
||||
`请先执行: hose-aipro bind ${targetSn} <索引号> 挂载明细级审核要点清单。\n`;
|
||||
return { stdout: "", stderr: errorMsg, exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ run, findings }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 说明"];
|
||||
const rows = findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS"
|
||||
? "✅ PASS"
|
||||
: f.checkStatus === "FAIL"
|
||||
? "❌ FAIL"
|
||||
: f.checkStatus === "SKIP"
|
||||
? "➖ SKIP"
|
||||
: "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const title = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (适用场景: [${run.scope || "未关联"}] | 总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`;
|
||||
|
||||
return { stdout: title + table, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
import {
|
||||
type ApprovalRunRecord,
|
||||
type CreateFindingInput,
|
||||
type FindingCheckStatus,
|
||||
type RuleRecord,
|
||||
parseRuleBody,
|
||||
validateGatewayAction,
|
||||
} from "../../../domains/approval/index.js";
|
||||
import {
|
||||
approveBill,
|
||||
getRawBillFlow,
|
||||
getTranslatorContext,
|
||||
rejectBill,
|
||||
} from "../../../domains/bill/tools.js";
|
||||
import { translateBillFlowToMarkdown } from "../../../domains/bill/translator.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { parseIntegerList, type AiProCommandResult, type AiProExecutionContext } from "./types.js";
|
||||
|
||||
export async function handleAiProInit(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { positional, parsed, getClient, repo, operator, rawArgs } = ctx;
|
||||
const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
if (!billSn) {
|
||||
throw new Error("请提供单号: hose-aipro init <单号>");
|
||||
}
|
||||
const context = await getClient();
|
||||
const raw = await getRawBillFlow(context.client, context.corpId, billSn);
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号为 [${billSn}] 的单据`);
|
||||
}
|
||||
const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record<
|
||||
string,
|
||||
any
|
||||
>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<
|
||||
string,
|
||||
any
|
||||
>;
|
||||
const title = form.title || flowIdObj.title || "<无标题>";
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(
|
||||
() => undefined
|
||||
);
|
||||
const snapshot = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
const run = repo.createApprovalRun({
|
||||
documentSn: form.code || billSn,
|
||||
corpId: context.corpId,
|
||||
flowId: flowIdObj.id || raw.id,
|
||||
documentSnapshot: snapshot,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "init",
|
||||
runId: run.shortId || run.id,
|
||||
documentSn: run.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `初始化审批会话成功,签发 6 位短 ID: ${run.shortId} (有效期 6 小时)`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout:
|
||||
JSON.stringify(
|
||||
{
|
||||
runId: run.shortId,
|
||||
documentSn: run.documentSn,
|
||||
title,
|
||||
corpId: run.corpId,
|
||||
status: run.decision,
|
||||
expiresIn: "6h",
|
||||
createdAt: run.createdAt,
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProTranslate(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs, getClient } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const specifiedSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
} else if (specifiedSn) {
|
||||
const maybeRun = repo.getRunByHandle(specifiedSn);
|
||||
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === specifiedSn.toUpperCase()) {
|
||||
runRecord = maybeRun;
|
||||
}
|
||||
}
|
||||
|
||||
let targetSn: string | undefined;
|
||||
let isSessionPrimary = false;
|
||||
|
||||
if (runRecord) {
|
||||
if (specifiedSn && specifiedSn !== runRecord.shortId) {
|
||||
targetSn = specifiedSn;
|
||||
} else {
|
||||
targetSn = runRecord.documentSn;
|
||||
isSessionPrimary = true;
|
||||
}
|
||||
} else {
|
||||
targetSn = specifiedSn;
|
||||
}
|
||||
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供会话 ID 或单号: hose-aipro translate [单号] --run <runId>");
|
||||
}
|
||||
|
||||
if (isSessionPrimary && runRecord?.documentSnapshot) {
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `在会话 [${runRecord.shortId}] 读取主单据快照 [${runRecord.documentSn}]`,
|
||||
});
|
||||
return {
|
||||
stdout: runRecord.documentSnapshot.endsWith("\n")
|
||||
? runRecord.documentSnapshot
|
||||
: runRecord.documentSnapshot + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const context = await getClient();
|
||||
const raw = await getRawBillFlow(context.client, context.corpId, targetSn);
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`);
|
||||
}
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(
|
||||
() => undefined
|
||||
);
|
||||
const markdown = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord
|
||||
? `在会话 [${runRecord.shortId}] 查阅关联单据 [${targetSn}] 转译文本`
|
||||
: `查阅单据 [${targetSn}] 转译文本`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: markdown.endsWith("\n") ? markdown : markdown + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProBind(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
|
||||
if (!runHandle) {
|
||||
throw new Error("请提供会话 ID: hose-aipro bind --run <runId> --rules '[1, 2]'");
|
||||
}
|
||||
const runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
|
||||
const rawRules = stringOption(parsed.options, ["rules", "rule", "codes", "c"]);
|
||||
const rawIndexes = stringOption(parsed.options, ["indexes", "index", "i", "scopes", "scope", "s"]);
|
||||
const fallbackRaw = positional
|
||||
.slice(1)
|
||||
.find((p) => p !== runHandle && p.startsWith("[") && p.endsWith("]"));
|
||||
|
||||
const ruleCodes = parseIntegerList(rawRules || fallbackRaw);
|
||||
const indexNums = parseIntegerList(rawIndexes);
|
||||
|
||||
if (ruleCodes.length === 0 && indexNums.length === 0) {
|
||||
throw new Error("请指定要挂载的规则或场景索引,例如: hose-aipro bind --run <runId> --rules '[1, 2]'");
|
||||
}
|
||||
|
||||
const targetRulesMap = new Map<number, RuleRecord>();
|
||||
for (const code of ruleCodes) {
|
||||
const r = repo.getRuleByCode(code);
|
||||
if (r && r.status === "active") {
|
||||
targetRulesMap.set(r.code, r);
|
||||
}
|
||||
}
|
||||
for (const idx of indexNums) {
|
||||
const detail = repo.getScopeDetail(idx);
|
||||
if (detail) {
|
||||
for (const r of detail.rules) {
|
||||
if (r.status === "active") {
|
||||
targetRulesMap.set(r.code, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targetRulesMap.size === 0) {
|
||||
throw new Error("未找到任何有效规则,请先运行 hose-aipro scopes 和 hose-aipro rules 查看规约");
|
||||
}
|
||||
|
||||
const sortedRules = Array.from(targetRulesMap.values()).sort((a, b) => a.code - b.code);
|
||||
const findingsToInject: CreateFindingInput[] = [];
|
||||
|
||||
for (const r of sortedRules) {
|
||||
const parsedRule = parseRuleBody(r.body);
|
||||
for (const clause of parsedRule.clauses) {
|
||||
findingsToInject.push({
|
||||
ruleId: r.id,
|
||||
clauseText: clause.action,
|
||||
strictness: clause.strictness,
|
||||
checkStatus: "PENDING",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const injected = repo.injectFindings(runRecord.id, findingsToInject);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "bind",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `在会话 [${runRecord.shortId}] 挂载 ${injected.length} 条审核要点清单(涵盖规则: ${sortedRules.map((r) => `#${r.code}`).join(", ")})`,
|
||||
});
|
||||
|
||||
const output = injected.map((f, i) => ({
|
||||
要点编号: i + 1,
|
||||
严格程度: f.strictness,
|
||||
归属规则: f.ruleCode ?? "-",
|
||||
审核要点: f.clauseText,
|
||||
核验状态: "待核验",
|
||||
}));
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(output, null, 2) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProReview(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
|
||||
if (!runHandle) {
|
||||
throw new Error("请提供会话 ID: hose-aipro review --run <runId> --eval '...'");
|
||||
}
|
||||
const runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
|
||||
const findings = repo.getFindingsByRunId(runRecord.id);
|
||||
if (findings.length === 0) {
|
||||
throw new Error(
|
||||
`会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何审核要点清单,请先执行 hose-aipro bind --run ${runRecord.shortId || runRecord.id} --rules '...'`
|
||||
);
|
||||
}
|
||||
|
||||
const evalStr = stringOption(parsed.options, ["eval", "findings", "e"]);
|
||||
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
|
||||
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as
|
||||
| FindingCheckStatus
|
||||
| undefined;
|
||||
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
|
||||
const reasoning = stringOption(parsed.options, ["reasoning", "reason"]);
|
||||
|
||||
const normalizeStatus = (raw: string): FindingCheckStatus => {
|
||||
const upper = raw.trim().toUpperCase();
|
||||
if (["PASS", "通过", "合规", "OK", "YES"].includes(upper)) return "PASS";
|
||||
if (["FAIL", "未通过", "不通过", "违规", "NO"].includes(upper)) return "FAIL";
|
||||
if (["SKIP", "跳过", "不适用", "NA", "N/A"].includes(upper)) return "SKIP";
|
||||
return "PENDING";
|
||||
};
|
||||
|
||||
const updates: Array<{
|
||||
index: number;
|
||||
status: FindingCheckStatus;
|
||||
evidence?: string;
|
||||
reasoning?: string;
|
||||
}> = [];
|
||||
|
||||
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
|
||||
updates.push({ index: pointIndex, status: normalizeStatus(statusInput), evidence, reasoning });
|
||||
} else if (evalStr) {
|
||||
const segments = evalStr
|
||||
.split(/[;\n]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/^(\d+)\s*=\s*([A-Za-z\u4e00-\u9fa5]+)(?::(.*))?$/);
|
||||
if (match) {
|
||||
const idx = parseInt(match[1], 10);
|
||||
const status = normalizeStatus(match[2]);
|
||||
const desc = match[3]?.trim();
|
||||
updates.push({ index: idx, status, evidence: desc, reasoning: desc });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
throw new Error(
|
||||
`请提供核验判定参数,例如:\n` +
|
||||
` hose-aipro review --run ${runRecord.shortId || runRecord.id} --eval "1=PASS:已上传发票; 2=FAIL:住宿超标; 3=SKIP"\n`
|
||||
);
|
||||
}
|
||||
|
||||
for (const item of updates) {
|
||||
const target = findings[item.index - 1];
|
||||
if (!target) {
|
||||
throw new Error(`要点编号超出范围: #${item.index} (当前要点总数: ${findings.length})`);
|
||||
}
|
||||
repo.updateFinding(target.id, {
|
||||
checkStatus: item.status,
|
||||
evidence: item.evidence,
|
||||
reasoning: item.reasoning,
|
||||
});
|
||||
}
|
||||
|
||||
const updatedFindings = repo.getFindingsByRunId(runRecord.id);
|
||||
const passCount = updatedFindings.filter((f) => f.checkStatus === "PASS").length;
|
||||
const failCount = updatedFindings.filter((f) => f.checkStatus === "FAIL").length;
|
||||
const skipCount = updatedFindings.filter((f) => f.checkStatus === "SKIP").length;
|
||||
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "review",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `在会话 [${runRecord.shortId || runRecord.id}] 录入 ${updates.length} 项要点核验(通过: ${passCount}, 违规: ${failCount}, 待核验: ${pendingCount})`,
|
||||
});
|
||||
|
||||
const checklistOutput = updatedFindings.map((f, i) => ({
|
||||
要点编号: i + 1,
|
||||
严格程度: f.strictness,
|
||||
归属规则: f.ruleCode ?? "-",
|
||||
审核要点: f.clauseText,
|
||||
核验状态:
|
||||
f.checkStatus === "PASS"
|
||||
? "通过"
|
||||
: f.checkStatus === "FAIL"
|
||||
? "未通过"
|
||||
: f.checkStatus === "SKIP"
|
||||
? "已跳过"
|
||||
: "待核验",
|
||||
事实依据: Array.from(new Set([f.evidence, f.reasoning].filter(Boolean))).join(" - ") || "-",
|
||||
}));
|
||||
|
||||
const resultObj = {
|
||||
会话ID: runRecord.shortId || runRecord.id,
|
||||
单号: runRecord.documentSn,
|
||||
要点总数: updatedFindings.length,
|
||||
已通过: passCount,
|
||||
未通过: failCount,
|
||||
已跳过: skipCount,
|
||||
待核验: pendingCount,
|
||||
核验清单: checklistOutput,
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(resultObj, null, 2) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProDecide(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, command, repo, operator, rawArgs, getClient } = ctx;
|
||||
const runHandle =
|
||||
stringOption(parsed.options, ["run", "r"]) ||
|
||||
positional
|
||||
.slice(1)
|
||||
.find(
|
||||
(p) => !["approve", "reject", "pass", "同意", "通过", "驳回", "拒绝"].includes(p.toLowerCase())
|
||||
);
|
||||
if (!runHandle) {
|
||||
throw new Error("请提供会话 ID: hose-aipro decide <approve|reject> --run <runId> --opinion '...'");
|
||||
}
|
||||
const runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
|
||||
let actionRaw: string | undefined = positional[1]?.toLowerCase();
|
||||
if (actionRaw === runHandle?.toLowerCase()) {
|
||||
actionRaw = positional[2]?.toLowerCase();
|
||||
}
|
||||
if (!actionRaw || actionRaw.startsWith("-")) {
|
||||
actionRaw = stringOption(parsed.options, ["action", "a"])?.toLowerCase();
|
||||
}
|
||||
if (command === "approve") {
|
||||
actionRaw = "approve";
|
||||
} else if (command === "reject") {
|
||||
actionRaw = "reject";
|
||||
}
|
||||
|
||||
let action: "APPROVE" | "REJECT" | undefined;
|
||||
if (["approve", "pass", "同意", "通过"].includes(actionRaw || "")) {
|
||||
action = "APPROVE";
|
||||
} else if (["reject", "refuse", "驳回", "拒绝"].includes(actionRaw || "")) {
|
||||
action = "REJECT";
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
throw new Error("请指定要执行的审批动作: hose-aipro decide approve 或 hose-aipro decide reject");
|
||||
}
|
||||
|
||||
const opinion = (
|
||||
stringOption(parsed.options, ["opinion", "comment", "message", "m", "审批意见", "意见"]) || ""
|
||||
).trim();
|
||||
|
||||
if (!opinion) {
|
||||
throw new Error("必须提供小于 150 字的审批意见: --opinion '<审批意见>'");
|
||||
}
|
||||
|
||||
const findings = repo.getFindingsByRunId(runRecord.id);
|
||||
|
||||
validateGatewayAction({
|
||||
documentSn: runRecord.documentSn,
|
||||
findings,
|
||||
requestedAction: action === "APPROVE" ? "approve" : "reject",
|
||||
opinion,
|
||||
});
|
||||
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
let executionStatus = "模拟完成(未带 --apply,未真实修改线上单据)";
|
||||
|
||||
if (apply) {
|
||||
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
|
||||
if (!confirmed) {
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
|
||||
}
|
||||
const { prompt } = await import("../../helpers.js");
|
||||
const ans = await prompt(
|
||||
`[AI PRO] 即将向合思系统真实执行审批流转 [${action === "APPROVE" ? "同意" : "驳回"}],确认执行?输入 yes: `
|
||||
);
|
||||
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
|
||||
}
|
||||
|
||||
const context = await getClient();
|
||||
if (action === "APPROVE") {
|
||||
await approveBill(context.client, context.corpId, runRecord.documentSn, {
|
||||
comment: opinion,
|
||||
});
|
||||
} else {
|
||||
await rejectBill(context.client, context.corpId, runRecord.documentSn, {
|
||||
comment: opinion,
|
||||
});
|
||||
}
|
||||
executionStatus = "已真实下发合思系统流转";
|
||||
}
|
||||
|
||||
repo.updateApprovalRun(runRecord.id, {
|
||||
decision: action,
|
||||
decisionSummary: opinion,
|
||||
failedRulesCount: findings.filter((f) => f.checkStatus === "FAIL").length,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "decide",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
decision: action,
|
||||
summary: `审批动作 [${action === "APPROVE" ? "同意" : "驳回"}] (${executionStatus})`,
|
||||
});
|
||||
|
||||
const resultObj = {
|
||||
会话ID: runRecord.shortId || runRecord.id,
|
||||
单号: runRecord.documentSn,
|
||||
执行动作: action === "APPROVE" ? "同意" : "驳回",
|
||||
审批意见: opinion,
|
||||
流转状态: executionStatus,
|
||||
网关状态: "放行",
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(resultObj, null, 2) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import type { ApprovalRunRecord } from "../../../domains/approval/index.js";
|
||||
import { VERSION } from "../../../version.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { formatExpiresAt, printJson, printTable } from "../../printer.js";
|
||||
import type { AiProCommandResult, AiProExecutionContext } from "./types.js";
|
||||
|
||||
export async function handleAiProStatus(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { repo, corp, corpId, operator, runtime, parsed } = ctx;
|
||||
const scopes = repo.listScopes("active");
|
||||
const rules = repo.listRules();
|
||||
const runs = corpId ? repo.listRuns({ corpId }) : repo.listRuns();
|
||||
const pendingRuns = runs.filter((r) => r.decision === "PENDING");
|
||||
const recentLogs = repo.listAiProLogs(undefined, 5);
|
||||
const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]);
|
||||
|
||||
const corpStaffId = corp?.credentials?.staffId || corp?.staffId || "-";
|
||||
const corpStaffName = corp?.staffName || corp?.session?.staffName || null;
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
|
||||
if (isJson) {
|
||||
return {
|
||||
stdout:
|
||||
JSON.stringify(
|
||||
{
|
||||
tool: "hose-aipro",
|
||||
version: VERSION,
|
||||
corp: corp
|
||||
? {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
staffId: corpStaffId,
|
||||
userName: corpStaffName,
|
||||
source: corp.source,
|
||||
expiresAt: corpExpiresAt,
|
||||
expired: corpExpiresAt ? corpExpiresAt <= Date.now() : false,
|
||||
baseUrl: corp.baseUrl,
|
||||
}
|
||||
: null,
|
||||
operator,
|
||||
ruleEngine: {
|
||||
scopesCount: scopes.length,
|
||||
rulesCount: rules.length,
|
||||
scopes: scopes.map((s) => ({
|
||||
index: s.index,
|
||||
scope: s.scope,
|
||||
ruleCount: s.ruleCount,
|
||||
})),
|
||||
},
|
||||
sessions: {
|
||||
total: runs.length,
|
||||
pending: pendingRuns.length,
|
||||
},
|
||||
recentLogsCount: recentLogs.length,
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思 AI PRO 确定性审批网关运行上下文 (v${VERSION}) ======`,
|
||||
` 当前连接企业 : ${corp ? `${corp.name} (${corp.id})` : "⚠️ 未指定企业"}`,
|
||||
` 当前操作工号 : ${corpStaffId}`,
|
||||
` 操作员标识 : ${operator}`,
|
||||
` 凭证有效状态 : ${corp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 主站 BaseURL : ${corp?.baseUrl || "-"}`,
|
||||
` 规约场景库 : 已加载 ${scopes.length} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ") || "无"}),共 ${rules.length} 条仲裁规则`,
|
||||
` 未结审批会话 : ${pendingRuns.length} 个待决断会话 (当前企业历史总会话: ${runs.length} 个)`,
|
||||
"",
|
||||
"提示:",
|
||||
" - 查看规约场景列表: hose-aipro scopes",
|
||||
" - 切换全局工作企业: hose-use corps switch <企业ID>",
|
||||
" - 临时指定执行企业: hose-aipro --corp=<企业ID> <子命令>",
|
||||
" - 单据审批全流程 : hose-aipro bind <单号> <索引号> -> hose-aipro review -> hose-aipro decide",
|
||||
"",
|
||||
];
|
||||
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAiProLogs(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, repo, runtime, targetSn } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
} else if (targetSn) {
|
||||
const maybeRun = repo.getRunByHandle(targetSn);
|
||||
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === targetSn.toUpperCase()) {
|
||||
runRecord = maybeRun;
|
||||
}
|
||||
}
|
||||
|
||||
const filter: { runId?: string; documentSn?: string } = {};
|
||||
if (runRecord) {
|
||||
filter.runId = runRecord.shortId || runRecord.id;
|
||||
} else if (runHandle) {
|
||||
filter.runId = runHandle;
|
||||
}
|
||||
if (targetSn && targetSn !== runRecord?.shortId) {
|
||||
filter.documentSn = targetSn;
|
||||
}
|
||||
|
||||
const logs = repo.listAiProLogs(filter, limit);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ total: logs.length, logs }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (logs.length === 0) {
|
||||
const targetDesc = filter.runId
|
||||
? ` (会话: ${filter.runId})`
|
||||
: filter.documentSn
|
||||
? ` (单号: ${filter.documentSn})`
|
||||
: "";
|
||||
return {
|
||||
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetDesc}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = [
|
||||
"#",
|
||||
"发生时间",
|
||||
"会话 ID",
|
||||
"动作 (Action)",
|
||||
"单号",
|
||||
"操作人",
|
||||
"状态",
|
||||
"网关决策",
|
||||
"摘要说明",
|
||||
];
|
||||
const rows = logs.map((l, i) => [
|
||||
i + 1,
|
||||
new Date(l.createdAt).toLocaleString("zh-CN"),
|
||||
l.runId || "-",
|
||||
l.action,
|
||||
l.documentSn || "-",
|
||||
l.operator || "-",
|
||||
l.status === "SUCCESS" ? "✅ SUCCESS" : l.status === "BLOCKED" ? "🚫 BLOCKED" : "❌ ERROR",
|
||||
l.decision || "-",
|
||||
l.summary || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO 全流程监控流水账本] (共登记 ${logs.length} 条记录) ======\n`;
|
||||
|
||||
return { stdout: title + table, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export function handleAiProHelp(ctx: AiProExecutionContext): AiProCommandResult {
|
||||
const { corp, operator, jsonMode } = ctx;
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
const corpBanner = corp
|
||||
? `[当前连接企业: ${corp.name} (${corp.id}) | 操作人: ${operator} | 凭证状态: ${formatExpiresAt(corpExpiresAt)}]\n[全局切换: hose-use corps switch <企业ID> | 临时指定: hose-aipro --corp=<企业ID>]`
|
||||
: `[当前企业: 未指定 | 请先运行 hose-use auth login 或带上 --corp=<企业ID>]`;
|
||||
|
||||
const helpText = `
|
||||
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
|
||||
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
|
||||
|
||||
${corpBanner}
|
||||
|
||||
核心工作流:
|
||||
0. 查看 AI PRO 运行上下文与当前绑定企业:
|
||||
hose-aipro status # 查看当前企业、操作人、规则库统计与待办会话
|
||||
|
||||
1. 查看规约场景索引库 (获取规则索引号):
|
||||
hose-aipro scopes # 列出所有场景索引 (Index / Scope / 规则数)
|
||||
|
||||
2. 查看场景审核要点清单 (纯规则元数据,与单据无关):
|
||||
hose-aipro points <索引号|场景名称> # 例如: hose-aipro points 1
|
||||
|
||||
3. 显式绑定单据并挂载审核要点:
|
||||
hose-aipro bind <单号> <索引号> # 例如: hose-aipro bind S26000001 1
|
||||
|
||||
4. 查看单据审核清单与核验进度:
|
||||
hose-aipro checklist <单号> # 查看当前单据要点核验进度与挂载场景
|
||||
|
||||
5. 逐项录入事实核验打标:
|
||||
hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP"
|
||||
hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票"
|
||||
|
||||
6. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支):
|
||||
hose-aipro decide <单号> # 预审仿真 (Dry Run)
|
||||
hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论
|
||||
|
||||
7. 全流程监控日志流水查看:
|
||||
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
|
||||
`;
|
||||
return {
|
||||
stdout: jsonMode ? printJson({ help: helpText.trim() }) + "\n" : helpText.trim() + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import type { ApprovalRepository, ApprovalService } from "../../../domains/approval/index.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export interface AiProExecutionContext {
|
||||
rawArgs: string[];
|
||||
parsed: CliParsedArgs;
|
||||
runtime: CliRuntime;
|
||||
corp: CorpConfig | null;
|
||||
corpId?: string;
|
||||
operator: string;
|
||||
positional: string[];
|
||||
command: string;
|
||||
targetSn?: string;
|
||||
jsonMode: boolean;
|
||||
repo: ApprovalRepository;
|
||||
service: ApprovalService;
|
||||
requireCorpId: () => string;
|
||||
getClient: () => Promise<{ client: KyInstance; corpId: string }>;
|
||||
}
|
||||
|
||||
export type AiProCommandResult = CliResult;
|
||||
|
||||
export function parseIntegerList(input?: string): number[] {
|
||||
if (!input) return [];
|
||||
const trimmed = input.trim();
|
||||
const list: number[] = [];
|
||||
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
||||
try {
|
||||
const parsedJson = JSON.parse(trimmed);
|
||||
if (Array.isArray(parsedJson)) {
|
||||
for (const item of parsedJson) {
|
||||
const n = Number(item);
|
||||
if (!isNaN(n)) list.push(n);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
const inner = trimmed.replace(/[\[\]]/g, "");
|
||||
const parts = inner.split(/[,,\s]+/).filter(Boolean);
|
||||
for (const p of parts) {
|
||||
const n = Number(p.replace(/['"]/g, ""));
|
||||
if (!isNaN(n)) list.push(n);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { fetchWorkbenchAppsList } from "../../domains/menu/tools.js";
|
||||
import { getPlatform } from "../../domains/datalink/api.js";
|
||||
import { getPlatform } from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
|
||||
@@ -19,6 +19,9 @@ import {
|
||||
addNodeBill,
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
inspectFormSpecification,
|
||||
formatFormPriorityList,
|
||||
hasLinkageOverridePriority,
|
||||
} from "../../domains/bill/tools.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
@@ -655,7 +658,95 @@ export async function handleBillCommand(
|
||||
};
|
||||
}
|
||||
|
||||
case "spec":
|
||||
case "specification": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "spec", "specification", "specification-id", "specificationId"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供单据模板 ID (specificationId): hose-use bill spec <specificationId>");
|
||||
}
|
||||
|
||||
const inspection = await inspectFormSpecification(await getClient(), corpId, target);
|
||||
if (!inspection) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, specificationId: target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到单据模板定义: ${target}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { specification: spec, warnings } = inspection;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...spec,
|
||||
warnings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = spec.components.map((comp, idx) => {
|
||||
const priorityStr = formatFormPriorityList(comp.priorityList);
|
||||
const overrideRisk = hasLinkageOverridePriority(comp.priorityList) ? "⚠️ 联动覆盖手动" : "-";
|
||||
return [
|
||||
idx + 1,
|
||||
comp.name,
|
||||
comp.label || "-",
|
||||
comp.type,
|
||||
comp.optional === false ? "🔴 必填" : "⚪ 选填",
|
||||
comp.isLinkageAssignment ? "🟢 开启(true)" : "⚪ 关闭(false)",
|
||||
comp.assignmentRule || "-",
|
||||
priorityStr,
|
||||
overrideRisk,
|
||||
];
|
||||
});
|
||||
|
||||
const outLines = [
|
||||
`====== 单据模板定义 (${spec.name || spec.id}) ======`,
|
||||
` 模板 ID : ${spec.id}`,
|
||||
` 模板名称 : ${spec.name || "-"}`,
|
||||
` 单据类型 : ${spec.type || "-"}`,
|
||||
` 状态 : ${spec.active ? "🟢 启用" : "🔴 停用"}`,
|
||||
` 字段总数 : ${spec.components.length} 个`,
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "字段标识 (name)", "显示名称 (label)", "类型 (type)", "必填", "联动赋值 (isLinkageAssignment)", "联动规则 (assignmentRule)", "赋值优先级 (priorityList)", "覆盖风险"],
|
||||
rows
|
||||
)
|
||||
: "暂无表单组件定义",
|
||||
];
|
||||
|
||||
if (warnings.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 联动赋值与优先级诊断 ──");
|
||||
for (const w of warnings) {
|
||||
outLines.push(` • ${w}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,7 +454,8 @@ export async function handleGenerateCorpLink(
|
||||
};
|
||||
}
|
||||
|
||||
const expiresIn = numberOption(parsed.options, ["expire", "expires", "ttl"]) ?? 7200;
|
||||
const expiresIn =
|
||||
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
|
||||
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
|
||||
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
|
||||
|
||||
|
||||
@@ -514,7 +514,13 @@ export async function handleFeeTypeCommand(
|
||||
};
|
||||
}
|
||||
|
||||
// ── 8. 查看表单字段配置 (fields / specs) ─────────────────────────────────────
|
||||
// ── 8. 查看单据模板定义 (spec / specification) ─────────────────────────────
|
||||
if (["spec", "specification"].includes(action)) {
|
||||
const { handleBillCommand } = await import("./bill.js");
|
||||
return handleBillCommand({ ...parsed, area: "bill", action: "spec" }, runtime);
|
||||
}
|
||||
|
||||
// ── 9. 查看表单字段配置 (fields / specs) ─────────────────────────────────────
|
||||
if (["fields", "specs", "schema"].includes(action)) {
|
||||
const target =
|
||||
parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core/embedded-openapi.js";
|
||||
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../packaging/embedded-openapi.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
@@ -196,4 +196,63 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(res.stdout).toContain("台账重算任务已成功触发");
|
||||
expect(recomputeSpy).toHaveBeenCalledWith(expect.anything(), "corp-1", "r-1");
|
||||
});
|
||||
|
||||
it("record get 支持仅传 <recordId> 免传应用与业务对象", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(
|
||||
spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: {
|
||||
id: "ID01DirectRecord",
|
||||
name: "直查记录",
|
||||
code: "DR-01",
|
||||
entityId: "entity-1",
|
||||
active: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
spies.push(spyOn(api, "listPlatforms").mockResolvedValue([mockPlatform] as any));
|
||||
spies.push(spyOn(api, "listPlatformEntities").mockResolvedValue([mockEntity] as any));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["get", "ID01DirectRecord"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("直查记录");
|
||||
expect(res.stdout).toContain("DR-01");
|
||||
});
|
||||
|
||||
it("record batch-edit --dry-run 生成安全合并预览且不发送真实写请求", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(
|
||||
spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
active: true,
|
||||
name: "旧名称",
|
||||
code: "P-1",
|
||||
},
|
||||
})
|
||||
);
|
||||
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
|
||||
spies.push(editSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "record",
|
||||
args: ["batch-edit", "platform-1", "entity-1"],
|
||||
options: { ids: "r-1", data: '{"名称":"新名称"}', "dry-run": true },
|
||||
raw: ["platform", "record", "batch-edit", "platform-1", "entity-1", "--ids=r-1", "--dry-run"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("Dry-Run 预览");
|
||||
expect(editSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+465
-32
@@ -1,8 +1,18 @@
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import { buildKeywordFilter, resolveEntity, resolvePlatform, selectRecordFields } from "../../domains/datalink/services.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
import * as api from "../../domains/datalink/services.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
resolveEntity,
|
||||
resolvePlatform,
|
||||
selectRecordFields,
|
||||
type BatchEditTargetItem,
|
||||
} from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
@@ -61,10 +71,15 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "audit":
|
||||
case "check":
|
||||
case "health": return handleAudit(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-batch-edit":
|
||||
case "batch-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
@@ -72,7 +87,7 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, record, permissions, imports\n`, exitCode: 1 };
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,12 +141,23 @@ async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const fetchAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
const page = await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, query: { start, count, filterBy, fields }, total: page.total, returned: data.length, data };
|
||||
const result = {
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, fields },
|
||||
total: page.total,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
@@ -145,7 +171,89 @@ async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
|
||||
}
|
||||
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
|
||||
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
|
||||
filterBy,
|
||||
pageSize,
|
||||
});
|
||||
const report = auditEntityRecords(page.data, resolved.entity, {
|
||||
checkFields,
|
||||
activeOnly,
|
||||
total: page.total,
|
||||
});
|
||||
|
||||
const output = {
|
||||
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
|
||||
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
|
||||
...report,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const issueRows = report.issues.map((issue, idx) => [
|
||||
idx + 1,
|
||||
issue.recordId,
|
||||
issue.recordCode || "-",
|
||||
issue.recordName || "-",
|
||||
issue.active ? "🟢 启用" : "🔴 停用",
|
||||
issue.type,
|
||||
issue.fieldLabel,
|
||||
issue.message,
|
||||
]);
|
||||
|
||||
const patchRows = report.suggestedPatches.map((patch, idx) => [
|
||||
idx + 1,
|
||||
patch.id,
|
||||
patch.code || "-",
|
||||
patch.name || "-",
|
||||
JSON.stringify(patch.form),
|
||||
patch.reason,
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
|
||||
printKeyValue({
|
||||
"总记录数": report.totalRecords,
|
||||
"本次体检记录数": report.auditedRecords,
|
||||
"健康记录数": report.healthyRecords,
|
||||
"异常记录数": report.affectedRecordCount,
|
||||
"总问题项数": report.issueCount,
|
||||
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
||||
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
||||
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
||||
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
|
||||
}),
|
||||
"",
|
||||
"── 异常诊断明细 ──",
|
||||
issueRows.length
|
||||
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
|
||||
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
||||
];
|
||||
|
||||
if (patchRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
|
||||
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -170,6 +278,291 @@ async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
function formatDirectRecordFieldValue(val: unknown): string {
|
||||
if (val === undefined || val === null || val === "") return "";
|
||||
if (typeof val === "object" && !Array.isArray(val)) {
|
||||
const obj = val as Record<string, unknown>;
|
||||
if ("standard" in obj) {
|
||||
return `${obj.standard} ${obj.standardStrCode || obj.standardUnit || "CNY"}`;
|
||||
}
|
||||
const nestedDl =
|
||||
obj.data && typeof obj.data === "object" && (obj.data as Record<string, unknown>).dataLink
|
||||
? ((obj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: undefined;
|
||||
if (nestedDl && typeof nestedDl === "object") {
|
||||
const eId = String(nestedDl.entityId || "");
|
||||
const title =
|
||||
nestedDl[`E_${eId}_name`] ?? nestedDl.name ?? nestedDl[`E_${eId}_code`] ?? nestedDl.code ?? "";
|
||||
return `${obj.id || nestedDl.id}${title ? ` (${title})` : ""}`;
|
||||
}
|
||||
if (typeof obj.id === "string" && (obj.name || obj.code)) {
|
||||
return `${obj.name || obj.code} (${obj.id})`;
|
||||
}
|
||||
}
|
||||
return cell(val);
|
||||
}
|
||||
|
||||
async function handleDirectRecordGet(
|
||||
recordId: string,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const detail = await api.getRecordDetail(clients.ekbClient, corpId, recordId);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const record = (detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>;
|
||||
const entityId = String(record.entityId || "");
|
||||
const nameKey = entityId ? `E_${entityId}_name` : "name";
|
||||
const codeKey = entityId ? `E_${entityId}_code` : "code";
|
||||
const nameVal = record.name ?? record["名称"] ?? record[nameKey];
|
||||
const codeVal = record.code ?? record["编码"] ?? record[codeKey];
|
||||
const formatTime = (time: unknown) =>
|
||||
typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象 ID (entityId)", entityId || "-"],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
const skipKeys = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"name",
|
||||
"code",
|
||||
nameKey,
|
||||
codeKey,
|
||||
"active",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"visibility",
|
||||
"form",
|
||||
]);
|
||||
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (skipKeys.has(k)) continue;
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
const label = entityId && k.startsWith(`E_${entityId}_`) ? `${k.slice(`E_${entityId}_`.length)} (${k})` : k;
|
||||
rows.push([label, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
rows.push([k, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 记录详情 (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJsonDataOption(parsed: CliParsedArgs): Record<string, unknown> {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
if (dataStr) {
|
||||
try {
|
||||
return JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
if (filePath) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function handleBatchEdit(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
appIndex: number,
|
||||
entityIndex: number
|
||||
): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) {
|
||||
throw new Error(
|
||||
"用法: hose-use platform record batch-edit <应用> <业务对象> (--ids=<id1,id2> | --filter=<expr>) (--data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
|
||||
);
|
||||
}
|
||||
|
||||
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
const concurrency = numberOption(parsed.options, ["concurrency", "c"], 8);
|
||||
const activeOpt =
|
||||
parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
|
||||
if (!dataStr && !filePath) {
|
||||
throw new Error("请通过 --data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量编辑业务对象记录",
|
||||
`hose-use platform record batch-edit ${resolved.platform.id} ${resolved.entity.id} --yes`
|
||||
);
|
||||
|
||||
let fileContent: unknown;
|
||||
if (filePath) {
|
||||
try {
|
||||
fileContent = JSON.parse(readFileSync(filePath, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
let uniformPatch: Record<string, unknown> | undefined;
|
||||
if (dataStr) {
|
||||
try {
|
||||
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
} else if (
|
||||
fileContent &&
|
||||
typeof fileContent === "object" &&
|
||||
!Array.isArray(fileContent) &&
|
||||
!Object.values(fileContent as Record<string, unknown>).every(
|
||||
(v) => v && typeof v === "object" && !Array.isArray(v) && !("standard" in (v as Record<string, unknown>))
|
||||
)
|
||||
) {
|
||||
uniformPatch = fileContent as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const targets: BatchEditTargetItem[] = [];
|
||||
if (Array.isArray(fileContent)) {
|
||||
for (const entry of fileContent) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const item = entry as Record<string, unknown>;
|
||||
const recordId = String(item.id ?? item.recordId ?? item.dataLinkId ?? "").trim();
|
||||
const patchForm =
|
||||
(item.form as Record<string, unknown>) ??
|
||||
(item.data as Record<string, unknown>) ??
|
||||
uniformPatch ??
|
||||
{};
|
||||
if (recordId) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm,
|
||||
active: typeof item.active === "boolean" ? item.active : activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (!uniformPatch && fileContent && typeof fileContent === "object") {
|
||||
for (const [recordId, patchVal] of Object.entries(fileContent as Record<string, unknown>)) {
|
||||
if (patchVal && typeof patchVal === "object" && !Array.isArray(patchVal)) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm: patchVal as Record<string, unknown>,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targets.length === 0) {
|
||||
if (!uniformPatch) {
|
||||
throw new Error("未解析到有效的批量更新内容");
|
||||
}
|
||||
let recordIds = splitFields(idsOpt);
|
||||
if (recordIds.length === 0 && filterBy) {
|
||||
const page = await fetchAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy }
|
||||
);
|
||||
recordIds = page.data
|
||||
.map((r) => {
|
||||
const dl =
|
||||
r.dataLink && typeof r.dataLink === "object"
|
||||
? (r.dataLink as Record<string, unknown>)
|
||||
: r;
|
||||
return String(dl.id ?? r.id ?? "").trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (recordIds.length === 0) {
|
||||
throw new Error("请通过 --ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
|
||||
}
|
||||
for (const id of recordIds) {
|
||||
targets.push({
|
||||
recordId: id,
|
||||
patchForm: uniformPatch,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const dryRun = isDryRun(parsed, runtime);
|
||||
const results = await batchSafeEditRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity,
|
||||
targets,
|
||||
{ concurrency, dryRun }
|
||||
);
|
||||
|
||||
const succeeded = results.filter((r) => r.status === "updated" || r.status === "preview").length;
|
||||
const failed = results.filter((r) => r.status === "failed").length;
|
||||
const summary = {
|
||||
dryRun,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
total: results.length,
|
||||
succeeded,
|
||||
failed,
|
||||
items: results,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(summary, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = results.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.recordId,
|
||||
item.status === "preview" ? "🔍 预览 (dry-run)" : item.status === "updated" ? "✅ 已更新" : "❌ 失败",
|
||||
item.payload ? Object.keys(item.payload.form).length : "-",
|
||||
item.error || "-",
|
||||
]);
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
|
||||
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
|
||||
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
|
||||
printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows),
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
@@ -177,6 +570,10 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (action === "batch-edit" || action === "record-batch-edit") {
|
||||
return handleBatchEdit(parsed, runtime, 0, 1);
|
||||
}
|
||||
|
||||
if (action.startsWith("record-")) {
|
||||
subAction = action.replace("record-", "");
|
||||
appIndex = 0;
|
||||
@@ -184,7 +581,20 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (["get", "show", "detail", "toggle", "state", "edit", "update", "recompute", "recalc"].includes(firstArg)) {
|
||||
if (
|
||||
[
|
||||
"get",
|
||||
"show",
|
||||
"detail",
|
||||
"toggle",
|
||||
"state",
|
||||
"edit",
|
||||
"update",
|
||||
"batch-edit",
|
||||
"recompute",
|
||||
"recalc",
|
||||
].includes(firstArg)
|
||||
) {
|
||||
subAction = firstArg;
|
||||
appIndex = 1;
|
||||
entityIndex = 2;
|
||||
@@ -197,6 +607,16 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
}
|
||||
}
|
||||
|
||||
if (subAction === "batch-edit") {
|
||||
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
||||
}
|
||||
|
||||
// 支持 hose-use platform record get <recordId> 或 hose-use platform record <recordId> 免应用/实体直接查询
|
||||
const remainingArgs = parsed.args.slice(appIndex);
|
||||
if (["get", "show", "detail"].includes(subAction) && remainingArgs.length === 1) {
|
||||
return handleDirectRecordGet(remainingArgs[0].trim(), runtime);
|
||||
}
|
||||
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
@@ -283,37 +703,49 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d", "f"]);
|
||||
let form: Record<string, unknown> = {};
|
||||
if (dataStr) {
|
||||
try {
|
||||
form = JSON.parse(dataStr);
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
const form = parseJsonDataOption(parsed);
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const changes = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt ?? null,
|
||||
};
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"编辑业务对象记录",
|
||||
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
|
||||
|
||||
let payload: api.SafeRecordEditOptions extends never ? never : ReturnType<typeof api.buildSafeRecordEditPayload>;
|
||||
if (isRaw) {
|
||||
payload = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
};
|
||||
} else {
|
||||
let detail: Record<string, unknown> = {};
|
||||
try {
|
||||
detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
} catch (error) {
|
||||
// 在部分仅 mock 了 editRecord 的单元测试中,ekbClient.get 可能未定义,此时退化为空基础详情以兼容测试
|
||||
if (typeof (resolved.clients.ekbClient as any)?.get === "function") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
payload = api.buildSafeRecordEditPayload({
|
||||
entityId: resolved.entity.id,
|
||||
recordId,
|
||||
detail,
|
||||
fields: resolved.entity.fields,
|
||||
patchForm: form,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload);
|
||||
}
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
@@ -345,6 +777,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, recompute`);
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, batch-edit, recompute`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import { createSessionClient, getEasoClient } from "../../core/http/index.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import * as api from "../../domains/platform/services.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
|
||||
@@ -25,10 +25,11 @@ export async function handleServiceCommand(
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp);
|
||||
const limit = numberOption(parsed.options, ["limit", "count", "n"], 50) || 50;
|
||||
const store = new EventStore(join(SERVICE_STATE_DIR, `events-${corpId}.json`));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
|
||||
const store = new EventStore(stateFile || `corp:${corpId}`);
|
||||
const result = await pollEvents(client, corpId, store, limit);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "事件状态文件": join(SERVICE_STATE_DIR, `events-${corpId}.json`) })}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "存储后端": stateFile || "SQLite (observed_events)" })}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const config: ServiceConfig = {
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
getDefaultGlobalSkillDir,
|
||||
getSkillContent,
|
||||
installSkillFiles,
|
||||
} from "../../core/embedded-skill.js";
|
||||
} from "../../packaging/embedded-skill.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
|
||||
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../packaging/runtime.js";
|
||||
import { syncGlobalSkillIfPresent } from "../../packaging/embedded-skill.js";
|
||||
import { loadGlobalConfig } from "../../core/config/loader.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
|
||||
+471
-19
@@ -2,16 +2,21 @@ import {
|
||||
listAllWorkflows,
|
||||
findWorkflowsByTaskType,
|
||||
} from "../../domains/platform/services.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import * as api from "../../domains/platform/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { analyzeWorkflow } from "../../domains/platform/analysis.js";
|
||||
import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../domains/platform/analysis.js";
|
||||
import { getFormSpecification } from "../../domains/bill/tools.js";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { WorkflowDetailSchema } from "../../domains/platform/types.js";
|
||||
import { WorkflowDetailSchema, type WorkflowTaskExecution } from "../../domains/platform/types.js";
|
||||
import {
|
||||
createWorkflowDraft,
|
||||
beginWorkflowSave,
|
||||
@@ -24,6 +29,7 @@ import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -68,6 +74,9 @@ export async function handleWorkflowCommand(
|
||||
case "logs":
|
||||
case "log":
|
||||
return handleLogs(parsed, runtime);
|
||||
case "job":
|
||||
case "execution":
|
||||
return handleJob(parsed, runtime);
|
||||
case "check":
|
||||
case "health":
|
||||
return handleCheck(parsed, runtime);
|
||||
@@ -77,7 +86,7 @@ export async function handleWorkflowCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, check\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, check\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -226,12 +235,12 @@ async function resolveWorkflowPlatformId(
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
|
||||
pipelineId: string
|
||||
): Promise<string> {
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) return explicit;
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
|
||||
if (!match?.platformId) {
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId>`);
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId> 或 --app-id=<appId>`);
|
||||
}
|
||||
return match.platformId;
|
||||
}
|
||||
@@ -239,15 +248,36 @@ async function resolveWorkflowPlatformId(
|
||||
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
const result = analyzeWorkflow(detail);
|
||||
const specIds = extractWorkflowSpecificationIds(detail);
|
||||
const specifications: Record<string, WorkflowFormSpecLike | undefined> = {};
|
||||
if (specIds.length > 0) {
|
||||
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
|
||||
await Promise.all(
|
||||
specIds.map(async (specId) => {
|
||||
try {
|
||||
const spec = await getFormSpecification(clients.ekbClient, corpId, specId);
|
||||
if (spec) specifications[specId] = spec;
|
||||
} catch {
|
||||
// Ignore specification fetch failure in offline or restricted environments
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
const result = analyzeWorkflow(detail, { specifications });
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
|
||||
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
|
||||
return { stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({ "工作流 ID": detail.id, "根节点数": result.ast.length, "依赖节点数": result.dependencies.length, "诊断数": result.diagnostics.length }),
|
||||
printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
|
||||
"根节点数": result.ast.length,
|
||||
"依赖节点数": result.dependencies.length,
|
||||
"诊断数": result.diagnostics.length,
|
||||
}),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
@@ -277,17 +307,423 @@ async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
|
||||
async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.listWorkflowLogs(client, pipelineId, {
|
||||
const rawResult = await api.listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const filteredJobList = hasErrorFilter
|
||||
? rawResult.jobList.filter(
|
||||
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
|
||||
)
|
||||
: rawResult.jobList;
|
||||
const result = hasErrorFilter
|
||||
? { ...rawResult, jobList: filteredJobList }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 工作流运行日志 [${pipelineId}] ======\n${printKeyValue({ "执行次数": result.executeCount, "成功次数": result.successCount, "错误次数": result.errorCount, "日志条数": result.totalItems, "运行记录": result.jobList.length })}\n${printJson(result, runtime.outputOptions)}\n`, stderr: "", exitCode: 0 };
|
||||
|
||||
const rows = result.jobList.map((job, idx) => [
|
||||
idx + 1,
|
||||
job.id,
|
||||
job.state,
|
||||
job.successTaskCount,
|
||||
job.errorTaskCount,
|
||||
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)",
|
||||
job.durationTime ?? "-",
|
||||
job.startTime || "-",
|
||||
]);
|
||||
const tableStr = rows.length
|
||||
? printTable(
|
||||
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
|
||||
rows
|
||||
)
|
||||
: "暂无匹配的运行记录";
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流运行日志 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"执行次数": result.executeCount,
|
||||
"成功次数": result.successCount,
|
||||
"错误次数": result.errorCount,
|
||||
"日志条数": result.totalItems,
|
||||
"当前返回记录": result.jobList.length,
|
||||
}),
|
||||
"",
|
||||
tableStr,
|
||||
"\n提示: 运行 hose-use workflow job <jobId> [--failed] 下钻查看单次 Job 节点级报错与入参明细\n",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function createJobPiperClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<Awaited<ReturnType<typeof createPiperClientForCorp>>> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) {
|
||||
return createPiperClientForCorp(corp, explicit);
|
||||
}
|
||||
const clients = await createClientsForCorp(corp);
|
||||
try {
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, corpId);
|
||||
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
|
||||
if (firstActive?.id) {
|
||||
return await createPiperClientForCorp(corp, firstActive.id);
|
||||
}
|
||||
} catch {
|
||||
// Fall back to default easoClient
|
||||
}
|
||||
return clients.easoClient;
|
||||
}
|
||||
|
||||
async function enrichFailedExecutions(
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>,
|
||||
jobId: string,
|
||||
items: WorkflowTaskExecution[]
|
||||
): Promise<WorkflowTaskExecution[]> {
|
||||
const parentCache = new Map<string, WorkflowTaskExecution[]>();
|
||||
const enriched: WorkflowTaskExecution[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
if (item.parentId && (!item.currentLoopPath || !item.name || !item.form)) {
|
||||
let siblings = parentCache.get(item.parentId);
|
||||
if (!siblings) {
|
||||
try {
|
||||
const level = await api.getJobExecutionLevel(client, jobId, {
|
||||
parentId: item.parentId,
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
});
|
||||
siblings = level.items;
|
||||
} catch {
|
||||
siblings = [];
|
||||
}
|
||||
parentCache.set(item.parentId, siblings);
|
||||
}
|
||||
const matched = siblings.find((s) => s.id === item.id);
|
||||
if (matched) {
|
||||
const itemInputs = item.inputs;
|
||||
const matchedInputs = matched.inputs;
|
||||
const hasItemInputs = Array.isArray(itemInputs)
|
||||
? itemInputs.length > 0
|
||||
: Boolean(itemInputs && typeof itemInputs === "object" && Object.keys(itemInputs as Record<string, unknown>).length > 0);
|
||||
const itemOutputs = item.outputs;
|
||||
const matchedOutputs = matched.outputs;
|
||||
const hasItemOutputs = Boolean(
|
||||
itemOutputs && typeof itemOutputs === "object" && Object.keys(itemOutputs as Record<string, unknown>).length > 0
|
||||
);
|
||||
enriched.push({
|
||||
...matched,
|
||||
...item,
|
||||
name: item.name || matched.name,
|
||||
label: item.label || matched.label,
|
||||
displayName: item.displayName || matched.displayName,
|
||||
type: item.type || matched.type,
|
||||
status: item.status || matched.status,
|
||||
currentLoopPath: item.currentLoopPath || matched.currentLoopPath,
|
||||
levelIndex: item.levelIndex?.length ? item.levelIndex : matched.levelIndex,
|
||||
form: item.form ?? matched.form,
|
||||
details: item.details ?? matched.details,
|
||||
inputs: hasItemInputs ? itemInputs : matchedInputs,
|
||||
outputs: hasItemOutputs ? itemOutputs : matchedOutputs,
|
||||
error: item.error ?? matched.error,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
enriched.push(item);
|
||||
}
|
||||
return enriched;
|
||||
}
|
||||
|
||||
async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const jobId = parsed.args[0] || stringOption(parsed.options, ["id", "job-id", "jobId"]);
|
||||
if (!jobId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const client = await createJobPiperClient(parsed, runtime);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
|
||||
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
|
||||
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
|
||||
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
||||
|
||||
// 1. --logs=<executionId>
|
||||
if (logsExecutionId) {
|
||||
const logs = await api.getExecutionLogs(client, logsExecutionId);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ jobId, executionId: logsExecutionId, logs }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = logs.map((log, i) => [
|
||||
i + 1,
|
||||
String(log.id ?? "-"),
|
||||
String(log.createAt ?? (log as Record<string, unknown>).createTime ?? (log as Record<string, unknown>).timestamp ?? "-"),
|
||||
String(log.level || "INFO"),
|
||||
String(log.message || JSON.stringify(log)),
|
||||
]);
|
||||
return {
|
||||
stdout: [
|
||||
`====== 节点执行日志 (Job: ${jobId} | Execution: ${logsExecutionId}) ======`,
|
||||
rows.length ? printTable(["#", "日志 ID", "时间", "级别", "内容"], rows) : "该节点暂无输出日志",
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. --parent=<executionId>
|
||||
if (parentExecutionId) {
|
||||
const levelPage = await api.getJobExecutionLevel(client, jobId, {
|
||||
parentId: parentExecutionId,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
parentId: parentExecutionId,
|
||||
...levelPage,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = levelPage.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.name || "-",
|
||||
item.label || item.displayName || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const extraDetails: string[] = [];
|
||||
for (const item of levelPage.items) {
|
||||
if (item.form !== undefined || item.error?.message) {
|
||||
extraDetails.push(
|
||||
`\n── 节点明细 [${item.id}] (${item.name || "-"} | loop=${item.currentLoopPath || "-"} | status=${item.status}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
extraDetails.push(` 错误原因: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
extraDetails.push(` 传入表单 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
if (item.details !== undefined) {
|
||||
extraDetails.push(` 明细数据 (details): ${JSON.stringify(item.details)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 子节点执行层级明细 (Job: ${jobId} | Parent: ${parentExecutionId} | 共 ${levelPage.totalItems} 项) ======`,
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因"],
|
||||
rows
|
||||
)
|
||||
: "暂无子节点执行记录",
|
||||
...extraDetails,
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. --failed
|
||||
if (onlyFailed) {
|
||||
const [job, failedPage] = await Promise.all([
|
||||
api.getJob(client, jobId).catch(() => undefined),
|
||||
api.getJobFailedExecutions(client, jobId),
|
||||
]);
|
||||
const enrichedItems = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job: job ?? null,
|
||||
totalItems: failedPage.totalItems,
|
||||
items: enrichedItems,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = enrichedItems.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const formSummaries: string[] = [];
|
||||
for (const item of enrichedItems) {
|
||||
if (item.error?.message || item.form !== undefined) {
|
||||
formSummaries.push(
|
||||
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | status=${item.status} | loop=${item.currentLoopPath || "-"}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
formSummaries.push(` 错误详情: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
formSummaries.push(` 表单入参 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== Job 异常/跳过执行节点明细 (Job: ${jobId}) ======`,
|
||||
job
|
||||
? printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
})
|
||||
: "",
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
rows
|
||||
)
|
||||
: "未发现异常或报错跳过的执行节点",
|
||||
...formSummaries,
|
||||
"",
|
||||
].filter(Boolean).join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Default mode: Job overview + top-level tree + failed executions
|
||||
const [job, tree, failedPage] = await Promise.all([
|
||||
api.getJob(client, jobId),
|
||||
api.getJobExecutionTree(client, jobId),
|
||||
api.getJobFailedExecutions(client, jobId).catch(() => ({
|
||||
number: 1,
|
||||
size: 100,
|
||||
totalPages: 0,
|
||||
totalItems: 0,
|
||||
items: [] as WorkflowTaskExecution[],
|
||||
})),
|
||||
]);
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job,
|
||||
executionTree: tree,
|
||||
failedExecutions,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const treeRows = tree.map((node, idx) => [
|
||||
idx + 1,
|
||||
node.id,
|
||||
node.name || "-",
|
||||
node.label || node.displayName || "-",
|
||||
node.type || "-",
|
||||
node.status || "-",
|
||||
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
||||
node.error?.message || "-",
|
||||
]);
|
||||
|
||||
const failedRows = failedExecutions.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
||||
printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
"Job 状态 (state)": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
"顶层节点数": tree.length,
|
||||
"异常/跳过节点数": failedExecutions.length,
|
||||
}),
|
||||
"",
|
||||
"── 顶层节点执行树 ──",
|
||||
treeRows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
|
||||
treeRows
|
||||
)
|
||||
: "暂无顶层节点执行记录",
|
||||
];
|
||||
|
||||
if (failedRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 失败/报错跳过节点明细 (含循环子项) ──");
|
||||
outLines.push(
|
||||
printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
failedRows
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -315,15 +751,16 @@ async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
state: workflow.state,
|
||||
observedAt,
|
||||
}));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]) || join(WORKFLOW_STATE_DIR, `workflow-alerts-${runtime.selectedCorp!.id}.json`);
|
||||
const check = new WorkflowAlertStore(stateFile).observe(activeAlerts);
|
||||
const explicitStateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
|
||||
const stateFile = explicitStateFile || `sqlite:workflow_error_alerts:${runtime.selectedCorp!.id}`;
|
||||
const check = new WorkflowAlertStore(explicitStateFile || `corp:${runtime.selectedCorp!.id}`).observe(activeAlerts);
|
||||
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
|
||||
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
|
||||
const scanErrorCount = result.errors.length + logErrors.length;
|
||||
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态文件: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态存储: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
}
|
||||
|
||||
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -349,8 +786,17 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
|
||||
const result = await listAllWorkflows(clients, { page, pageSize });
|
||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||
const workflows = filterPlatformId
|
||||
? rawResult.workflows.filter(
|
||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||
)
|
||||
: rawResult.workflows;
|
||||
const result = filterPlatformId
|
||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
@@ -429,15 +875,21 @@ async function createWorkflowDetailClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
pipelineId: string,
|
||||
): Promise<{ client: Awaited<ReturnType<typeof createPiperClientForCorp>> }> {
|
||||
): Promise<{
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>;
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>;
|
||||
}> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
let platformId = explicit;
|
||||
if (!platformId) {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
|
||||
}
|
||||
return { client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient };
|
||||
return {
|
||||
client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient,
|
||||
clients,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { EkbError } from "../core/errors.js";
|
||||
|
||||
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
|
||||
|
||||
export class CliError extends Error {
|
||||
@@ -35,6 +37,15 @@ export function classifyCliError(error: unknown): {
|
||||
return { exitCode: error.exitCode, nextAction: error.nextAction };
|
||||
}
|
||||
|
||||
if (error instanceof EkbError) {
|
||||
if (error.code === "NOT_LOGGED_IN" || error.code === "AUTH_FAILED" || error.status === 401) {
|
||||
return { exitCode: 11, nextAction: "hose-use auth login" };
|
||||
}
|
||||
if (error.code === "VALIDATION_ERROR") {
|
||||
return { exitCode: 2 };
|
||||
}
|
||||
}
|
||||
|
||||
const value = error instanceof Error ? error.message : String(error);
|
||||
const status = responseStatus(error);
|
||||
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
|
||||
@@ -56,3 +67,4 @@ function responseStatus(error: unknown): number | undefined {
|
||||
const status = (response as { status?: unknown }).status;
|
||||
return typeof status === "number" ? status : undefined;
|
||||
}
|
||||
|
||||
+4
-4
@@ -39,10 +39,10 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照"] },
|
||||
bill: { summary: "单据检索与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象与底层记录", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录", record: "查看或修改单条记录", permissions: "查看权限", imports: "查看导入任务" }, options: ["--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作"] },
|
||||
feetype: { summary: "费用类型全生命周期管理", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
workflow: { summary: "工作流查询、草稿、运行排障与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流(含禁用/SKIP/联动覆盖检查)", job: "查看单次运行实例树、报错节点与MVEL日志", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照", "--failed 只看失败节点", "--parent=<executionId> 展开循环/分支子节点", "--logs=<executionId> 查看节点执行日志"] },
|
||||
bill: { summary: "单据检索、表单规格诊断与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", spec: "查看单据模板字段配置与联动覆盖规则", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象、全量记录安全更新与台账体检", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录(支持 --all 全量拉取)", record: "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)", audit: "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)", permissions: "查看权限", imports: "查看导入任务" }, options: ["--all 自动翻页拉取全量记录", "--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作", "--raw 跳过安全合并直接发送原始补丁"] },
|
||||
feetype: { summary: "费用类型全生命周期管理与模板规格查询", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", spec: "查看单据/申请模板字段与联动规则", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
|
||||
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
|
||||
message: { summary: "消息中心与通知管理", usage: "hose-use message <子命令>", commands: { list: "查询消息", count: "查看未读数", read: "标记消息已读", "read-all": "全部标记已读" } },
|
||||
|
||||
+30
-2
@@ -4,6 +4,7 @@ import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { CorpConfig } from "../core/config/types.js";
|
||||
import {
|
||||
createSessionClient,
|
||||
getEasoClient,
|
||||
getUnityClient,
|
||||
getScriptEngineClient,
|
||||
} from "../core/http/index.js";
|
||||
@@ -63,13 +64,23 @@ export function initCorpRuntime(
|
||||
|
||||
export async function createClientsForCorp(corp: CorpConfig) {
|
||||
const sessionClient = await createSessionClient(corp);
|
||||
const { client: unityClient } = await getUnityClient(corp);
|
||||
let easoClient: Awaited<ReturnType<typeof getEasoClient>>["client"];
|
||||
let unityClient: Awaited<ReturnType<typeof getUnityClient>>["client"];
|
||||
try {
|
||||
const easo = await getEasoClient(corp);
|
||||
easoClient = easo.client;
|
||||
unityClient = easo.client;
|
||||
} catch {
|
||||
const unity = await getUnityClient(corp);
|
||||
unityClient = unity.client;
|
||||
easoClient = unity.client;
|
||||
}
|
||||
return {
|
||||
corp,
|
||||
sessionClient,
|
||||
ekbClient: sessionClient,
|
||||
unityClient,
|
||||
easoClient: unityClient,
|
||||
easoClient,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,6 +90,23 @@ export async function createScriptEngineClientForCorp(corp: CorpConfig, platform
|
||||
|
||||
export const createPiperClientForCorp = createScriptEngineClientForCorp;
|
||||
|
||||
export function requireSelectedCorp(
|
||||
runtime: CliRuntime,
|
||||
message = "未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
): CorpConfig {
|
||||
if (!runtime.selectedCorp) {
|
||||
throw new Error(message);
|
||||
}
|
||||
return runtime.selectedCorp;
|
||||
}
|
||||
|
||||
export async function getSessionClientForRuntime(runtime: CliRuntime) {
|
||||
const corp = requireSelectedCorp(runtime);
|
||||
const corpId = corp.credentials?.corpId || corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp);
|
||||
return { corp, corpId, client };
|
||||
}
|
||||
|
||||
export function prompt(question: string): Promise<string> {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
|
||||
+99
-4
@@ -17,6 +17,7 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"check-only",
|
||||
"changelog",
|
||||
"log",
|
||||
"l",
|
||||
"local",
|
||||
"workspace",
|
||||
"external",
|
||||
@@ -25,13 +26,87 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"allowFull",
|
||||
"summary",
|
||||
"yes",
|
||||
"y",
|
||||
"confirm",
|
||||
"force-write",
|
||||
"forceWrite",
|
||||
"dry-run",
|
||||
"dryRun",
|
||||
"dryrun",
|
||||
"all",
|
||||
"a",
|
||||
"include-disabled",
|
||||
"flat",
|
||||
"flatten",
|
||||
"table",
|
||||
"specs",
|
||||
"spec",
|
||||
"fields",
|
||||
"recursive",
|
||||
"in-place",
|
||||
"inPlace",
|
||||
"value-json",
|
||||
"valueJson",
|
||||
"has-error",
|
||||
"hasError",
|
||||
"errors",
|
||||
"failed",
|
||||
"fail",
|
||||
"fail-on-alert",
|
||||
"failOnAlert",
|
||||
"includeDetail",
|
||||
"detail",
|
||||
"apply",
|
||||
"execute",
|
||||
"do",
|
||||
"refresh",
|
||||
"overwrite",
|
||||
"elevate",
|
||||
"elevate-hose",
|
||||
"as-hose",
|
||||
"no-elevate",
|
||||
"reveal",
|
||||
"plain",
|
||||
"save",
|
||||
"persist",
|
||||
"verify",
|
||||
"workbench",
|
||||
"w",
|
||||
"active-only",
|
||||
"activeOnly",
|
||||
"active",
|
||||
"read",
|
||||
"unread",
|
||||
"clear",
|
||||
"sms",
|
||||
"sync",
|
||||
"interactive",
|
||||
"i",
|
||||
"reminder",
|
||||
"remind",
|
||||
"keep-it-secret",
|
||||
"secret",
|
||||
"private",
|
||||
"mine",
|
||||
"my",
|
||||
"self",
|
||||
"distinct",
|
||||
"risk",
|
||||
"with-risk",
|
||||
"audit",
|
||||
"github",
|
||||
"gh",
|
||||
"gitea",
|
||||
"yingqing",
|
||||
"mirror",
|
||||
]);
|
||||
|
||||
function isExplicitBooleanLiteral(val: string | undefined): boolean {
|
||||
if (!val) return false;
|
||||
const lower = val.toLowerCase();
|
||||
return lower === "true" || lower === "false";
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
const options: Record<string, string | boolean | number> = {};
|
||||
const positional: string[] = [];
|
||||
@@ -53,11 +128,18 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
} else {
|
||||
const key = arg.slice(2);
|
||||
const keyLower = key.toLowerCase();
|
||||
const next = rawArgs[i + 1];
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key) || KNOWN_BOOLEAN_FLAGS.has(keyLower)) {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
if (isExplicitBooleanLiteral(next)) {
|
||||
const boolVal = next!.toLowerCase() === "true";
|
||||
options[key] = boolVal;
|
||||
if (key !== keyLower) options[keyLower] = boolVal;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
}
|
||||
} else {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options[key] = next;
|
||||
i++;
|
||||
@@ -86,6 +168,14 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
} else {
|
||||
options.o = true;
|
||||
}
|
||||
} else if (flag === "c") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.c = next;
|
||||
i++;
|
||||
} else {
|
||||
options.c = true;
|
||||
}
|
||||
} else {
|
||||
options[flag] = true;
|
||||
}
|
||||
@@ -103,6 +193,7 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
area,
|
||||
action,
|
||||
args,
|
||||
positional,
|
||||
options,
|
||||
raw: rawArgs,
|
||||
};
|
||||
@@ -128,7 +219,11 @@ export function booleanOption(
|
||||
for (const k of keys) {
|
||||
const val = options[k];
|
||||
if (typeof val === "boolean") return val;
|
||||
if (typeof val === "string") return val === "true" || val === "1";
|
||||
if (typeof val === "string") {
|
||||
const lower = val.toLowerCase();
|
||||
if (lower === "true" || lower === "1") return true;
|
||||
if (lower === "false" || lower === "0") return false;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
+4
-4
@@ -132,17 +132,17 @@ export function printHelp(target: string[] = []): string {
|
||||
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
|
||||
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, analyze, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
workflow 工作流管理 (list, get, find, analyze, job, toggle, publish, patch, save, history, logs, check)
|
||||
bill 单据检索、模板规格与审批动作 (list, get <单号|ID> [--risk], spec <模板ID>, approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
|
||||
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
|
||||
task 待办中心与审批任务 (todo, approved, records, submitted, cc)
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
app 应用管理 (桌面端工作台业务应用: list [--keyword], get <应用ID|名称>)
|
||||
menu 桌面端主导航菜单树与模块 (list, tree, apps)
|
||||
platform 自建应用与数据模型 (开放平台业务对象、字段与底层记录: list, get, entities, schema, records, permissions, imports)
|
||||
platform 自建应用与数据模型 (list, get, entities, schema, records [--all], record get|create|edit|batch-edit, audit, permissions, imports)
|
||||
datalink platform 的同义入口,面向 DataLink 业务对象查询
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, create, update, disable, enable, move, fields)
|
||||
feetype 费用类型管理与字段规格配置 (list, get, spec <模板ID>, create, update, disable, enable, move, fields)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
permission 权限模型快照 (get)
|
||||
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import { handleAuthCommand } from "./commands/auth.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleWorkflowCommand } from "./commands/workflow.js";
|
||||
import { handlePlatformCommand } from "./commands/platform.js";
|
||||
import { handleAppCommand } from "./commands/app.js";
|
||||
import { handleMenuCommand } from "./commands/menu.js";
|
||||
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 { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import { handleRuleCommand } from "./commands/rule.js";
|
||||
import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
export type CliCommandHandler = (
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
options: CliRunOptions
|
||||
) => Promise<CliResult>;
|
||||
|
||||
export interface CliCommandDefinition {
|
||||
area: string;
|
||||
aliases: string[];
|
||||
standing?: boolean | ((args: string[]) => boolean);
|
||||
handler: CliCommandHandler;
|
||||
}
|
||||
|
||||
export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "context",
|
||||
aliases: ["status", "whoami", "env"],
|
||||
handler: (parsed, runtime) => handleContextCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "aipro",
|
||||
aliases: [],
|
||||
handler: async (parsed) => {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1);
|
||||
return runAiProCli(subArgs);
|
||||
},
|
||||
},
|
||||
{
|
||||
area: "auth",
|
||||
aliases: ["login"],
|
||||
handler: (parsed, runtime) => handleAuthCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "corps",
|
||||
aliases: ["corp"],
|
||||
handler: (parsed, runtime) => handleCorpsCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "config",
|
||||
aliases: ["mode"],
|
||||
handler: (parsed, runtime) => handleConfigCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "workflow",
|
||||
aliases: ["workflows", "wf"],
|
||||
handler: (parsed, runtime) => handleWorkflowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "bill",
|
||||
aliases: ["bills", "fee", "fees", "invoice", "invoices"],
|
||||
handler: (parsed, runtime) => handleBillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "contact",
|
||||
aliases: ["contacts", "staff", "staffs"],
|
||||
handler: (parsed, runtime) => handleContactCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "task",
|
||||
aliases: ["tasks", "todo"],
|
||||
handler: (parsed, runtime) => handleTaskCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "dimension",
|
||||
aliases: ["dimensions", "archive", "archives"],
|
||||
handler: (parsed, runtime) => handleDimensionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "feetype",
|
||||
aliases: ["feetypes", "fee-type", "fee-types", "expense-type", "expense-types", "costtype"],
|
||||
handler: (parsed, runtime) => handleFeeTypeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "role",
|
||||
aliases: ["roles"],
|
||||
handler: (parsed, runtime) => handleRoleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "permission",
|
||||
aliases: ["permissions"],
|
||||
handler: (parsed, runtime) => handlePermissionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "rule",
|
||||
aliases: ["rules"],
|
||||
handler: (parsed, runtime) => handleRuleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "approval",
|
||||
aliases: ["approvals", "audit"],
|
||||
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "message",
|
||||
aliases: ["messages", "notify", "notifications"],
|
||||
handler: (parsed, runtime) => handleMessageCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "platform",
|
||||
aliases: ["platforms", "datalink", "data-link"],
|
||||
handler: (parsed, runtime) => handlePlatformCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "app",
|
||||
aliases: ["apps", "workbench"],
|
||||
handler: (parsed, runtime) => handleAppCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "menu",
|
||||
aliases: ["menus"],
|
||||
handler: (parsed, runtime) => handleMenuCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "skill",
|
||||
aliases: ["skills"],
|
||||
handler: (parsed, runtime) => handleSkillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "probe",
|
||||
aliases: ["diagnose"],
|
||||
handler: (parsed, runtime) => handleProbeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "update",
|
||||
aliases: ["upgrade", "self-update", "changelog"],
|
||||
handler: (parsed, runtime, options) => handleUpdateCommand(parsed, runtime, options),
|
||||
},
|
||||
{
|
||||
area: "openapi",
|
||||
aliases: ["schema", "spec"],
|
||||
handler: (parsed, runtime) => handleOpenApiCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "keys",
|
||||
aliases: ["key", "secret", "secrets"],
|
||||
handler: (parsed, runtime) => handleKeysCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "store",
|
||||
aliases: ["market"],
|
||||
handler: (parsed, runtime) => handleStoreCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "http",
|
||||
aliases: ["server", "web"],
|
||||
standing: true,
|
||||
handler: (parsed, runtime) => handleHttpCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "service",
|
||||
aliases: ["daemon"],
|
||||
standing: (args) => args[1]?.toLowerCase() === "run",
|
||||
handler: (parsed, runtime) => handleServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "mcp",
|
||||
aliases: [],
|
||||
standing: true,
|
||||
handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options),
|
||||
},
|
||||
];
|
||||
|
||||
const COMMAND_LOOKUP = new Map<string, CliCommandDefinition>();
|
||||
for (const def of CLI_COMMAND_REGISTRY) {
|
||||
COMMAND_LOOKUP.set(def.area.toLowerCase(), def);
|
||||
for (const alias of def.aliases) {
|
||||
COMMAND_LOOKUP.set(alias.toLowerCase(), def);
|
||||
}
|
||||
}
|
||||
|
||||
export function findCommandByArea(area?: string): CliCommandDefinition | undefined {
|
||||
if (!area) return undefined;
|
||||
return COMMAND_LOOKUP.get(area.toLowerCase());
|
||||
}
|
||||
|
||||
export function isStandingCommand(args: string[]): boolean {
|
||||
if (!args.length) return false;
|
||||
const def = findCommandByArea(args[0]);
|
||||
if (!def?.standing) return false;
|
||||
return typeof def.standing === "function" ? def.standing(args) : def.standing;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { runCli } from "./runner.js";
|
||||
import { parseArgs, booleanOption } from "./parser.js";
|
||||
import { VERSION_INFO, formatVersionLabel } from "../version.js";
|
||||
|
||||
describe("CLI runner - version and help aliases", () => {
|
||||
@@ -98,4 +99,19 @@ describe("CLI runner - version and help aliases", () => {
|
||||
expect(help.stderr).toBe("");
|
||||
expect(version.stderr).toBe("");
|
||||
});
|
||||
|
||||
it("does not swallow positional arguments after subcommand boolean flags", () => {
|
||||
const parsed1 = parseArgs(["feetype", "get", "--all", "FT001"]);
|
||||
expect(booleanOption(parsed1.options, ["all"])).toBe(true);
|
||||
expect(parsed1.args).toEqual(["FT001"]);
|
||||
|
||||
const parsed2 = parseArgs(["workflow", "patch", "--in-place", "--value-json", "PIPE_123"]);
|
||||
expect(booleanOption(parsed2.options, ["in-place"])).toBe(true);
|
||||
expect(booleanOption(parsed2.options, ["value-json"])).toBe(true);
|
||||
expect(parsed2.args).toEqual(["PIPE_123"]);
|
||||
|
||||
const parsed3 = parseArgs(["platform", "record", "toggle", "--active", "false", "REC_01"]);
|
||||
expect(booleanOption(parsed3.options, ["active"], true)).toBe(false);
|
||||
expect(parsed3.args).toEqual(["toggle", "REC_01"]);
|
||||
});
|
||||
});
|
||||
+12
-162
@@ -3,46 +3,9 @@ import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.
|
||||
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||
import { classifyCliError } from "./errors.js";
|
||||
import { initCorpRuntime } from "./helpers.js";
|
||||
import { handleAuthCommand } from "./commands/auth.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleWorkflowCommand } from "./commands/workflow.js";
|
||||
import { handlePlatformCommand } from "./commands/platform.js";
|
||||
import { handleAppCommand } from "./commands/app.js";
|
||||
import { handleMenuCommand } from "./commands/menu.js";
|
||||
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 { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import { handleRuleCommand } from "./commands/rule.js";
|
||||
import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { findCommandByArea, isStandingCommand } from "./registry.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
|
||||
function isStandingCommand(args: string[]): boolean {
|
||||
if (!args.length) return false;
|
||||
const first = args[0]?.toLowerCase();
|
||||
const second = args[1]?.toLowerCase();
|
||||
if (STANDING_COMMANDS.has(first)) return true;
|
||||
if ((first === "service" || first === "daemon") && second === "run") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
let runQueue = Promise.resolve<any>(undefined);
|
||||
|
||||
export function runCli(
|
||||
@@ -175,131 +138,18 @@ async function dispatchCli(
|
||||
});
|
||||
|
||||
try {
|
||||
switch (parsed.area) {
|
||||
case "context":
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "env":
|
||||
return await handleContextCommand(parsed, runtime);
|
||||
case "aipro": {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1);
|
||||
return await runAiProCli(subArgs);
|
||||
}
|
||||
case "auth":
|
||||
case "login":
|
||||
return await handleAuthCommand(parsed, runtime);
|
||||
case "corps":
|
||||
case "corp":
|
||||
return await handleCorpsCommand(parsed, runtime);
|
||||
case "config":
|
||||
case "mode":
|
||||
return await handleConfigCommand(parsed, runtime);
|
||||
case "workflow":
|
||||
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 "contact":
|
||||
case "contacts":
|
||||
case "staff":
|
||||
case "staffs":
|
||||
return await handleContactCommand(parsed, runtime);
|
||||
case "task":
|
||||
case "tasks":
|
||||
case "todo":
|
||||
return await handleTaskCommand(parsed, runtime);
|
||||
case "dimension":
|
||||
case "dimensions":
|
||||
case "archive":
|
||||
case "archives":
|
||||
return await handleDimensionCommand(parsed, runtime);
|
||||
case "feetype":
|
||||
case "feetypes":
|
||||
case "fee-type":
|
||||
case "fee-types":
|
||||
case "expense-type":
|
||||
case "expense-types":
|
||||
case "costtype":
|
||||
return await handleFeeTypeCommand(parsed, runtime);
|
||||
case "role":
|
||||
case "roles":
|
||||
return await handleRoleCommand(parsed, runtime);
|
||||
case "permission":
|
||||
case "permissions":
|
||||
return await handlePermissionCommand(parsed, runtime);
|
||||
case "rule":
|
||||
case "rules":
|
||||
return await handleRuleCommand(parsed, runtime);
|
||||
case "approval":
|
||||
case "approvals":
|
||||
case "audit":
|
||||
return await handleApprovalCommand(parsed, runtime);
|
||||
case "message":
|
||||
case "messages":
|
||||
case "notify":
|
||||
case "notifications":
|
||||
return await handleMessageCommand(parsed, runtime);
|
||||
case "platform":
|
||||
case "platforms":
|
||||
case "datalink":
|
||||
case "data-link":
|
||||
return await handlePlatformCommand(parsed, runtime);
|
||||
case "app":
|
||||
case "apps":
|
||||
case "workbench":
|
||||
return await handleAppCommand(parsed, runtime);
|
||||
case "menu":
|
||||
case "menus":
|
||||
return await handleMenuCommand(parsed, runtime);
|
||||
case "skill":
|
||||
case "skills":
|
||||
return await handleSkillCommand(parsed, runtime);
|
||||
case "probe":
|
||||
case "diagnose":
|
||||
return await handleProbeCommand(parsed, runtime);
|
||||
case "update":
|
||||
case "upgrade":
|
||||
case "self-update":
|
||||
case "changelog":
|
||||
return await handleUpdateCommand(parsed, runtime, options);
|
||||
case "openapi":
|
||||
case "schema":
|
||||
case "spec":
|
||||
return await handleOpenApiCommand(parsed, runtime);
|
||||
case "keys":
|
||||
case "key":
|
||||
case "secret":
|
||||
case "secrets":
|
||||
return await handleKeysCommand(parsed, runtime);
|
||||
case "store":
|
||||
case "market":
|
||||
return await handleStoreCommand(parsed, runtime);
|
||||
case "http":
|
||||
case "server":
|
||||
case "web":
|
||||
return await handleHttpCommand(parsed, runtime);
|
||||
case "service":
|
||||
case "daemon":
|
||||
return await handleServiceCommand(parsed, runtime);
|
||||
case "mcp":
|
||||
return await handleMcpCommand(parsed, options);
|
||||
case undefined:
|
||||
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
if (!parsed.area) {
|
||||
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
const commandDef = findCommandByArea(parsed.area);
|
||||
if (!commandDef) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return await commandDef.handler(parsed, runtime, options);
|
||||
} catch (error) {
|
||||
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface CliParsedArgs {
|
||||
area?: string;
|
||||
action?: string;
|
||||
args: string[];
|
||||
positional?: string[];
|
||||
options: Record<string, string | boolean | number>;
|
||||
raw: string[];
|
||||
}
|
||||
|
||||
+18
-15
@@ -1,45 +1,48 @@
|
||||
# Core 层说明
|
||||
|
||||
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。
|
||||
Core 层负责基础设施:企业配置管理、认证 Token 获取与持久化缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。
|
||||
|
||||
## 代码结构
|
||||
|
||||
```text
|
||||
src/core/
|
||||
├── auth/ # 登录认证协议与凭证存储(纯凭据层:用户级主账号 + 企业级 OpenAPI 持久化双通道)
|
||||
│ ├── login.ts # 登录与换票矩阵(RSA账密、短信、F12/协助链接导入、浏览器同步、OpenAPI 密钥持久化与 getProvisionalAuth 续期)
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json)
|
||||
│ ├── tools.ts # MCP Auth Tools 注册与调度
|
||||
│ ├── token-store.ts # 动态 Token 缓存 (~/.config/hose-use/tokens.json)
|
||||
│ ├── login.ts # IDP 账密/短信/浏览器登录、企业切换换票与双通道自动续期入口
|
||||
│ ├── openapi-v1.ts # OpenAPI v1 换票、Provisional 免密鉴权、密钥提取与标准域名探测
|
||||
│ ├── link-import.ts # 协助链接 (thirdparty.html)、F12 Headers / cURL 凭证解析与导入
|
||||
│ ├── openapi-onboard.ts # OpenAPI 持久化一键建档、seal-use 同步、企业提权与免密直达链接签发
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json, 0o600 权限保护)
|
||||
│ ├── token-store.ts # 子域动态 Token 跨进程 L2 持久化缓存 (~/.config/hose-use/tokens.json, 0o600)
|
||||
│ └── types.ts
|
||||
├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端)
|
||||
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
|
||||
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
|
||||
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
|
||||
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(支持账号/OpenAPI 双通道预续期)
|
||||
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(L1 内存 + L2 token-store 跨进程复用)
|
||||
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端(L1 + L2 token-store 缓存)
|
||||
│ └── index.ts # 统一导出入口
|
||||
├── cache/ # 统一多级协同缓存
|
||||
│ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理)
|
||||
│ ├── memory.ts # L1 内存缓存(严格 LRU、TTL、容量限制、按命名空间清理)
|
||||
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
|
||||
│ ├── multi-level.ts # 多级联动门面与 withCache 透明包装器
|
||||
│ ├── multi-level.ts # 多级联动门面与 in-flight 并发防击穿包装器
|
||||
│ └── types.ts
|
||||
├── db/ # 统一 SQLite 数据库与结构化版本迁移
|
||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||
│ └── types.ts
|
||||
├── config/ # 企业配置管理
|
||||
│ ├── loader.ts
|
||||
│ ├── manager.ts
|
||||
│ └── types.ts
|
||||
└── errors.ts # 统一异常语义(EkbError 子类)
|
||||
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
|
||||
│ ├── manager.ts # CorpContext 多企业上下文与身份解析
|
||||
│ └── types.ts # CorpConfig / GlobalConfig Schema 与统一字段访问器
|
||||
└── errors.ts # 统一异常语义(EkbError / NotLoggedInError / AuthenticationError / PermissionError / NotFoundError / ValidationError / BusinessError / EkbApiError)
|
||||
```
|
||||
|
||||
## 分层约束
|
||||
|
||||
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一
|
||||
- `domains/*` 层只抛 `EkbError` 子类
|
||||
- `server.ts` 负责把 `EkbError` 映射为 MCP error
|
||||
- `domains/*` 层只抛 `EkbError` 子类(由 `cli/errors.ts` 统一按结构化 `code` / `status` 映射退出码)
|
||||
- `server.ts` 作为极简 MCP 单工具网关(`hose_cli`)直接委托 `cli/runner.ts` 执行
|
||||
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
||||
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
|
||||
|
||||
@@ -10,6 +10,14 @@ export const ACCOUNT_CACHE_PATH = join(
|
||||
"accounts.json"
|
||||
);
|
||||
|
||||
export function resolveAccountCachePath(): string {
|
||||
const envFile = process.env.HOSE_ACCOUNTS_FILE?.trim();
|
||||
if (envFile) return envFile;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "accounts.json");
|
||||
return ACCOUNT_CACHE_PATH;
|
||||
}
|
||||
|
||||
export const AccountCorporationMetaSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
@@ -48,8 +56,9 @@ function ensureDir(path: string): void {
|
||||
}
|
||||
|
||||
export function loadAccountStore(): AccountStore {
|
||||
const filePath = resolveAccountCachePath();
|
||||
try {
|
||||
const content = readFileSync(ACCOUNT_CACHE_PATH, "utf-8");
|
||||
const content = readFileSync(filePath, "utf-8");
|
||||
return AccountStoreSchema.parse(JSON.parse(content));
|
||||
} catch {
|
||||
return { accounts: {} };
|
||||
@@ -57,8 +66,15 @@ export function loadAccountStore(): AccountStore {
|
||||
}
|
||||
|
||||
export function saveAccountStore(store: AccountStore): void {
|
||||
ensureDir(ACCOUNT_CACHE_PATH);
|
||||
writeFileSync(ACCOUNT_CACHE_PATH, JSON.stringify(store, null, 2), "utf-8");
|
||||
const filePath = resolveAccountCachePath();
|
||||
ensureDir(filePath);
|
||||
writeFileSync(filePath, JSON.stringify(store, null, 2), {
|
||||
encoding: "utf-8",
|
||||
mode: 0o600,
|
||||
});
|
||||
try {
|
||||
chmodSync(filePath, 0o600);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function saveAccount(entry: AccountEntry): void {
|
||||
|
||||
@@ -0,0 +1,612 @@
|
||||
import ky from "ky";
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig, CredentialSource } from "../config/types.js";
|
||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||
import { resolveCorpCluster, clearUnityClientCache } from "../http/unity-client.js";
|
||||
import { clearScriptEngineClientCache } from "../http/script-engine-client.js";
|
||||
import { clearCorpTokens } from "./token-store.js";
|
||||
import {
|
||||
DEFAULT_EKB_BASE_URL,
|
||||
HoseOpenApiKeyItem,
|
||||
fetchOpenApiKeysBySession,
|
||||
selectOpenApiKey,
|
||||
} from "./openapi-v1.js";
|
||||
|
||||
// ── 模式 4:F12 / cURL / 手动直接导入单企业凭证 ───────────────────────────────
|
||||
|
||||
export interface F12ImportParams {
|
||||
accessToken: string;
|
||||
corpId: string;
|
||||
staffId?: string;
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
cluster?: string;
|
||||
source?: CredentialSource;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
appKey?: string;
|
||||
appSecurity?: string;
|
||||
keyId?: string;
|
||||
elevate?: boolean;
|
||||
autoElevate?: boolean;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export interface ImportFromLinkOptions {
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
appKey?: string;
|
||||
appSecurity?: string;
|
||||
keyId?: string;
|
||||
elevate?: boolean;
|
||||
autoElevate?: boolean;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
function parseDurationMs(value: string | number, defaultUnit: "hours" | "days"): number {
|
||||
const raw = String(value).trim().toLowerCase();
|
||||
const match = raw.match(/^(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|d|day|days)?$/);
|
||||
if (!match) throw new AuthenticationError(`无效的有效期参数: ${value}(示例:3d、72h)`);
|
||||
const amount = Number(match[1]);
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
const unit = match[2];
|
||||
const isDays = unit ? ["d", "day", "days"].includes(unit) : defaultUnit === "days";
|
||||
return amount * (isDays ? 24 : 1) * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
export function resolveLinkExpiresAt(
|
||||
options: { ttl?: string | number; expires?: string | number },
|
||||
baseTime = Date.now()
|
||||
): number | undefined {
|
||||
if (options.ttl !== undefined) return baseTime + parseDurationMs(options.ttl, "hours");
|
||||
if (options.expires !== undefined) return baseTime + parseDurationMs(options.expires, "days");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseExpiresInSeconds(
|
||||
value?: string | number,
|
||||
fallbackSeconds = 7200
|
||||
): number {
|
||||
if (value === undefined || value === null || String(value).trim() === "") {
|
||||
return fallbackSeconds;
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw new AuthenticationError(`有效期秒数必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
return Math.round(value);
|
||||
}
|
||||
const raw = String(value).trim().toLowerCase();
|
||||
const match = raw.match(
|
||||
/^(\d+(?:\.\d+)?)\s*(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days)?$/
|
||||
);
|
||||
if (!match) {
|
||||
throw new AuthenticationError(
|
||||
`无效的有效期参数: ${value}(支持秒数如 86400,或带单位如 30m、24h、3d)`
|
||||
);
|
||||
}
|
||||
const amount = Number(match[1]);
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
const unit = match[2] || "s";
|
||||
if (["s", "sec", "secs", "second", "seconds"].includes(unit)) {
|
||||
return Math.round(amount);
|
||||
}
|
||||
if (["m", "min", "mins", "minute", "minutes"].includes(unit)) {
|
||||
return Math.round(amount * 60);
|
||||
}
|
||||
if (["h", "hr", "hrs", "hour", "hours"].includes(unit)) {
|
||||
return Math.round(amount * 3600);
|
||||
}
|
||||
return Math.round(amount * 86400);
|
||||
}
|
||||
|
||||
export function invalidateCorpSubdomainTokenCaches(corp: CorpConfig): void {
|
||||
try {
|
||||
const keys = new Set<string>(
|
||||
[corp.id, corp.corpId, corp.credentials?.corpId].filter((v): v is string => Boolean(v))
|
||||
);
|
||||
for (const key of keys) {
|
||||
clearCorpTokens(key);
|
||||
clearUnityClientCache(key);
|
||||
clearScriptEngineClientCache(key);
|
||||
}
|
||||
} catch {
|
||||
// Ignore cache cleanup errors in restricted environments
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析从 F12 抓包复制出来的 Request Headers、cURL 命令或 URL 字符串
|
||||
*/
|
||||
export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
|
||||
const result: Partial<F12ImportParams> = {};
|
||||
if (!rawInput) return result;
|
||||
|
||||
// 0. 尝试匹配完整 URL(包含 http:// 或 https://)
|
||||
const urlMatch = /(https?:\/\/[^\s"'<>]+)/i.exec(rawInput);
|
||||
if (urlMatch) {
|
||||
try {
|
||||
const parsedUrl = new URL(urlMatch[1]);
|
||||
result.baseUrl = `${parsedUrl.protocol}//${parsedUrl.host}`;
|
||||
const tokenParam =
|
||||
parsedUrl.searchParams.get("accessToken") ||
|
||||
parsedUrl.searchParams.get("token");
|
||||
if (tokenParam) result.accessToken = tokenParam;
|
||||
const corpParam =
|
||||
parsedUrl.searchParams.get("ekbCorpId") ||
|
||||
parsedUrl.searchParams.get("corpId") ||
|
||||
parsedUrl.searchParams.get("corporationId");
|
||||
if (corpParam) result.corpId = corpParam;
|
||||
const staffParam = parsedUrl.searchParams.get("staffId");
|
||||
if (staffParam) result.staffId = staffParam;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 1. 尝试匹配各种 -H / --header 参数:-H 'header: value' 或 -H "header: value"
|
||||
const headerRegex = /(?:-H|--header)\s+['"]([^'"]+)['"]/gi;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = headerRegex.exec(rawInput)) !== null) {
|
||||
const headerStr = match[1];
|
||||
const colonIdx = headerStr.indexOf(":");
|
||||
if (colonIdx !== -1) {
|
||||
const key = headerStr.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
|
||||
const val = headerStr.slice(colonIdx + 1).trim();
|
||||
if (key === "accesstoken") result.accessToken = val;
|
||||
if (key === "corpid" || key === "corporationid") result.corpId = val;
|
||||
if (key === "staffid") result.staffId = val;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 逐行匹配标准 HTTP Headers (如 accesstoken: xxx)
|
||||
const lines = rawInput.split("\n");
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
const colonIdx = trimmed.indexOf(":");
|
||||
if (colonIdx !== -1) {
|
||||
const key = trimmed.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
|
||||
const val = trimmed.slice(colonIdx + 1).trim().replace(/^['"]|['"]$/g, "");
|
||||
if (key === "accesstoken" && !result.accessToken) result.accessToken = val;
|
||||
if ((key === "corpid" || key === "corporationid") && !result.corpId) result.corpId = val;
|
||||
if (key === "staffid" && !result.staffId) result.staffId = val;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 从 URL/Query 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx 或 ekbCorpId=xxx)
|
||||
if (!result.corpId) {
|
||||
const urlCorpMatch = /(?:[?&](?:ekbCorpId|corpId|corporationId)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlCorpMatch) {
|
||||
result.corpId = decodeURIComponent(urlCorpMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.accessToken) {
|
||||
const urlTokenMatch = /(?:[?&](?:accessToken|token)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlTokenMatch) {
|
||||
result.accessToken = decodeURIComponent(urlTokenMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.staffId) {
|
||||
const urlStaffMatch = /(?:[?&]staffId=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlStaffMatch) {
|
||||
result.staffId = decodeURIComponent(urlStaffMatch[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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并导入单个抓包/手动凭证,自动探测官方 Session 平台类型并保存到企业配置
|
||||
*/
|
||||
export async function importCredentials(
|
||||
params: F12ImportParams
|
||||
): Promise<CorpConfig> {
|
||||
const { accessToken, corpId } = params;
|
||||
let staffId = params.staffId;
|
||||
const baseUrl = params.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken || !corpId) {
|
||||
throw new AuthenticationError("导入凭证失败:accessToken 与 corpId 均为必填项");
|
||||
}
|
||||
|
||||
// 检查已存在保护:当明确要求不覆盖 (overwrite === false) 且文件已存在时拦截
|
||||
const targetDir = params.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
const targetFile = join(targetDir, `${corpId}.json`);
|
||||
if (params.overwrite === false && existsSync(targetFile)) {
|
||||
throw new AuthenticationError(`企业 [${corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
|
||||
}
|
||||
|
||||
// 1. 若 staffId 缺失,优先通过 $UNITY JWT 自动探测 staffId、企业名与身份
|
||||
let corpName = params.name;
|
||||
let staffName: string | undefined;
|
||||
let cellphone: string | undefined;
|
||||
let isAdmin: boolean | undefined;
|
||||
let sourceChannel: string | undefined;
|
||||
let jwtExpMs: number | undefined;
|
||||
const requestedExpiresAt = resolveLinkExpiresAt(params);
|
||||
|
||||
try {
|
||||
const jwtHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
jwtHeaders.staffid = staffId;
|
||||
}
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: jwtHeaders,
|
||||
})
|
||||
.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 (!staffId && payload.staffId) {
|
||||
staffId = payload.staffId;
|
||||
}
|
||||
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.sourceChannel) {
|
||||
sourceChannel = payload.sourceChannel;
|
||||
}
|
||||
if (payload.exp) {
|
||||
jwtExpMs = Number(payload.exp) * 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 探测失败则继续后续降级流程
|
||||
}
|
||||
|
||||
// 2. 验证凭证有效性并提取官方服务端 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 sessionHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
sessionHeaders.staffid = staffId;
|
||||
}
|
||||
const res = await ky
|
||||
.get(`${baseUrl}/api/account/v2/session`, {
|
||||
headers: sessionHeaders,
|
||||
})
|
||||
.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;
|
||||
};
|
||||
}>();
|
||||
|
||||
sessionData = res.value;
|
||||
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
|
||||
throw new Error("服务端未返回有效 Session");
|
||||
}
|
||||
|
||||
if (!staffId && sessionData.loginStaffId) {
|
||||
staffId = sessionData.loginStaffId;
|
||||
}
|
||||
if (!staffName && sessionData.privilege) {
|
||||
staffName = sessionData.privilege;
|
||||
}
|
||||
} catch (err) {
|
||||
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
|
||||
// 兜底 staffId:若依然为空,退化为 corpId:admin
|
||||
if (!staffId) {
|
||||
staffId = `${corpId}:admin`;
|
||||
}
|
||||
|
||||
// 3. 自动或显式提取 OpenAPI 密钥实现持久化提权 (appKey + appSecurity)
|
||||
let resolvedAppKey = params.appKey;
|
||||
let resolvedAppSecurity = params.appSecurity;
|
||||
|
||||
if ((!resolvedAppKey || !resolvedAppSecurity) && params.elevate !== false && params.autoElevate !== false) {
|
||||
if (params.elevate === true || params.keyId || (params.appKey && !params.appSecurity)) {
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
const selected = selectOpenApiKey(keys, corpId, {
|
||||
appKey: params.appKey,
|
||||
keyId: params.keyId,
|
||||
force: params.force,
|
||||
});
|
||||
resolvedAppKey = selected.appKey;
|
||||
resolvedAppSecurity = selected.appSecurity;
|
||||
} else {
|
||||
// 默认最佳努力自动提权:若当前身份可读取 OpenAPI 密钥则自动挂载持久化
|
||||
try {
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
if (keys.length > 0) {
|
||||
const picked = keys.find((k) => k.active !== false) ?? keys[0];
|
||||
if (picked) {
|
||||
resolvedAppKey = picked.appKey;
|
||||
resolvedAppSecurity = picked.appSecurity;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 无权限或未开通开放平台时静默降级为普通会话
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 智能判断语义化凭证来源与集群环境
|
||||
let source: CredentialSource = params.source || "curl";
|
||||
if (!params.source) {
|
||||
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
|
||||
source = "assist";
|
||||
}
|
||||
}
|
||||
|
||||
const cluster = params.cluster || resolveCorpCluster({ cluster: params.cluster, baseUrl });
|
||||
|
||||
// 5. 计算 Token 过期时间戳 (ms)
|
||||
let expiresAt: number | undefined;
|
||||
if (sessionData?.expTime && sessionData.expTime > 0) {
|
||||
expiresAt = sessionData.expTime;
|
||||
} else if (jwtExpMs && jwtExpMs > 0) {
|
||||
expiresAt = jwtExpMs;
|
||||
} else if (requestedExpiresAt) {
|
||||
expiresAt = requestedExpiresAt;
|
||||
}
|
||||
|
||||
const corpConfig: CorpConfig = {
|
||||
id: corpId,
|
||||
name: corpName || `企业-${corpId}`,
|
||||
baseUrl,
|
||||
cluster,
|
||||
source,
|
||||
staffName,
|
||||
credentials: {
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
...(resolvedAppKey && resolvedAppSecurity
|
||||
? {
|
||||
appKey: resolvedAppKey,
|
||||
appSecurity: resolvedAppSecurity,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
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,
|
||||
},
|
||||
};
|
||||
|
||||
saveCorpConfig(corpConfig, params.enterprisesDir);
|
||||
return corpConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接通过第三方协助/免密链接 (thirdparty.html / assistance link) 一键导入企业
|
||||
*/
|
||||
export async function importFromLink(
|
||||
linkUrl: string,
|
||||
options: ImportFromLinkOptions = {}
|
||||
): Promise<CorpConfig> {
|
||||
const parsed = parseHeadersOrCurl(linkUrl);
|
||||
const accessToken = parsed.accessToken;
|
||||
const corpId = parsed.corpId;
|
||||
const baseUrl = options.baseUrl || parsed.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 accessToken 参数");
|
||||
}
|
||||
if (!corpId) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 ekbCorpId 或 corpId 参数");
|
||||
}
|
||||
|
||||
return await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId: parsed.staffId,
|
||||
name: options.name,
|
||||
baseUrl,
|
||||
enterprisesDir: options.enterprisesDir,
|
||||
overwrite: options.overwrite,
|
||||
source: "link",
|
||||
ttl: options.ttl,
|
||||
expires: options.expires,
|
||||
appKey: options.appKey,
|
||||
appSecurity: options.appSecurity,
|
||||
keyId: options.keyId,
|
||||
elevate: options.elevate,
|
||||
autoElevate: options.autoElevate,
|
||||
force: options.force,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从协助链接提取 OpenAPI 密钥列表(可选保存为持久化企业配置)
|
||||
*/
|
||||
export async function extractOpenApiKeysFromLink(
|
||||
linkUrl: string,
|
||||
options: {
|
||||
save?: boolean;
|
||||
name?: string;
|
||||
overwrite?: boolean;
|
||||
force?: boolean;
|
||||
appKey?: string;
|
||||
keyId?: string;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<{
|
||||
corpId: string;
|
||||
corpName?: string;
|
||||
baseUrl: string;
|
||||
staffId: string;
|
||||
keys: HoseOpenApiKeyItem[];
|
||||
selectedKey?: HoseOpenApiKeyItem;
|
||||
savedCorp?: CorpConfig;
|
||||
}> {
|
||||
const parsed = parseHeadersOrCurl(linkUrl);
|
||||
const accessToken = parsed.accessToken;
|
||||
const corpId = parsed.corpId;
|
||||
const baseUrl = parsed.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken || !corpId) {
|
||||
throw new AuthenticationError("无效的合思协助链接:缺少 accessToken 或 ekbCorpId 参数");
|
||||
}
|
||||
|
||||
let staffId = parsed.staffId;
|
||||
let corpName = options.name;
|
||||
|
||||
try {
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: { accesstoken: accessToken, corpid: corpId },
|
||||
})
|
||||
.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 (!staffId && payload.staffId) staffId = payload.staffId;
|
||||
if (!corpName && payload.corporationName) corpName = payload.corporationName;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
if (!staffId) staffId = `${corpId}:admin`;
|
||||
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
|
||||
if (!options.save) {
|
||||
return { corpId, corpName, baseUrl, staffId, keys };
|
||||
}
|
||||
|
||||
const selectedKey = selectOpenApiKey(keys, corpId, {
|
||||
appKey: options.appKey,
|
||||
keyId: options.keyId,
|
||||
force: options.force,
|
||||
});
|
||||
|
||||
const savedCorp = await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
name: corpName,
|
||||
baseUrl,
|
||||
overwrite: options.overwrite ?? true,
|
||||
source: "link",
|
||||
enterprisesDir: options.enterprisesDir,
|
||||
appKey: selectedKey.appKey,
|
||||
appSecurity: selectedKey.appSecurity,
|
||||
autoElevate: false,
|
||||
});
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: savedCorp.name,
|
||||
baseUrl,
|
||||
staffId: savedCorp.credentials.staffId,
|
||||
keys,
|
||||
selectedKey,
|
||||
savedCorp,
|
||||
};
|
||||
}
|
||||
|
||||
// 保持历史命名兼容
|
||||
export const importF12Credentials = importCredentials;
|
||||
+24
-1582
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,523 @@
|
||||
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig, CorpConfigSchema } from "../config/types.js";
|
||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||
import { resolveCorpCluster } from "../http/unity-client.js";
|
||||
import {
|
||||
DEFAULT_EKB_BASE_URL,
|
||||
HoseOpenApiKeyItem,
|
||||
canRefreshCorpAccessToken,
|
||||
fetchHoseOpenApiAccessToken,
|
||||
fetchHoseProvisionalAuth,
|
||||
fetchHoseRoleDefGroups,
|
||||
fetchHoseRoleStaffs,
|
||||
fetchHoseStaffDetails,
|
||||
fetchOpenApiKeysBySession,
|
||||
formatBeijingIso,
|
||||
getCorpOpenApiCredentials,
|
||||
hasOpenApiPersistentCredentials,
|
||||
normalizeBaseUrl,
|
||||
probeHoseDomain,
|
||||
selectOpenApiKey,
|
||||
} from "./openapi-v1.js";
|
||||
import {
|
||||
importCredentials,
|
||||
invalidateCorpSubdomainTokenCaches,
|
||||
parseExpiresInSeconds,
|
||||
} from "./link-import.js";
|
||||
import { refreshSingleCorpAccessToken } from "./login.js";
|
||||
|
||||
export interface OnboardHosePersistentParams {
|
||||
id?: string;
|
||||
name?: string;
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
domain?: string;
|
||||
baseUrl?: string;
|
||||
corpId?: string;
|
||||
staffId?: string;
|
||||
staffName?: string;
|
||||
staffPhone?: string;
|
||||
role?: string;
|
||||
force?: boolean;
|
||||
overwrite?: boolean;
|
||||
enterprisesDir?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过开放平台持久化密钥 (appKey + appSecurity) 自动探测域名、管理员并导入企业配置
|
||||
*/
|
||||
export async function onboardHosePersistent(
|
||||
input: OnboardHosePersistentParams
|
||||
): Promise<CorpConfig> {
|
||||
const explicitDomain = input.domain || input.baseUrl;
|
||||
const probe = await probeHoseDomain(input.appKey, input.appSecurity, explicitDomain);
|
||||
const domain = probe.domain;
|
||||
const corpId = input.corpId || probe.corpId;
|
||||
let corpName = input.name || probe.corpName;
|
||||
let staffId = input.staffId;
|
||||
let staffName = input.staffName;
|
||||
|
||||
const targetDir = input.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
const targetFile = join(targetDir, `${input.id || corpId}.json`);
|
||||
if (input.overwrite === false && existsSync(targetFile)) {
|
||||
throw new AuthenticationError(`企业 [${input.id || corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
|
||||
}
|
||||
|
||||
if (!staffId) {
|
||||
const roleQuery = input.role ?? "admin";
|
||||
const roleGroups = await fetchHoseRoleDefGroups(domain, probe.openapiToken).catch(() => []);
|
||||
let targetRoleId: string | undefined;
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id.endsWith(`:${roleQuery}`) || role.name === roleQuery || role.id === roleQuery) {
|
||||
targetRoleId = role.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleId) break;
|
||||
}
|
||||
if (!targetRoleId) {
|
||||
targetRoleId = roleGroups
|
||||
.find((group) => group.roleDefs.some((role) => role.id.endsWith(":admin")))
|
||||
?.roleDefs.find((role) => role.id.endsWith(":admin"))?.id;
|
||||
}
|
||||
|
||||
if (targetRoleId) {
|
||||
const roleStaffs = await fetchHoseRoleStaffs(domain, probe.openapiToken, targetRoleId).catch(() => ({ staffs: [] }));
|
||||
const staffDetails = await fetchHoseStaffDetails(domain, probe.openapiToken, roleStaffs.staffs).catch(() => []);
|
||||
if (input.staffName || input.staffPhone) {
|
||||
const matches = staffDetails.filter((staff) => {
|
||||
if (input.staffName && staff.name !== input.staffName && !staff.name.includes(input.staffName)) return false;
|
||||
if (input.staffPhone && (!staff.cellphone || !staff.cellphone.includes(input.staffPhone))) return false;
|
||||
return true;
|
||||
});
|
||||
if (matches.length === 1 && matches[0]) {
|
||||
staffId = matches[0].id;
|
||||
staffName = matches[0].name;
|
||||
} else if (matches.length > 1) {
|
||||
throw new AuthenticationError(
|
||||
`匹配到多位管理员候选人 (${matches.map((s) => `${s.name}[${s.id}]`).join(", ")}),请通过 --staff-id 精确指定。`
|
||||
);
|
||||
} else {
|
||||
throw new AuthenticationError(
|
||||
`未找到匹配 '${input.staffName ?? input.staffPhone}' 的管理员,请检查姓名/手机号或显式指定 --staff-id。`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const activeStaffs = staffDetails.filter((s) => s.active);
|
||||
if (staffDetails.length === 1 && staffDetails[0]) {
|
||||
staffId = staffDetails[0].id;
|
||||
staffName = staffDetails[0].name;
|
||||
} else if (activeStaffs.length === 1 && activeStaffs[0]) {
|
||||
staffId = activeStaffs[0].id;
|
||||
staffName = activeStaffs[0].name;
|
||||
} else if (input.force && (activeStaffs[0] || staffDetails[0])) {
|
||||
const picked = activeStaffs[0] ?? staffDetails[0]!;
|
||||
staffId = picked.id;
|
||||
staffName = picked.name;
|
||||
} else if (staffDetails.length > 1) {
|
||||
const candidates = staffDetails.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
cellphone: s.cellphone ? s.cellphone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") : undefined,
|
||||
active: s.active,
|
||||
}));
|
||||
throw new AuthenticationError(
|
||||
`检测到多位主管理员候选人,请通过 --staff-id、--staff-name 指定,或追加 --force 自动选择第一位在职管理员: ${JSON.stringify(candidates)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!staffId) {
|
||||
throw new AuthenticationError(
|
||||
"缺少员工工号 (staffId),且未能从主管理员角色自动发现,请通过 --staff-id 显式指定。"
|
||||
);
|
||||
}
|
||||
|
||||
const normalizedStaffId = staffId.includes(":") ? staffId : `${corpId}:${staffId}`;
|
||||
|
||||
// 使用 getProvisionalAuth 签发初始会话并走 importCredentials 完整探测企业全称与 Session 元数据
|
||||
const provisional = await fetchHoseProvisionalAuth({
|
||||
baseUrl: domain,
|
||||
openapiToken: probe.openapiToken,
|
||||
corpId,
|
||||
staffId: normalizedStaffId,
|
||||
expiresIn: 7200,
|
||||
});
|
||||
|
||||
const imported = await importCredentials({
|
||||
accessToken: provisional.token,
|
||||
corpId,
|
||||
staffId: normalizedStaffId,
|
||||
name: corpName,
|
||||
baseUrl: domain,
|
||||
source: "openapi",
|
||||
enterprisesDir: input.enterprisesDir,
|
||||
overwrite: true,
|
||||
appKey: input.appKey,
|
||||
appSecurity: input.appSecurity,
|
||||
autoElevate: false,
|
||||
});
|
||||
|
||||
if (staffName && !imported.staffName) {
|
||||
imported.staffName = staffName;
|
||||
saveCorpConfig(imported, input.enterprisesDir);
|
||||
}
|
||||
|
||||
return imported;
|
||||
}
|
||||
|
||||
export interface SyncFromSealUseOptions {
|
||||
filter?: string;
|
||||
sealEnterprisesDir?: string;
|
||||
enterprisesDir?: string;
|
||||
verify?: boolean;
|
||||
overwrite?: boolean;
|
||||
}
|
||||
|
||||
export interface SyncFromSealUseItemResult {
|
||||
corpId: string;
|
||||
name: string;
|
||||
appKey: string;
|
||||
domain: string;
|
||||
staffId: string;
|
||||
action: "merged" | "created" | "skipped";
|
||||
}
|
||||
|
||||
export async function syncOpenApiFromSealUse(
|
||||
options: SyncFromSealUseOptions = {}
|
||||
): Promise<{
|
||||
sealDir: string;
|
||||
targetDir: string;
|
||||
items: SyncFromSealUseItemResult[];
|
||||
}> {
|
||||
const sealDir =
|
||||
options.sealEnterprisesDir ||
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR?.trim() ||
|
||||
join(homedir(), ".config", "seal-use", "enterprises");
|
||||
const targetDir = options.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
|
||||
if (!existsSync(sealDir)) {
|
||||
throw new AuthenticationError(`未找到 seal-use 企业配置目录: ${sealDir}`);
|
||||
}
|
||||
|
||||
const files = readdirSync(sealDir).filter((f) => f.endsWith(".json") && !f.startsWith("example."));
|
||||
const kw = options.filter?.trim().toLowerCase();
|
||||
const items: SyncFromSealUseItemResult[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(join(sealDir, file), "utf-8"));
|
||||
const sourceObj = raw?.source?.hose || raw?.source || raw?.hose;
|
||||
const appKey = sourceObj?.appKey;
|
||||
const appSecurity = sourceObj?.appSecurity;
|
||||
if (!appKey || !appSecurity) continue;
|
||||
|
||||
const corpId: string = sourceObj.corpId || raw.id;
|
||||
const sealName: string = raw.name || corpId;
|
||||
const domain = normalizeBaseUrl(sourceObj.domain || DEFAULT_EKB_BASE_URL);
|
||||
const rawStaffId: string = sourceObj.staffId || `${corpId}:admin`;
|
||||
const staffId = rawStaffId.includes(":") ? rawStaffId : `${corpId}:${rawStaffId}`;
|
||||
|
||||
if (kw) {
|
||||
const matched =
|
||||
corpId.toLowerCase().includes(kw) ||
|
||||
sealName.toLowerCase().includes(kw) ||
|
||||
String(raw.id || "").toLowerCase().includes(kw);
|
||||
if (!matched) continue;
|
||||
}
|
||||
|
||||
const targetPath = join(targetDir, `${corpId}.json`);
|
||||
if (existsSync(targetPath)) {
|
||||
const existing = CorpConfigSchema.parse(JSON.parse(readFileSync(targetPath, "utf-8")));
|
||||
if (hasOpenApiPersistentCredentials(existing) && options.overwrite === false) {
|
||||
items.push({
|
||||
corpId,
|
||||
name: existing.name,
|
||||
appKey: existing.credentials.appKey || appKey,
|
||||
domain: existing.baseUrl || domain,
|
||||
staffId: existing.credentials.staffId,
|
||||
action: "skipped",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
existing.credentials.appKey = appKey;
|
||||
existing.credentials.appSecurity = appSecurity;
|
||||
if (!existing.baseUrl) existing.baseUrl = domain;
|
||||
if (!existing.credentials.staffId) existing.credentials.staffId = staffId;
|
||||
if (options.verify) {
|
||||
await refreshSingleCorpAccessToken(existing);
|
||||
} else {
|
||||
saveCorpConfig(existing, targetDir);
|
||||
}
|
||||
items.push({
|
||||
corpId,
|
||||
name: existing.name,
|
||||
appKey,
|
||||
domain: existing.baseUrl || domain,
|
||||
staffId: existing.credentials.staffId,
|
||||
action: "merged",
|
||||
});
|
||||
} else {
|
||||
let createdConfig: CorpConfig | null = null;
|
||||
if (options.verify) {
|
||||
try {
|
||||
createdConfig = await onboardHosePersistent({
|
||||
id: corpId,
|
||||
name: sealName,
|
||||
appKey,
|
||||
appSecurity,
|
||||
domain,
|
||||
corpId,
|
||||
staffId,
|
||||
overwrite: true,
|
||||
enterprisesDir: targetDir,
|
||||
});
|
||||
} catch {
|
||||
// fallback to saving raw OpenAPI credentials below
|
||||
}
|
||||
}
|
||||
if (!createdConfig) {
|
||||
createdConfig = {
|
||||
id: corpId,
|
||||
name: sealName,
|
||||
corpId,
|
||||
staffId,
|
||||
source: "openapi",
|
||||
baseUrl: domain,
|
||||
cluster: resolveCorpCluster({ baseUrl: domain }),
|
||||
credentials: {
|
||||
accessToken: "",
|
||||
corpId,
|
||||
staffId,
|
||||
appKey,
|
||||
appSecurity,
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
},
|
||||
};
|
||||
saveCorpConfig(createdConfig, targetDir);
|
||||
}
|
||||
items.push({
|
||||
corpId,
|
||||
name: createdConfig.name,
|
||||
appKey,
|
||||
domain: createdConfig.baseUrl || domain,
|
||||
staffId: createdConfig.credentials.staffId,
|
||||
action: "created",
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid file
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sealDir,
|
||||
targetDir,
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已配置企业提取并持久化 OpenAPI 密钥
|
||||
*/
|
||||
export async function elevateCorpWithOpenApiKey(
|
||||
corp: CorpConfig,
|
||||
options: {
|
||||
appKey?: string;
|
||||
keyId?: string;
|
||||
force?: boolean;
|
||||
silent?: boolean;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<HoseOpenApiKeyItem | undefined> {
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = corp.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
try {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expMs = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken: corp.credentials.accessToken,
|
||||
}).catch(async (err) => {
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const refreshed = await refreshSingleCorpAccessToken(corp);
|
||||
if (refreshed) {
|
||||
return fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken: corp.credentials.accessToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (keys.length === 0) {
|
||||
if (options.silent) return undefined;
|
||||
throw new AuthenticationError(`企业 [${corp.name}] 暂未创建 OpenAPI 密钥`);
|
||||
}
|
||||
const selected = selectOpenApiKey(keys, corpId, {
|
||||
appKey: options.appKey,
|
||||
keyId: options.keyId,
|
||||
force: options.force ?? options.silent,
|
||||
});
|
||||
corp.credentials.appKey = selected.appKey;
|
||||
corp.credentials.appSecurity = selected.appSecurity;
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
return selected;
|
||||
} catch (err) {
|
||||
if (options.silent) return undefined;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成指定企业的合思 Web 免密登录直达链接 (thirdparty.html)
|
||||
* 优先走 OpenAPI getProvisionalAuth 签发独立授权链接;若无 OpenAPI 密钥则尝试自动提权,最后回退当前有效会话 Token。
|
||||
*/
|
||||
export async function getCorpProvisionalAuthLink(
|
||||
corp: CorpConfig,
|
||||
options: {
|
||||
expiresIn?: number | string;
|
||||
ttl?: number | string;
|
||||
pageType?: string;
|
||||
force?: boolean;
|
||||
syncLocalSession?: boolean;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<{
|
||||
corpId: string;
|
||||
corpName: string;
|
||||
staffId: string;
|
||||
staffName?: string;
|
||||
url: string;
|
||||
token: string;
|
||||
expiresIn: number;
|
||||
expiresAt: string;
|
||||
persistent: boolean;
|
||||
method: "provisional-openapi" | "session-token";
|
||||
}> {
|
||||
const explicitDuration = options.expiresIn ?? options.ttl;
|
||||
const expiresIn = parseExpiresInSeconds(explicitDuration, 7200);
|
||||
const pageType = options.pageType || "home";
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
|
||||
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
|
||||
if (!hasOpenApiPersistentCredentials(corp)) {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expMs = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
if (corp.credentials.accessToken) {
|
||||
await elevateCorpWithOpenApiKey(corp, { silent: true, force: true, enterprisesDir: options.enterprisesDir });
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 若具备 OpenAPI 持久化密钥,直接走 getProvisionalAuth 签发标准免密链接
|
||||
const openApiCreds = getCorpOpenApiCredentials(corp);
|
||||
if (openApiCreds) {
|
||||
const openapiToken = await fetchHoseOpenApiAccessToken({
|
||||
appKey: openApiCreds.appKey,
|
||||
appSecurity: openApiCreds.appSecurity,
|
||||
baseUrl,
|
||||
forceRefresh: options.force,
|
||||
});
|
||||
const provisional = await fetchHoseProvisionalAuth({
|
||||
baseUrl,
|
||||
openapiToken,
|
||||
corpId,
|
||||
staffId,
|
||||
expiresIn,
|
||||
pageType,
|
||||
});
|
||||
|
||||
if (options.syncLocalSession !== false) {
|
||||
corp.credentials.accessToken = provisional.token;
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = provisional.expiresAt;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = provisional.expiresAt;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
invalidateCorpSubdomainTokenCaches(corp);
|
||||
}
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId: provisional.uid,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
url: provisional.url,
|
||||
token: provisional.token,
|
||||
expiresIn: provisional.expiresIn,
|
||||
expiresAt: formatBeijingIso(provisional.expiresAt),
|
||||
persistent: true,
|
||||
method: "provisional-openapi",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 回退路径:无 OpenAPI 密钥时,使用主账号或现有有效 Session Token 拼装免密链接
|
||||
if (!corp.credentials.accessToken) {
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corp.name}] 缺少可用访问令牌且未配置 OpenAPI 持久化密钥,请重新登录或导入链接。`
|
||||
);
|
||||
}
|
||||
|
||||
const expMs =
|
||||
explicitDuration !== undefined
|
||||
? Date.now() + expiresIn * 1000
|
||||
: corp.auth?.expiresAt || corp.session?.expTime || Date.now() + expiresIn * 1000;
|
||||
if (expMs <= Date.now() && !canRefreshCorpAccessToken(corp)) {
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corp.name}] 临时凭证已过期且未配置持久化密钥,请使用 hose-use corps add-link 重新导入。`
|
||||
);
|
||||
}
|
||||
|
||||
if (explicitDuration !== undefined && options.syncLocalSession !== false) {
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = expMs;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = expMs;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
}
|
||||
|
||||
const url = `${baseUrl}/web/thirdparty.html?accessToken=${encodeURIComponent(
|
||||
corp.credentials.accessToken
|
||||
)}&ekbCorpId=${encodeURIComponent(corpId)}&pageType=${encodeURIComponent(
|
||||
pageType
|
||||
)}&overdueTokenRedirect=&noPathCache=true`;
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
url,
|
||||
token: corp.credentials.accessToken,
|
||||
expiresIn: Math.max(1, Math.round((expMs - Date.now()) / 1000)),
|
||||
expiresAt: formatBeijingIso(expMs),
|
||||
persistent: canRefreshCorpAccessToken(corp),
|
||||
method: "session-token",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
import ky from "ky";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
|
||||
export const DEFAULT_EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
|
||||
export const HOSE_STANDARD_DOMAINS = [
|
||||
"https://app.ekuaibao.com",
|
||||
"https://dd2.hosecloud.com",
|
||||
"https://wx2.ekuaibao.com",
|
||||
"https://kdcloud2.ekuaibao.com",
|
||||
"https://ddenterprise.ekuaibao.com",
|
||||
"https://feishu.ekuaibao.com",
|
||||
] as const;
|
||||
|
||||
export function normalizeBaseUrl(url: string): string {
|
||||
return url.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function formatBeijingIso(timestampMs: number): string {
|
||||
const shanghaiMs = timestampMs + 8 * 60 * 60 * 1000;
|
||||
const iso = new Date(shanghaiMs).toISOString();
|
||||
return `${iso.slice(0, 19)}+08:00`;
|
||||
}
|
||||
|
||||
export function maskOpenApiSecurity(secret: string): string {
|
||||
if (!secret) return "-";
|
||||
if (secret.length <= 12) return "******";
|
||||
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
|
||||
}
|
||||
|
||||
export function getCorpOpenApiCredentials(
|
||||
corp?: CorpConfig | null
|
||||
): { appKey: string; appSecurity: string } | undefined {
|
||||
if (!corp) return undefined;
|
||||
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
|
||||
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
|
||||
if (appKey && appSecurity) {
|
||||
return { appKey, appSecurity };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function hasOpenApiPersistentCredentials(corp?: CorpConfig | null): boolean {
|
||||
return Boolean(getCorpOpenApiCredentials(corp));
|
||||
}
|
||||
|
||||
export function canRefreshCorpAccessToken(corp?: CorpConfig | null): boolean {
|
||||
if (!corp) return false;
|
||||
if (hasOpenApiPersistentCredentials(corp)) {
|
||||
return true;
|
||||
}
|
||||
return corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
}
|
||||
|
||||
// ── OpenAPI v1 持久凭据换票、免密链接签发与提权 ──────────────────────────────
|
||||
|
||||
export interface HoseOpenApiKeyItem {
|
||||
id: string;
|
||||
name?: string;
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
active: boolean;
|
||||
corporationId?: string;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
}
|
||||
|
||||
export interface HoseProbeDomainResult {
|
||||
domain: string;
|
||||
corpId: string;
|
||||
corpName?: string;
|
||||
openapiToken: string;
|
||||
expireTime?: number;
|
||||
}
|
||||
|
||||
export interface HoseRoleDef {
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
sourceType?: string;
|
||||
sourceTypeValue?: string | null;
|
||||
groupId?: string;
|
||||
groupName?: string;
|
||||
}
|
||||
|
||||
export interface HoseRoleDefGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
roleDefs: HoseRoleDef[];
|
||||
}
|
||||
|
||||
export interface HoseStaffDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
nickName?: string | null;
|
||||
code?: string;
|
||||
departments?: string[];
|
||||
defaultDepartment?: string;
|
||||
cellphone?: string;
|
||||
active: boolean;
|
||||
userId?: string;
|
||||
email?: string | null;
|
||||
showEmail?: string | null;
|
||||
external?: boolean;
|
||||
authState?: boolean;
|
||||
}
|
||||
|
||||
const openapiV1TokenCache = new Map<string, { token: string; expiresAt: number }>();
|
||||
const openapiV1TokenInflight = new Map<string, Promise<string>>();
|
||||
|
||||
export async function fetchHoseOpenApiAccessToken(params: {
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
baseUrl?: string;
|
||||
forceRefresh?: boolean;
|
||||
}): Promise<string> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const cacheKey = `${params.appKey}@${baseUrl}`;
|
||||
|
||||
if (!params.forceRefresh) {
|
||||
const cached = openapiV1TokenCache.get(cacheKey);
|
||||
if (cached && Date.now() < cached.expiresAt - 60_000) {
|
||||
return cached.token;
|
||||
}
|
||||
const inflight = openapiV1TokenInflight.get(cacheKey);
|
||||
if (inflight) return inflight;
|
||||
}
|
||||
|
||||
const req = (async () => {
|
||||
const res = await ky
|
||||
.post(`${baseUrl}/api/openapi/v1/auth/getAccessToken`, {
|
||||
json: {
|
||||
appKey: params.appKey,
|
||||
appSecurity: params.appSecurity,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
accessToken?: string;
|
||||
corporationId?: string;
|
||||
expireTime?: number;
|
||||
errorCode?: number;
|
||||
errorMessage?: string;
|
||||
};
|
||||
accessToken?: string;
|
||||
token?: string;
|
||||
}>();
|
||||
|
||||
if (res.value?.errorCode) {
|
||||
throw new AuthenticationError(
|
||||
res.value.errorMessage || `OpenAPI 换票失败 (errorCode: ${res.value.errorCode})`
|
||||
);
|
||||
}
|
||||
|
||||
const token = res.value?.accessToken ?? res.accessToken ?? res.token;
|
||||
if (!token) {
|
||||
throw new AuthenticationError("合思 OpenAPI getAccessToken 未返回有效 accessToken");
|
||||
}
|
||||
|
||||
openapiV1TokenCache.set(cacheKey, {
|
||||
token,
|
||||
expiresAt: Date.now() + 3600 * 1000,
|
||||
});
|
||||
return token;
|
||||
})().finally(() => {
|
||||
openapiV1TokenInflight.delete(cacheKey);
|
||||
});
|
||||
|
||||
openapiV1TokenInflight.set(cacheKey, req);
|
||||
return req;
|
||||
}
|
||||
|
||||
export async function fetchHoseProvisionalAuth(params: {
|
||||
baseUrl?: string;
|
||||
openapiToken: string;
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
expiresIn?: number;
|
||||
pageType?: string;
|
||||
}): Promise<{
|
||||
url: string;
|
||||
token: string;
|
||||
uid: string;
|
||||
expiresIn: number;
|
||||
expiresAt: number;
|
||||
}> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const expiresIn = params.expiresIn && params.expiresIn > 0 ? params.expiresIn : 7200;
|
||||
const pageType = params.pageType || "home";
|
||||
const uid = params.staffId.includes(":")
|
||||
? params.staffId
|
||||
: `${params.corpId}:${params.staffId}`;
|
||||
|
||||
const response = await ky
|
||||
.post(`${baseUrl}/api/openapi/v1.1/provisional/getProvisionalAuth`, {
|
||||
searchParams: {
|
||||
accessToken: params.openapiToken,
|
||||
},
|
||||
json: {
|
||||
uid,
|
||||
pageType,
|
||||
expireDate: expiresIn,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{ value?: { message?: string } }>();
|
||||
|
||||
const url = response.value?.message;
|
||||
if (!url) {
|
||||
throw new AuthenticationError("合思 getProvisionalAuth 未返回免密授权链接");
|
||||
}
|
||||
|
||||
const token = new URL(url).searchParams.get("accessToken");
|
||||
if (!token) {
|
||||
throw new AuthenticationError("合思免密授权链接缺少 accessToken 参数");
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
token,
|
||||
uid,
|
||||
expiresIn,
|
||||
expiresAt: Date.now() + expiresIn * 1000,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchOpenApiKeysBySession(params: {
|
||||
baseUrl?: string;
|
||||
corpId: string;
|
||||
staffId?: string;
|
||||
accessToken: string;
|
||||
}): Promise<HoseOpenApiKeyItem[]> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const staffId = params.staffId || `${params.corpId}:admin`;
|
||||
const response = await ky
|
||||
.get(`${baseUrl}/api/innerapi/v1/key`, {
|
||||
searchParams: { corpId: params.corpId },
|
||||
headers: {
|
||||
accesstoken: params.accessToken,
|
||||
corpid: params.corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{ items?: unknown[] }>();
|
||||
|
||||
const rawItems = response.items ?? [];
|
||||
const keys: HoseOpenApiKeyItem[] = [];
|
||||
for (const raw of rawItems) {
|
||||
if (typeof raw === "object" && raw !== null) {
|
||||
const item = raw as Record<string, unknown>;
|
||||
if (typeof item.appKey === "string" && typeof item.appSecurity === "string") {
|
||||
keys.push({
|
||||
id: String(item.id ?? item.appKey),
|
||||
name: typeof item.name === "string" ? item.name : undefined,
|
||||
appKey: item.appKey,
|
||||
appSecurity: item.appSecurity,
|
||||
active: typeof item.active === "boolean" ? item.active : true,
|
||||
corporationId: typeof item.corporationId === "string" ? item.corporationId : params.corpId,
|
||||
createTime: typeof item.createTime === "number" ? item.createTime : undefined,
|
||||
updateTime: typeof item.updateTime === "number" ? item.updateTime : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
export function selectOpenApiKey(
|
||||
keys: HoseOpenApiKeyItem[],
|
||||
corpId: string,
|
||||
selection: { appKey?: string; keyId?: string; force?: boolean } = {}
|
||||
): HoseOpenApiKeyItem {
|
||||
if (keys.length === 0) {
|
||||
throw new AuthenticationError(
|
||||
`未能从企业 [${corpId}] 中提取到 OpenAPI 密钥凭据。请确认该企业在合思开放平台已创建应用密钥,且当前员工具有管理员权限。`
|
||||
);
|
||||
}
|
||||
if (selection.keyId || selection.appKey) {
|
||||
const matched = keys.find(
|
||||
(k) =>
|
||||
(selection.keyId && k.id === selection.keyId) ||
|
||||
(selection.appKey && k.appKey === selection.appKey)
|
||||
);
|
||||
if (!matched) {
|
||||
const candidates = keys
|
||||
.map((k) => ` • "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${k.active ? "🟢 启用" : "⚪ 停用"})`)
|
||||
.join("\n");
|
||||
throw new AuthenticationError(
|
||||
`指定的合思密钥不存在,请从候选列表中选择正确的 --app-key 或 --key-id:\n${candidates}`
|
||||
);
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
const activeKeys = keys.filter((k) => k.active !== false);
|
||||
if (keys.length === 1) return keys[0]!;
|
||||
if (activeKeys.length === 1) return activeKeys[0]!;
|
||||
if (selection.force) {
|
||||
return activeKeys[0] ?? keys[0]!;
|
||||
}
|
||||
const candidates = keys
|
||||
.map(
|
||||
(k, idx) =>
|
||||
` [${idx + 1}] "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${k.active ? "🟢 启用" : "⚪ 停用"})`
|
||||
)
|
||||
.join("\n");
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corpId}] 存在多套 (${keys.length} 套) OpenAPI 应用密钥凭据:\n${candidates}\n请通过 --app-key <key> 或 --key-id <id> 显式指定,或追加 --force 自动选用第一套启用密钥。`
|
||||
);
|
||||
}
|
||||
|
||||
export async function probeHoseDomain(
|
||||
appKey: string,
|
||||
appSecurity: string,
|
||||
explicitDomain?: string
|
||||
): Promise<HoseProbeDomainResult> {
|
||||
if (explicitDomain) {
|
||||
const normalized = normalizeBaseUrl(explicitDomain);
|
||||
const result = await testSingleHoseDomain(normalized, appKey, appSecurity);
|
||||
if (!result) {
|
||||
throw new AuthenticationError(
|
||||
`在指定域名 ${normalized} 上校验 OpenAPI 凭据失败,请检查 appKey/appSecurity 与域名连通性。`
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const results = await Promise.all(
|
||||
HOSE_STANDARD_DOMAINS.map((domain) =>
|
||||
testSingleHoseDomain(domain, appKey, appSecurity).catch(() => undefined)
|
||||
)
|
||||
);
|
||||
const matched = results.find((item): item is HoseProbeDomainResult => Boolean(item));
|
||||
if (matched) return matched;
|
||||
|
||||
throw new AuthenticationError(
|
||||
`在全部 6 个标准合思域名 (${HOSE_STANDARD_DOMAINS.join(", ")}) 上均未能通过 appKey/appSecurity 鉴权。若为私有化或独立域名,请通过 --domain 显式指定。`
|
||||
);
|
||||
}
|
||||
|
||||
async function testSingleHoseDomain(
|
||||
domain: string,
|
||||
appKey: string,
|
||||
appSecurity: string
|
||||
): Promise<HoseProbeDomainResult | undefined> {
|
||||
try {
|
||||
const response = await fetch(`${domain}/api/openapi/v1/auth/getAccessToken`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ appKey, appSecurity }),
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
if (!response.ok) return undefined;
|
||||
const data = (await response.json()) as {
|
||||
value?: {
|
||||
accessToken?: string;
|
||||
corporationId?: string;
|
||||
corporation?: { id?: string; name?: string };
|
||||
expireTime?: number;
|
||||
errorCode?: number;
|
||||
};
|
||||
accessToken?: string;
|
||||
};
|
||||
if (data.value?.errorCode) return undefined;
|
||||
const openapiToken = data.value?.accessToken ?? data.accessToken;
|
||||
const corpId = data.value?.corporationId ?? data.value?.corporation?.id;
|
||||
if (!openapiToken || !corpId) return undefined;
|
||||
return {
|
||||
domain,
|
||||
corpId,
|
||||
corpName: data.value?.corporation?.name,
|
||||
openapiToken,
|
||||
expireTime: data.value?.expireTime,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchHoseRoleDefGroups(
|
||||
domain: string,
|
||||
openapiToken: string
|
||||
): Promise<HoseRoleDefGroup[]> {
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roleDefGroups?accessToken=${encodeURIComponent(openapiToken)}`;
|
||||
const response = await fetch(url, {
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取合思角色定义组失败: ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
items?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
roleDefs?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
sourceType?: string;
|
||||
sourceTypeValue?: string | null;
|
||||
}>;
|
||||
}>;
|
||||
};
|
||||
return (json.items ?? []).map((g) => ({
|
||||
id: g.id,
|
||||
name: g.name,
|
||||
enName: g.enName,
|
||||
roleDefs: (g.roleDefs ?? []).map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
enName: r.enName,
|
||||
sourceType: r.sourceType,
|
||||
sourceTypeValue: r.sourceTypeValue,
|
||||
groupId: g.id,
|
||||
groupName: g.name,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function fetchHoseRoleStaffs(
|
||||
domain: string,
|
||||
openapiToken: string,
|
||||
roledefId: string,
|
||||
staffBy = "id"
|
||||
): Promise<{ id: string; name: string; count: number; staffs: string[] }> {
|
||||
const cleanId = roledefId.startsWith("$") ? roledefId.slice(1) : roledefId;
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roledefs/$${cleanId}?accessToken=${encodeURIComponent(openapiToken)}&staffBy=${encodeURIComponent(staffBy)}&pathType=name`;
|
||||
const response = await fetch(url, {
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取角色成员失败 (${cleanId}): ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
value?: {
|
||||
id: string;
|
||||
name: string;
|
||||
count?: number;
|
||||
contents?: Array<{ staffs?: string[] }>;
|
||||
};
|
||||
};
|
||||
const val = json.value;
|
||||
if (!val) throw new AuthenticationError(`角色成员查询返回为空 (${cleanId})`);
|
||||
const allStaffs: string[] = [];
|
||||
for (const c of val.contents ?? []) {
|
||||
for (const s of c.staffs ?? []) {
|
||||
if (s && !allStaffs.includes(s)) allStaffs.push(s);
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: val.id ?? cleanId,
|
||||
name: val.name ?? "",
|
||||
count: val.count ?? allStaffs.length,
|
||||
staffs: allStaffs,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchHoseStaffDetails(
|
||||
domain: string,
|
||||
openapiToken: string,
|
||||
staffIds: string[]
|
||||
): Promise<HoseStaffDetail[]> {
|
||||
if (staffIds.length === 0) return [];
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/staffs/getStaffIds?accessToken=${encodeURIComponent(openapiToken)}`;
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify({
|
||||
type: "STAFFID",
|
||||
conditionIds: staffIds.slice(0, 100),
|
||||
}),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取合思员工详情失败: ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as { items?: HoseStaffDetail[] };
|
||||
return json.items ?? [];
|
||||
}
|
||||
|
||||
export async function listHoseStaffsByOpenApi(input: {
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
domain?: string;
|
||||
role?: string;
|
||||
roleDefId?: string;
|
||||
}) {
|
||||
const probe = await probeHoseDomain(input.appKey, input.appSecurity, input.domain);
|
||||
const roleQuery = input.role ?? input.roleDefId ?? "admin";
|
||||
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken);
|
||||
let targetRoleDefId: string | undefined;
|
||||
let targetRoleName: string | undefined;
|
||||
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id === roleQuery || role.id === `${probe.corpId}:${roleQuery}`) {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
|
||||
if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) {
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id.endsWith(":admin") || role.name === "主管理员") {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetRoleDefId) {
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.name.toLowerCase().includes(roleQuery.toLowerCase())) {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetRoleDefId) {
|
||||
throw new AuthenticationError(`未找到匹配 '${roleQuery}' 的角色定义`);
|
||||
}
|
||||
|
||||
const roleStaffs = await fetchHoseRoleStaffs(probe.domain, probe.openapiToken, targetRoleDefId);
|
||||
const staffs = await fetchHoseStaffDetails(probe.domain, probe.openapiToken, roleStaffs.staffs);
|
||||
return {
|
||||
domain: probe.domain,
|
||||
corpId: probe.corpId,
|
||||
corpName: probe.corpName ?? probe.corpId,
|
||||
roleId: targetRoleDefId,
|
||||
roleName: targetRoleName,
|
||||
staffs,
|
||||
};
|
||||
}
|
||||
@@ -12,7 +12,11 @@ export const PRIMARY_TOKEN_CACHE_PATH = join(
|
||||
|
||||
export const TOKEN_CACHE_PATH = PRIMARY_TOKEN_CACHE_PATH;
|
||||
|
||||
function resolveTokenCachePath(): string {
|
||||
export function resolveTokenCachePath(): string {
|
||||
const envFile = process.env.HOSE_TOKENS_FILE?.trim();
|
||||
if (envFile) return envFile;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "tokens.json");
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
|
||||
@@ -28,9 +32,15 @@ function ensureDir(path: string): void {
|
||||
|
||||
let memoryTokenCache: TokenStore | null = null;
|
||||
let lastMtimeMs = 0;
|
||||
let lastResolvedPath = "";
|
||||
|
||||
export function loadTokenStore(): TokenStore {
|
||||
const filePath = resolveTokenCachePath();
|
||||
if (filePath !== lastResolvedPath) {
|
||||
memoryTokenCache = null;
|
||||
lastMtimeMs = 0;
|
||||
lastResolvedPath = filePath;
|
||||
}
|
||||
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
@@ -53,8 +63,9 @@ export function loadTokenStore(): TokenStore {
|
||||
}
|
||||
|
||||
export function saveTokenStore(store: TokenStore): void {
|
||||
const targetPath = resolveTokenCachePath();
|
||||
memoryTokenCache = store;
|
||||
const targetPath = PRIMARY_TOKEN_CACHE_PATH;
|
||||
lastResolvedPath = targetPath;
|
||||
ensureDir(targetPath);
|
||||
|
||||
// MAJ-03: 强制写入 0o600 保护敏感凭证
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { CorpContext } from "../config/manager.js";
|
||||
import { createSessionClient } from "../http/session-client.js";
|
||||
|
||||
// ── 精简 MCP Auth Tools (其余复杂登录/刷新均由 CLI 直接提供) ───────────────────
|
||||
|
||||
export const authTools = [
|
||||
{
|
||||
name: "list_corps",
|
||||
description: "列出当前所有已配置的企业列表",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
|
||||
return {
|
||||
activeCorp: corpContext.getCurrent()?.id,
|
||||
corporations: corpContext.listCorps(),
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "switch_corp",
|
||||
description: "切换当前活跃工作企业",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("目标企业 ID"),
|
||||
}),
|
||||
handler: async (
|
||||
{ corpContext }: { corpContext: CorpContext },
|
||||
params: { corpId: string }
|
||||
) => {
|
||||
const success = corpContext.switchCorp(params.corpId);
|
||||
if (!success) {
|
||||
throw new Error(`企业 ${params.corpId} 不存在或未配置`);
|
||||
}
|
||||
const current = corpContext.getCurrent();
|
||||
return {
|
||||
success: true,
|
||||
message: `已切换到企业: ${current?.name} (${current?.id})`,
|
||||
corp: current,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "whoami",
|
||||
description: "查看当前操作员身份、当前活跃企业与账号状态",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
|
||||
const current = corpContext.getCurrent();
|
||||
if (!current) {
|
||||
return {
|
||||
authenticated: false,
|
||||
message: "未配置任何企业,请先运行 hose-use auth login",
|
||||
};
|
||||
}
|
||||
|
||||
let sessionValid = false;
|
||||
let sessionData: unknown = null;
|
||||
try {
|
||||
const client = await createSessionClient(current);
|
||||
const res = await client.get("api/account/v2/session").json<{ value?: unknown }>();
|
||||
sessionData = res.value;
|
||||
sessionValid = !!res.value;
|
||||
} catch {
|
||||
sessionValid = false;
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: sessionValid,
|
||||
currentCorp: {
|
||||
id: current.id,
|
||||
name: current.name,
|
||||
staffId: current.credentials.staffId,
|
||||
source: current.source,
|
||||
accountId: current.accountId,
|
||||
baseUrl: current.baseUrl,
|
||||
},
|
||||
session: sessionData,
|
||||
};
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -11,11 +11,18 @@ export const CorpTokensSchema = z.object({
|
||||
unityJwt: z.string(),
|
||||
easToken: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
unity: z.object({
|
||||
unityJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
piper: z.object({
|
||||
hoseToken: z.string(),
|
||||
easJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, utimesSync } from "node:fs";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, statSync, utimesSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
syncLegacyEnterprisesDir,
|
||||
syncLegacyGlobalConfig,
|
||||
} from "./loader.js";
|
||||
import { saveAccount, loadAccountStore, resolveAccountCachePath } from "../auth/account-store.js";
|
||||
import type { CorpConfig } from "./types.js";
|
||||
|
||||
describe("core/config/loader", () => {
|
||||
@@ -213,4 +214,30 @@ describe("core/config/loader", () => {
|
||||
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
|
||||
expect(existsSync(legacy)).toBe(false);
|
||||
});
|
||||
|
||||
test("saveCorpConfig and saveAccount enforce 0o600 file permissions and respect HOSE_ACCOUNTS_FILE", () => {
|
||||
const targetDir = join(tempDir, "secure-corps");
|
||||
const corpFile = saveCorpConfig(createMockCorp("sec-1", "安全测试企业"), targetDir);
|
||||
if (process.platform !== "win32") {
|
||||
expect(statSync(corpFile).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
|
||||
const customAccountsFile = join(tempDir, "secure-accounts", "accounts.json");
|
||||
process.env.HOSE_ACCOUNTS_FILE = customAccountsFile;
|
||||
expect(resolveAccountCachePath()).toBe(customAccountsFile);
|
||||
|
||||
saveAccount({
|
||||
accountId: "86-13800138000",
|
||||
cloudAuthToken: "secret-cloud-token",
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
corporations: [],
|
||||
});
|
||||
|
||||
expect(existsSync(customAccountsFile)).toBe(true);
|
||||
if (process.platform !== "win32") {
|
||||
expect(statSync(customAccountsFile).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
expect(loadAccountStore().accounts["86-13800138000"]?.cloudAuthToken).toBe("secret-cloud-token");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema, normalizeCorpConfig } from "./types.js";
|
||||
|
||||
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
||||
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||
@@ -17,7 +17,18 @@ export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "c
|
||||
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function writeSecureFile(filePath: string, content: string): void {
|
||||
ensureDir(dirname(filePath));
|
||||
writeFileSync(filePath, content, { encoding: "utf-8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(filePath, 0o600);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function resolveEnterprisesDirs(): string[] {
|
||||
@@ -165,8 +176,7 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||
|
||||
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");
|
||||
writeSecureFile(targetFile, JSON.stringify(updated, null, 2));
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -184,7 +194,7 @@ export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||
try {
|
||||
const content = readFileSync(join(dir, file), "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
const corp = CorpConfigSchema.parse(parsed);
|
||||
const corp = normalizeCorpConfig(CorpConfigSchema.parse(parsed));
|
||||
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
|
||||
if (!byId.has(corp.id)) {
|
||||
byId.set(corp.id, corp);
|
||||
@@ -228,9 +238,9 @@ export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
// ignore malformed existing file
|
||||
}
|
||||
}
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const validated = normalizeCorpConfig(CorpConfigSchema.parse(config));
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||
writeSecureFile(filePath, JSON.stringify(validated, null, 2));
|
||||
return filePath;
|
||||
}
|
||||
|
||||
|
||||
+16
-13
@@ -1,4 +1,11 @@
|
||||
import { CorpConfig, GlobalConfig } from "./types.js";
|
||||
import {
|
||||
CorpConfig,
|
||||
getCorpExpiresAt,
|
||||
getCorpPhysicalId,
|
||||
getCorpStaffId,
|
||||
getCorpStaffName,
|
||||
} from "./types.js";
|
||||
import { NotFoundError, NotLoggedInError, ValidationError } from "../errors.js";
|
||||
import { saveGlobalConfig } from "./loader.js";
|
||||
|
||||
export interface CorpSummary {
|
||||
@@ -35,18 +42,14 @@ export function resolveCorpConfig(
|
||||
let corp = corps.find((item) => item.id === selectedCorpId);
|
||||
// 2. 其次按企业物理 ID 匹配 (如 uzU7pcWfScck00)
|
||||
if (!corp) {
|
||||
corp = corps.find(
|
||||
(item) =>
|
||||
item.corpId === selectedCorpId ||
|
||||
item.credentials.corpId === selectedCorpId
|
||||
);
|
||||
corp = corps.find((item) => getCorpPhysicalId(item) === selectedCorpId);
|
||||
}
|
||||
if (corp) return corp;
|
||||
throw new Error(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`);
|
||||
throw new NotFoundError(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`);
|
||||
}
|
||||
|
||||
if (!options.stateful) {
|
||||
throw new Error(
|
||||
throw new ValidationError(
|
||||
"当前处于无状态模式 (Stateless Mode)。执行企业级操作必须显式指定 --corp <corpId>。\n" +
|
||||
"如需设置默认企业,可执行 `hose-use config mode stateful` 切换为有状态模式。"
|
||||
);
|
||||
@@ -56,7 +59,7 @@ export function resolveCorpConfig(
|
||||
if (firstCorp) return firstCorp;
|
||||
|
||||
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
|
||||
throw new Error(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`);
|
||||
throw new NotLoggedInError(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`);
|
||||
}
|
||||
|
||||
export class CorpContext {
|
||||
@@ -160,14 +163,14 @@ export class CorpContext {
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
corpId: getCorpPhysicalId(corp),
|
||||
staffId: getCorpStaffId(corp),
|
||||
staffName: getCorpStaffName(corp),
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
expiresAt: getCorpExpiresAt(corp),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -66,6 +66,69 @@ export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
|
||||
/**
|
||||
* 获取企业真实物理 corpId(统一收敛 corp.corpId / corp.credentials.corpId / corp.id)
|
||||
*/
|
||||
export function getCorpPhysicalId(corp: CorpConfig): string {
|
||||
return corp.corpId || corp.credentials.corpId || corp.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业内当前员工工号 staffId(统一收敛 corp.credentials.staffId / corp.staffId)
|
||||
*/
|
||||
export function getCorpStaffId(corp: CorpConfig): string {
|
||||
return corp.credentials.staffId || corp.staffId || "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业内当前员工姓名(统一收敛 corp.staffName / corp.session?.staffName)
|
||||
*/
|
||||
export function getCorpStaffName(corp: CorpConfig): string | undefined {
|
||||
return corp.staffName || corp.session?.staffName || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取凭证过期时间戳 ms(统一收敛 corp.auth?.expiresAt / corp.session?.expTime)
|
||||
*/
|
||||
export function getCorpExpiresAt(corp: CorpConfig): number | undefined {
|
||||
return corp.auth?.expiresAt || (corp.session?.expTime ?? undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 CorpConfig 冗余字段,确保顶层与嵌套凭证/会话字段保持一致
|
||||
*/
|
||||
export function normalizeCorpConfig(corp: CorpConfig): CorpConfig {
|
||||
const physicalCorpId = getCorpPhysicalId(corp);
|
||||
const staffId = getCorpStaffId(corp);
|
||||
const staffName = getCorpStaffName(corp);
|
||||
const expiresAt = getCorpExpiresAt(corp);
|
||||
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
|
||||
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
|
||||
|
||||
return {
|
||||
...corp,
|
||||
corpId: physicalCorpId,
|
||||
...(staffId ? { staffId } : {}),
|
||||
...(staffName ? { staffName } : {}),
|
||||
credentials: {
|
||||
...corp.credentials,
|
||||
corpId: corp.credentials.corpId || physicalCorpId,
|
||||
staffId,
|
||||
...(appKey ? { appKey } : {}),
|
||||
...(appSecurity ? { appSecurity } : {}),
|
||||
},
|
||||
...(corp.auth || expiresAt
|
||||
? {
|
||||
auth: {
|
||||
refreshTtl: corp.auth?.refreshTtl ?? 300,
|
||||
...corp.auth,
|
||||
...(expiresAt ? { expiresAt } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
// ── 全局运行配置(有状态/无状态模式)─────────────────────────────────────────
|
||||
|
||||
export const GlobalConfigSchema = z.object({
|
||||
@@ -79,3 +142,4 @@ export const GlobalConfigSchema = z.object({
|
||||
|
||||
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
|
||||
|
||||
|
||||
@@ -37,6 +37,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(tableNames.has("approval_findings")).toBe(true);
|
||||
expect(tableNames.has("aipro_logs")).toBe(true);
|
||||
expect(tableNames.has("cache_entries")).toBe(true);
|
||||
expect(tableNames.has("observed_events")).toBe(true);
|
||||
expect(tableNames.has("workflow_error_alerts")).toBe(true);
|
||||
|
||||
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
||||
const indices = db
|
||||
@@ -51,6 +53,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(indexNames.has("idx_findings_rule_id")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_namespace")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
||||
expect(indexNames.has("idx_observed_events_scope")).toBe(true);
|
||||
expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true);
|
||||
});
|
||||
|
||||
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
||||
|
||||
@@ -184,6 +184,38 @@ export const migrations: DatabaseMigration[] = [
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 3,
|
||||
name: "003_events_and_workflow_alerts_tables",
|
||||
up(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS observed_events (
|
||||
scope_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
corp_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
observed_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (scope_key, id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_observed_events_scope ON observed_events(scope_key, observed_at);");
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS workflow_error_alerts (
|
||||
scope_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
pipeline_id TEXT NOT NULL,
|
||||
platform_id TEXT NOT NULL,
|
||||
pipeline_name TEXT,
|
||||
error_count INTEGER NOT NULL,
|
||||
state INTEGER NOT NULL DEFAULT 0,
|
||||
observed_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (scope_key, id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_workflow_alerts_scope ON workflow_error_alerts(scope_key);");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -12,12 +12,35 @@ export class EkbError extends Error {
|
||||
export class NotLoggedInError extends EkbError {
|
||||
constructor(message = "No corp selected") {
|
||||
super(message, "NOT_LOGGED_IN", 401);
|
||||
this.name = "NotLoggedInError";
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthenticationError extends EkbError {
|
||||
constructor(message = "Authentication failed") {
|
||||
super(message, "AUTH_FAILED", 401);
|
||||
this.name = "AuthenticationError";
|
||||
}
|
||||
}
|
||||
|
||||
export class PermissionError extends EkbError {
|
||||
constructor(message = "Permission denied") {
|
||||
super(message, "FORBIDDEN", 403);
|
||||
this.name = "PermissionError";
|
||||
}
|
||||
}
|
||||
|
||||
export class NotFoundError extends EkbError {
|
||||
constructor(message: string, code = "NOT_FOUND") {
|
||||
super(message, code, 404);
|
||||
this.name = "NotFoundError";
|
||||
}
|
||||
}
|
||||
|
||||
export class ValidationError extends EkbError {
|
||||
constructor(message: string, code = "VALIDATION_ERROR") {
|
||||
super(message, code, 400);
|
||||
this.name = "ValidationError";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,3 +50,12 @@ export class BusinessError extends EkbError {
|
||||
this.name = "BusinessError";
|
||||
}
|
||||
}
|
||||
|
||||
export class EkbApiError extends EkbError {
|
||||
constructor(message: string, code = "API_ERROR", status = 500) {
|
||||
super(message, code, status);
|
||||
this.name = "EkbApiError";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,8 +13,12 @@ import {
|
||||
createOpenApiClient,
|
||||
getOpenApiHeaders,
|
||||
} from "./openapi-client.js";
|
||||
import { resolveCorpCluster } from "./unity-client.js";
|
||||
import { resolveCorpCluster, getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
||||
import { getScriptEngineClient } from "./script-engine-client.js";
|
||||
import { setCorpTokens, resetTokenStoreMemory } from "../auth/token-store.js";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
function mockCorp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
@@ -109,4 +113,41 @@ describe("core/http/unity-client & script-engine-client", () => {
|
||||
it("getScriptEngineClient is defined and callable", () => {
|
||||
expect(getScriptEngineClient).toBeDefined();
|
||||
});
|
||||
|
||||
it("reuses persisted EASO and Unity tokens from token-store across CLI runs without network calls", async () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "hose-tokens-test-"));
|
||||
const prevTokensFile = process.env.HOSE_TOKENS_FILE;
|
||||
process.env.HOSE_TOKENS_FILE = join(tempDir, "tokens.json");
|
||||
|
||||
try {
|
||||
clearUnityClientCache();
|
||||
resetTokenStoreMemory();
|
||||
|
||||
const corp = mockCorp({ id: "corp-persisted" });
|
||||
setCorpTokens("corp-persisted", {
|
||||
eas: {
|
||||
hoseToken: "persisted-hose-token",
|
||||
unityJwt: "persisted-unity-jwt",
|
||||
easToken: "persisted-easo-token",
|
||||
expiresAt: Date.now() + 3600 * 1000,
|
||||
sourceAccessToken: "mock-access-token",
|
||||
},
|
||||
});
|
||||
|
||||
// Simulate fresh process memory
|
||||
resetTokenStoreMemory();
|
||||
|
||||
const easo = await getEasoClient(corp);
|
||||
expect(easo.client).toBeDefined();
|
||||
|
||||
const unity = await getUnityClient(corp);
|
||||
expect(unity.unityJwt).toBe("persisted-unity-jwt");
|
||||
} finally {
|
||||
if (prevTokensFile === undefined) delete process.env.HOSE_TOKENS_FILE;
|
||||
else process.env.HOSE_TOKENS_FILE = prevTokensFile;
|
||||
resetTokenStoreMemory();
|
||||
clearUnityClientCache();
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,14 @@ import {
|
||||
fetchHoseToken,
|
||||
EKB_BASE_URL,
|
||||
} from "./unity-client.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
import {
|
||||
getCorpTokens,
|
||||
setCorpTokens,
|
||||
} from "../auth/token-store.js";
|
||||
|
||||
export const SCRIPT_ENGINE_BASE_URL = "https://piper.ekuaibao.com";
|
||||
|
||||
@@ -16,9 +24,36 @@ export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
|
||||
// 内存缓存
|
||||
const scriptEngineMemoryCache = new Map<
|
||||
string,
|
||||
{ jwt: string; hoseToken: string; expiresAt: number }
|
||||
{ jwt: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
function invalidateScriptEngineCache(corpId: string, cacheKey?: string): void {
|
||||
if (cacheKey) {
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
} else {
|
||||
const prefix = `${corpId}:`;
|
||||
for (const key of scriptEngineMemoryCache.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
scriptEngineMemoryCache.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
const persisted = getCorpTokens(corpId);
|
||||
if (persisted?.piper) {
|
||||
const next = { ...persisted };
|
||||
delete next.piper;
|
||||
setCorpTokens(corpId, next);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearScriptEngineClientCache(corpId?: string): void {
|
||||
if (!corpId) {
|
||||
scriptEngineMemoryCache.clear();
|
||||
return;
|
||||
}
|
||||
invalidateScriptEngineCache(corpId);
|
||||
}
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
@@ -57,21 +92,50 @@ export async function getScriptEngineClient(
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:${platformId}:script-engine`;
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = scriptEngineMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
// 1. 检查 L1 内存缓存
|
||||
let mem = scriptEngineMemoryCache.get(cacheKey);
|
||||
|
||||
// 2. 检查 L2 持久化 TokenStore
|
||||
if (!mem) {
|
||||
const persisted = getCorpTokens(corp.id)?.piper;
|
||||
if (
|
||||
persisted &&
|
||||
persisted.sourceAccessToken === corp.credentials.accessToken &&
|
||||
!isExpired(persisted, refreshTtl)
|
||||
) {
|
||||
mem = {
|
||||
jwt: persisted.easJwt,
|
||||
hoseToken: persisted.hoseToken,
|
||||
expiresAt: persisted.expiresAt,
|
||||
sourceAccessToken: persisted.sourceAccessToken,
|
||||
};
|
||||
scriptEngineMemoryCache.set(cacheKey, mem);
|
||||
}
|
||||
}
|
||||
|
||||
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
||||
const cachedJwt = mem.jwt;
|
||||
const cachedHoseToken = mem.hoseToken;
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${mem.jwt}`,
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
platformid: platformId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
@@ -90,14 +154,27 @@ export async function getScriptEngineClient(
|
||||
baseUrl
|
||||
);
|
||||
|
||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
||||
const entry = {
|
||||
jwt: easoJwt,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
};
|
||||
|
||||
scriptEngineMemoryCache.set(cacheKey, entry);
|
||||
|
||||
const existingTokens = getCorpTokens(corp.id) ?? {};
|
||||
setCorpTokens(corp.id, {
|
||||
...existingTokens,
|
||||
piper: {
|
||||
hoseToken,
|
||||
easJwt: easoJwt,
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
},
|
||||
});
|
||||
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
@@ -106,7 +183,7 @@ export async function getScriptEngineClient(
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
canRefreshCorpAccessToken,
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
parseExpiresInSeconds,
|
||||
resolveLinkExpiresAt,
|
||||
selectOpenApiKey,
|
||||
} from "../auth/login.js";
|
||||
@@ -161,4 +162,11 @@ describe("core/auth/login link expiry", () => {
|
||||
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses expires-in / ttl strings to seconds for provisional auth link", () => {
|
||||
expect(parseExpiresInSeconds("24h")).toBe(86400);
|
||||
expect(parseExpiresInSeconds("7d")).toBe(604800);
|
||||
expect(parseExpiresInSeconds("86400")).toBe(86400);
|
||||
expect(parseExpiresInSeconds(3600)).toBe(3600);
|
||||
});
|
||||
});
|
||||
+137
-20
@@ -6,6 +6,11 @@ import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
import {
|
||||
clearCorpTokens,
|
||||
getCorpTokens,
|
||||
setCorpTokens,
|
||||
} from "../auth/token-store.js";
|
||||
|
||||
export const EASO_BASE_URL = "https://unity.ekuaibao.com";
|
||||
export const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
@@ -30,17 +35,28 @@ export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string })
|
||||
return "app";
|
||||
}
|
||||
|
||||
// 内存缓存
|
||||
// 内存缓存 (L1)
|
||||
const easoMemoryCache = new Map<
|
||||
string,
|
||||
{ token: string; hoseToken: string; expiresAt: number }
|
||||
{ token: string; unityJwt?: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
const unityMemoryCache = new Map<
|
||||
string,
|
||||
{ token: string; expiresAt: number }
|
||||
{ token: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
export function clearUnityClientCache(corpId?: string): void {
|
||||
if (!corpId) {
|
||||
easoMemoryCache.clear();
|
||||
unityMemoryCache.clear();
|
||||
return;
|
||||
}
|
||||
easoMemoryCache.delete(`${corpId}:easo`);
|
||||
unityMemoryCache.delete(`${corpId}:unity`);
|
||||
clearCorpTokens(corpId);
|
||||
}
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
@@ -109,6 +125,26 @@ export async function fetchEasoRealmToken(
|
||||
return token;
|
||||
}
|
||||
|
||||
function invalidateEasoCache(corpId: string): void {
|
||||
easoMemoryCache.delete(`${corpId}:easo`);
|
||||
const persisted = getCorpTokens(corpId);
|
||||
if (persisted?.eas) {
|
||||
const next = { ...persisted };
|
||||
delete next.eas;
|
||||
setCorpTokens(corpId, next);
|
||||
}
|
||||
}
|
||||
|
||||
function invalidateUnityCache(corpId: string): void {
|
||||
unityMemoryCache.delete(`${corpId}:unity`);
|
||||
const persisted = getCorpTokens(corpId);
|
||||
if (persisted?.unity) {
|
||||
const next = { ...persisted };
|
||||
delete next.unity;
|
||||
setCorpTokens(corpId, next);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 EASO 授权客户端 (用于请求 EASO 体系资源)
|
||||
*/
|
||||
@@ -117,21 +153,44 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
}> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:easo`;
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = easoMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
// 1. 检查 L1 内存缓存
|
||||
let mem = easoMemoryCache.get(cacheKey);
|
||||
|
||||
// 2. 若 L1 未命中,检查 L2 持久化 TokenStore (跨 CLI 进程复用)
|
||||
if (!mem) {
|
||||
const persisted = getCorpTokens(corp.id)?.eas;
|
||||
if (
|
||||
persisted &&
|
||||
persisted.sourceAccessToken === corp.credentials.accessToken &&
|
||||
!isExpired(persisted, refreshTtl)
|
||||
) {
|
||||
mem = {
|
||||
token: persisted.easToken,
|
||||
unityJwt: persisted.unityJwt,
|
||||
hoseToken: persisted.hoseToken,
|
||||
expiresAt: persisted.expiresAt,
|
||||
sourceAccessToken: persisted.sourceAccessToken,
|
||||
};
|
||||
easoMemoryCache.set(cacheKey, mem);
|
||||
}
|
||||
}
|
||||
|
||||
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
||||
const cachedToken = mem.token;
|
||||
const cachedHoseToken = mem.hoseToken;
|
||||
return {
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${mem.token}`,
|
||||
Authorization: `Bearer ${cachedToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corp.credentials.corpId,
|
||||
hoseaccesstoken: mem.hoseToken,
|
||||
corporationid: corpId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
easoMemoryCache.delete(cacheKey);
|
||||
invalidateEasoCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -144,7 +203,6 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
@@ -167,13 +225,38 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
hoseToken
|
||||
);
|
||||
|
||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
||||
const entry = {
|
||||
token: easoToken,
|
||||
unityJwt,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
};
|
||||
|
||||
easoMemoryCache.set(cacheKey, entry);
|
||||
unityMemoryCache.set(`${corp.id}:unity`, {
|
||||
token: unityJwt,
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
});
|
||||
|
||||
const existingTokens = getCorpTokens(corp.id) ?? {};
|
||||
setCorpTokens(corp.id, {
|
||||
...existingTokens,
|
||||
eas: {
|
||||
hoseToken,
|
||||
unityJwt,
|
||||
easToken: easoToken,
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
},
|
||||
unity: {
|
||||
unityJwt,
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
client: createAuthClient({
|
||||
@@ -185,7 +268,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
easoMemoryCache.delete(cacheKey);
|
||||
invalidateEasoCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -202,17 +285,39 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:unity`;
|
||||
|
||||
const mem = unityMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
let mem = unityMemoryCache.get(cacheKey);
|
||||
if (!mem) {
|
||||
const persisted = getCorpTokens(corp.id);
|
||||
const persistedUnity = persisted?.unity ?? (persisted?.eas ? {
|
||||
unityJwt: persisted.eas.unityJwt,
|
||||
expiresAt: persisted.eas.expiresAt,
|
||||
sourceAccessToken: persisted.eas.sourceAccessToken,
|
||||
} : undefined);
|
||||
if (
|
||||
persistedUnity &&
|
||||
persistedUnity.sourceAccessToken === corp.credentials.accessToken &&
|
||||
!isExpired(persistedUnity, refreshTtl)
|
||||
) {
|
||||
mem = {
|
||||
token: persistedUnity.unityJwt,
|
||||
expiresAt: persistedUnity.expiresAt,
|
||||
sourceAccessToken: persistedUnity.sourceAccessToken,
|
||||
};
|
||||
unityMemoryCache.set(cacheKey, mem);
|
||||
}
|
||||
}
|
||||
|
||||
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
||||
const cachedJwt = mem.token;
|
||||
return {
|
||||
unityJwt: mem.token,
|
||||
unityJwt: cachedJwt,
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${mem.token}`,
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
unityMemoryCache.delete(cacheKey);
|
||||
invalidateUnityCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -236,12 +341,24 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
baseUrl
|
||||
);
|
||||
|
||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000;
|
||||
const entry = {
|
||||
token: unityJwt,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000,
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
};
|
||||
unityMemoryCache.set(cacheKey, entry);
|
||||
|
||||
const existingTokens = getCorpTokens(corp.id) ?? {};
|
||||
setCorpTokens(corp.id, {
|
||||
...existingTokens,
|
||||
unity: {
|
||||
unityJwt,
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
unityJwt,
|
||||
client: createAuthClient({
|
||||
@@ -250,7 +367,7 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
unityMemoryCache.delete(cacheKey);
|
||||
invalidateUnityCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -1,21 +1,38 @@
|
||||
# Domains 域层说明
|
||||
|
||||
本目录按业务域组织代码,每个域独立负责自己的传输层、业务层和模型层。
|
||||
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
||||
|
||||
## 当前域
|
||||
## 当前域(共 14 个)
|
||||
|
||||
| 域 | 说明 | 详细文档 |
|
||||
|---|---|---|
|
||||
| `platform/` | 自建应用(DataLink Platform)与工作流(EASO/Piper) | [README.platform.md](./platform/README.platform.md) |
|
||||
| `datalink/` | 自建应用下的业务对象、字段、记录、权限与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `store/` | 企业应用中心/应用商店与 OpenAPI 密钥凭证 | [README.store.md](./store/README.store.md) |
|
||||
| `feetype/` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
| `platform/` | `api / tools / services / analysis / workflow-state / workflow-alert-store / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) |
|
||||
| `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | - |
|
||||
| `store/` | `api / tools / types` | 企业应用中心/应用商店与 OpenAPI 密钥凭证探查 | [README.store.md](./store/README.store.md) |
|
||||
| `feetype/` | `api / tools / types` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
|
||||
| `contact/` | `api / tools / types` | 企业组织架构(部门树)与员工通讯录检索 | - |
|
||||
| `dimension/` | `api / tools / types` | 自定义档案/核算维度类别与档案项管理 | - |
|
||||
| `role/` | `api / tools / types` | 企业角色定义组与角色成员分配查询 | - |
|
||||
| `permission/` | `api / tools / types` | 单据数据权限与可见范围规则查询 | - |
|
||||
| `menu/` | `api / tools / types` | 企业桌面端导航菜单与工作台应用清单查询 | - |
|
||||
| `message/` | `api / tools / types` | 系统通知消息分页查询与已读状态标记 | - |
|
||||
| `task/` | `api / tools / types` | 待办/已办审批任务流分页查询与汇总 | - |
|
||||
| `events/` | `poller / store / types` | 待办与未读消息增量事件轮询及基于 `core/db` (`observed_events`) 的去重存储 | - |
|
||||
|
||||
## 分层规则
|
||||
## 分层与形态规则
|
||||
|
||||
- `api.ts`:只负责 HTTP 请求和响应校验
|
||||
- `tools.ts`:负责 MCP tool 注册和业务编排
|
||||
- `types.ts`:Zod schema 与类型定义
|
||||
|
||||
Server 入口 `src/server.ts` 只调用 `domains/*/tools.ts`,不直接调用 `api.ts`。
|
||||
1. **标准三件套形态**(`contact`, `dimension`, `feetype`, `menu`, `message`, `permission`, `role`, `store`, `task`):
|
||||
- `api.ts`:只负责 HTTP 请求和响应校验
|
||||
- `tools.ts`:纯函数式业务编排,供 CLI 命令(`src/cli/commands/*`)调用
|
||||
- `types.ts`:Zod schema 与类型定义
|
||||
2. **扩展复合形态**(有明确职责拆分理由):
|
||||
- `platform/` 与 `datalink/`:使用 `services.ts` 提供跨应用聚合、台账健康度审计、批量安全编辑与对 `api.ts` 的服务级门面封装
|
||||
- `bill/`:独立拆分 `translator.ts` 负责复杂单据/审批流到结构化 Markdown 的纯函数转译
|
||||
- `approval/`:采用 `parser.ts`(DSL 解析)+ `gateway.ts`(确定性仲裁门禁)+ `repository.ts`(基于 `core/db` 的数据访问)+ `service.ts`(业务编排)
|
||||
- `events/`:组合 `task/` 与 `message/` 域的 `tools.ts` 实现轮询(`poller.ts`),并通过 `store.ts` 落盘至 `core/db`
|
||||
3. **边界与异常约束**(由 `src/cli/architecture-boundaries.test.ts` 强制校验):
|
||||
- 任何入口层(`src/cli/**`, `src/http/**`, `src/server.ts`, `src/cli.ts`, `src/aipro-cli.ts`)严禁直接导入 `domains/*/api.ts`
|
||||
- `domains/*` 严禁反向导入 `cli/`、`http/` 或顶层入口文件
|
||||
- `domains/*` 统一抛出 `EkbError` 子类(定义在 `src/core/errors.ts`)
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { getApprovalDatabase } from "./db.js";
|
||||
import { getDatabase } from "../../core/db/index.js";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { parseRuleBody, validatePreferenceText } from "./parser.js";
|
||||
import {
|
||||
AiProLogRecord,
|
||||
@@ -44,7 +45,7 @@ export class ApprovalRepository {
|
||||
private db: Database;
|
||||
|
||||
constructor(db?: Database) {
|
||||
this.db = db ?? getApprovalDatabase();
|
||||
this.db = db ?? getDatabase();
|
||||
}
|
||||
|
||||
// ===================== 规约管理 (Rules) =====================
|
||||
@@ -205,7 +206,7 @@ export class ApprovalRepository {
|
||||
public updateRule(id: string, updates: UpdateRuleInput): RuleRecord {
|
||||
const existing = this.getRuleById(id);
|
||||
if (!existing) {
|
||||
throw new Error(`未找到 ID 为 "${id}" 的规则`);
|
||||
throw new NotFoundError(`未找到 ID 为 "${id}" 的规则`);
|
||||
}
|
||||
|
||||
if (updates.body !== undefined) {
|
||||
@@ -247,7 +248,7 @@ export class ApprovalRepository {
|
||||
.query("SELECT * FROM preferences ORDER BY updated_at DESC LIMIT 1")
|
||||
.get() as any;
|
||||
if (!fallback) {
|
||||
throw new Error("数据库未初始化默认偏好配置");
|
||||
throw new NotFoundError("数据库未初始化默认偏好配置");
|
||||
}
|
||||
return this.mapPreferenceRow(fallback);
|
||||
}
|
||||
@@ -266,7 +267,7 @@ export class ApprovalRepository {
|
||||
): PreferenceRecord {
|
||||
const existing = this.getPreferenceById(id);
|
||||
if (!existing) {
|
||||
throw new Error(`未找到 ID 为 "${id}" 的偏好配置`);
|
||||
throw new NotFoundError(`未找到 ID 为 "${id}" 的偏好配置`);
|
||||
}
|
||||
|
||||
if (updates.rulesReject !== undefined) validatePreferenceText(updates.rulesReject);
|
||||
@@ -371,7 +372,7 @@ export class ApprovalRepository {
|
||||
if (row) return this.mapRunRow(row);
|
||||
const expiredRow = this.db.query("SELECT * FROM approval_runs WHERE UPPER(short_id) = UPPER(?)").get(trimmed) as any;
|
||||
if (expiredRow) {
|
||||
throw new Error(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`);
|
||||
throw new BusinessError(`审批会话 [${trimmed}] 已过期(有效时长 6 小时),请运行 hose-aipro init 重新发起审批会话`);
|
||||
}
|
||||
}
|
||||
// 2. 尝试按长 UUID 查找
|
||||
@@ -431,7 +432,7 @@ export class ApprovalRepository {
|
||||
): ApprovalRunRecord {
|
||||
const existing = this.getRunById(id);
|
||||
if (!existing) {
|
||||
throw new Error(`未找到 ID 为 "${id}" 的审批运行记录`);
|
||||
throw new NotFoundError(`未找到 ID 为 "${id}" 的审批运行记录`);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
@@ -468,7 +469,7 @@ export class ApprovalRepository {
|
||||
public injectFindings(runId: string, findings: CreateFindingInput[]): ApprovalFindingRecord[] {
|
||||
const run = this.getRunById(runId);
|
||||
if (!run) {
|
||||
throw new Error(`审批运行记录不存在: ${runId}`);
|
||||
throw new NotFoundError(`审批运行记录不存在: ${runId}`);
|
||||
}
|
||||
|
||||
// 重新挂载时清空旧要点
|
||||
@@ -521,7 +522,7 @@ export class ApprovalRepository {
|
||||
): ApprovalFindingRecord {
|
||||
const row = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any;
|
||||
if (!row) {
|
||||
throw new Error(`未找到审核要点记录: ${findingId}`);
|
||||
throw new NotFoundError(`未找到审核要点记录: ${findingId}`);
|
||||
}
|
||||
|
||||
const checkStatus = updates.checkStatus ?? row.check_status;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { KyInstance } from "ky";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { ApprovalRepository } from "./repository.js";
|
||||
import { parseRuleBody } from "./parser.js";
|
||||
import {
|
||||
@@ -64,7 +65,7 @@ export class ApprovalService {
|
||||
// 1. 获取单据详情
|
||||
const bills = await getBillByCodeOrId(client, corpId, documentSn);
|
||||
if (bills.length === 0) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`);
|
||||
throw new NotFoundError(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`);
|
||||
}
|
||||
const bill = bills[0];
|
||||
const actualSn = bill.billCode || documentSn;
|
||||
@@ -75,7 +76,7 @@ export class ApprovalService {
|
||||
if (!scopeDetail) {
|
||||
const allScopes = this.repo.listScopes();
|
||||
if (allScopes.length === 0) {
|
||||
throw new Error("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则");
|
||||
throw new BusinessError("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则");
|
||||
}
|
||||
|
||||
// 自动启发式场景匹配
|
||||
@@ -95,7 +96,7 @@ export class ApprovalService {
|
||||
}
|
||||
|
||||
if (!scopeDetail || scopeDetail.rules.length === 0) {
|
||||
throw new Error(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`);
|
||||
throw new NotFoundError(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`);
|
||||
}
|
||||
|
||||
// 3. 提取所有规则的 AST 条款要点
|
||||
@@ -119,7 +120,7 @@ export class ApprovalService {
|
||||
}
|
||||
|
||||
if (clauseInputs.length === 0) {
|
||||
throw new Error(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`);
|
||||
throw new BusinessError(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`);
|
||||
}
|
||||
|
||||
// 4. 为单据创建/重置审批运行记录
|
||||
@@ -192,7 +193,7 @@ export class ApprovalService {
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
throw new Error(`未找到要点: ${item.id ?? `#${item.index}`}`);
|
||||
throw new NotFoundError(`未找到要点: ${item.id ?? `#${item.index}`}`);
|
||||
}
|
||||
|
||||
this.repo.updateFinding(target.id, {
|
||||
|
||||
@@ -107,18 +107,18 @@ export interface ApprovalFindingRecord {
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export class ApprovalRuleValidationError extends Error {
|
||||
public readonly code = "RULE_VALIDATION_ERROR";
|
||||
import { BusinessError } from "../../core/errors.js";
|
||||
|
||||
export class ApprovalRuleValidationError extends BusinessError {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
super(message, "RULE_VALIDATION_ERROR", 400);
|
||||
this.name = "ApprovalRuleValidationError";
|
||||
}
|
||||
}
|
||||
|
||||
export class ApprovalGatewayBlockedError extends Error {
|
||||
public readonly code = "APPROVAL_GATEWAY_BLOCKED";
|
||||
export class ApprovalGatewayBlockedError extends BusinessError {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
super(message, "APPROVAL_GATEWAY_BLOCKED", 400);
|
||||
this.name = "ApprovalGatewayBlockedError";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ import {
|
||||
RawBillSearchResponseSchema,
|
||||
RawBillBatchGetResponseSchema,
|
||||
EntityListResponseSchema,
|
||||
FormSpecificationSchema,
|
||||
type RawBillSearchResponse,
|
||||
type RawBillItem,
|
||||
type EntityMeta,
|
||||
type FormSpecification,
|
||||
} from "./types.js";
|
||||
|
||||
function quoted(value: string): string {
|
||||
@@ -472,3 +474,31 @@ export async function getDatalinkCard(
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 单据模板规格定义 API(GET api/form/v2/specifications/[{specificationId}])──
|
||||
|
||||
export async function getFormSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecification | undefined> {
|
||||
const cleanId = specificationId.replace(/^\[|\]$/g, "").trim();
|
||||
if (!cleanId) return undefined;
|
||||
const response = await client.get(
|
||||
`api/form/v2/specifications/[${encodeURIComponent(cleanId)}]`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
}
|
||||
);
|
||||
const json = (await response.json()) as {
|
||||
items?: unknown[];
|
||||
value?: unknown;
|
||||
id?: string;
|
||||
};
|
||||
const raw = Array.isArray(json.items)
|
||||
? json.items[0]
|
||||
: json.value ?? (typeof json.id === "string" ? json : undefined);
|
||||
if (!raw || typeof raw !== "object") return undefined;
|
||||
return FormSpecificationSchema.parse(raw);
|
||||
}
|
||||
|
||||
+97
-116
@@ -1,9 +1,15 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { basename, extname, join, resolve } from "node:path";
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import {
|
||||
BusinessError,
|
||||
EkbApiError,
|
||||
NotFoundError,
|
||||
PermissionError,
|
||||
ValidationError,
|
||||
} from "../../core/errors.js";
|
||||
import {
|
||||
searchRawBills,
|
||||
getRawBillsByIds,
|
||||
@@ -21,6 +27,7 @@ import {
|
||||
commentBillAction,
|
||||
getInvoiceValidationDetail,
|
||||
getDatalinkCard,
|
||||
getFormSpecification,
|
||||
type BillActionOptions,
|
||||
type BillActionTarget,
|
||||
} from "./api.js";
|
||||
@@ -48,9 +55,10 @@ import {
|
||||
type BillRelationsReport,
|
||||
type BillAttachment,
|
||||
type BillAttachmentReport,
|
||||
type FormSpecification,
|
||||
type FormSpecificationComponent,
|
||||
type FormPriorityItem,
|
||||
} from "./types.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { resolveDimension } from "../dimension/tools.js";
|
||||
|
||||
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
|
||||
@@ -531,13 +539,13 @@ export async function downloadBillAttachments(
|
||||
report: BillAttachmentReport;
|
||||
}> {
|
||||
const report = await getBillAttachments(client, corpId, target);
|
||||
if (!report) throw new Error(`未找到单据附件: ${target}`);
|
||||
if (!report) throw new NotFoundError(`未找到单据附件: ${target}`);
|
||||
|
||||
const selected = fileId
|
||||
? report.attachments.filter((item) => item.fileId === fileId)
|
||||
: report.attachments;
|
||||
if (fileId && selected.length === 0) {
|
||||
throw new Error(`单据 ${target} 中未找到附件 fileId: ${fileId}`);
|
||||
throw new NotFoundError(`单据 ${target} 中未找到附件 fileId: ${fileId}`);
|
||||
}
|
||||
|
||||
const destination = resolve(outputDir);
|
||||
@@ -555,7 +563,7 @@ export async function downloadBillAttachments(
|
||||
const path = uniqueAttachmentPath(destination, safeAttachmentName(sourceName), attachment.fileId, usedPaths);
|
||||
const response = await fetch(attachment.url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`附件下载失败 (${response.status}): ${sourceName}`);
|
||||
throw new EkbApiError(`附件下载失败 (${response.status}): ${sourceName}`, "ATTACHMENT_DOWNLOAD_FAILED", response.status);
|
||||
}
|
||||
const content = new Uint8Array(await response.arrayBuffer());
|
||||
await writeFile(path, content);
|
||||
@@ -957,7 +965,7 @@ function actionTarget(raw: Record<string, unknown>, fallback: string): BillActio
|
||||
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
||||
const backlogId = typeof raw.id === "string" ? raw.id : fallback;
|
||||
const flowId = typeof flow.id === "string" ? flow.id : undefined;
|
||||
if (!flowId) throw new Error(`未找到单据流程 ID: ${fallback}`);
|
||||
if (!flowId) throw new NotFoundError(`未找到单据流程 ID: ${fallback}`);
|
||||
const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record<string, unknown> : {};
|
||||
const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
|
||||
const nodeName = typeof raw.nodeName === "string" ? raw.nodeName : undefined;
|
||||
@@ -978,7 +986,7 @@ function actionTarget(raw: Record<string, unknown>, fallback: string): BillActio
|
||||
|
||||
async function resolveActionTarget(client: KyInstance, corpId: string, target: string): Promise<BillActionTarget> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
if (!raw) throw new Error(`未找到单据或审批任务: ${target}`);
|
||||
if (!raw) throw new NotFoundError(`未找到单据或审批任务: ${target}`);
|
||||
return actionTarget(raw, target);
|
||||
}
|
||||
|
||||
@@ -1018,11 +1026,11 @@ export async function resolveBillStaffIds(
|
||||
for (const value of values) {
|
||||
const matches = matchesFor(value);
|
||||
if (matches.length !== 1) {
|
||||
if (matches.length > 1) throw new Error(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`);
|
||||
throw new Error(`未找到员工 [${value}]`);
|
||||
if (matches.length > 1) throw new ValidationError(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`);
|
||||
throw new NotFoundError(`未找到员工 [${value}]`);
|
||||
}
|
||||
const id = typeof matches[0]?.id === "string" ? matches[0].id : undefined;
|
||||
if (!id) throw new Error(`员工 [${value}] 缺少可用 ID`);
|
||||
if (!id) throw new BusinessError(`员工 [${value}] 缺少可用 ID`);
|
||||
result.push(id);
|
||||
}
|
||||
return result;
|
||||
@@ -1049,7 +1057,7 @@ async function runBillAction(
|
||||
const allowed = entry?.[1];
|
||||
const requiredAction = action === "approve" ? "freeflow.agree" : action === "reject" ? "freeflow.reject" : "freeflow.addnode";
|
||||
if (!Array.isArray(allowed) || !allowed.includes(requiredAction)) {
|
||||
throw new Error(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`);
|
||||
throw new PermissionError(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1077,22 +1085,22 @@ export function approveBill(client: KyInstance, corpId: string, target: string,
|
||||
}
|
||||
|
||||
export function rejectBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空");
|
||||
if (!options.comment?.trim()) throw new ValidationError("驳回原因不能为空");
|
||||
return runBillAction(client, corpId, target, "reject", options);
|
||||
}
|
||||
|
||||
export function transferBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.approverIds?.length) throw new Error("转交审批至少需要一个 approverId");
|
||||
if (!options.approverIds?.length) throw new ValidationError("转交审批至少需要一个 approverId");
|
||||
return runBillAction(client, corpId, target, "transfer", options);
|
||||
}
|
||||
|
||||
export function addNodeBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.approverIds?.length) throw new Error("加签审批至少需要一个 approverId");
|
||||
if (!options.approverIds?.length) throw new ValidationError("加签审批至少需要一个 approverId");
|
||||
return runBillAction(client, corpId, target, "add-node", options);
|
||||
}
|
||||
|
||||
export function commentBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||||
if (!options.comment?.trim()) throw new Error("评论内容不能为空");
|
||||
if (!options.comment?.trim()) throw new ValidationError("评论内容不能为空");
|
||||
return runBillAction(client, corpId, target, "comment", options);
|
||||
}
|
||||
|
||||
@@ -1267,13 +1275,15 @@ export async function searchAndFormatBills(
|
||||
});
|
||||
} catch (err) {
|
||||
if (String(err).includes("timed out") || (err as any)?.name === "TimeoutError") {
|
||||
throw new Error(
|
||||
throw new EkbApiError(
|
||||
`全局单据台账检索超时。在大企业或海量单据租户中,建议指定时间范围或单号筛选:\n` +
|
||||
`建议:\n` +
|
||||
` - 指定时间范围:hose-use bill list --since=7d 或 --start-date=2026-09-01\n` +
|
||||
` - 查看当前员工发起的单据:hose-use task submitted 或 hose-use bill list --mine\n` +
|
||||
` - 查看待我审批单据:hose-use task todo\n` +
|
||||
` - 按单号精确查询:hose-use bill get <单号>`
|
||||
` - 按单号精确查询:hose-use bill get <单号>`,
|
||||
"BILL_SEARCH_TIMEOUT",
|
||||
504
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
@@ -1349,104 +1359,6 @@ export async function searchAndFormatBills(
|
||||
};
|
||||
}
|
||||
|
||||
// ── MCP Tools 适配 ────────────────────────────────────────────────────────────
|
||||
|
||||
export const billTools = [
|
||||
{
|
||||
name: "bill_search",
|
||||
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称,原生支持服务端时间与单号过滤)",
|
||||
parameters: z.object({
|
||||
code: z.string().optional().describe("按单据编号/单号过滤(如 jO1it3cIufDjNS)"),
|
||||
keyword: z.string().optional().describe("按关键字模糊搜索标题、名称或内容"),
|
||||
searchFields: z.union([z.array(z.string()), z.string()]).optional().describe("指定 keyword 检索匹配的字段列表,默认 ['name', 'code', 'form'],可传入 ['name'] 或 'name,code' 等"),
|
||||
since: z.string().optional().describe("相对时间范围,如 7d (7天), 30d (30天), 90d, 1y"),
|
||||
startDate: z.string().optional().describe("起始时间 (YYYY-MM-DD 或毫秒时间戳)"),
|
||||
endDate: z.string().optional().describe("截止时间 (YYYY-MM-DD 或毫秒时间戳)"),
|
||||
filterBy: z.string().optional().describe("原始合思 RQL 检索表达式,如 ((createTime > 1780000000000) && (code.in('BX-001')))"),
|
||||
select: z.string().optional().describe("按需返回字段(逗号分隔),如 id,code,name,createTime,updateTime,form"),
|
||||
distinct: z.boolean().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("拉取记录数"),
|
||||
order: z.enum(["ASC", "DESC", "asc", "desc"]).optional().default("DESC").describe("排序方向,默认 DESC 最新在前"),
|
||||
}),
|
||||
handler: async (
|
||||
{ corpContext }: { corpContext: CorpContext },
|
||||
params: BillQueryParams
|
||||
) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) {
|
||||
throw new Error("未配置活跃企业上下文");
|
||||
}
|
||||
const client = await createSessionClient(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 createSessionClient(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 createSessionClient(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,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export async function getTranslatorContext(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
@@ -1596,6 +1508,74 @@ export async function getTranslatorContext(
|
||||
};
|
||||
}
|
||||
|
||||
export function formatFormPriorityList(priorityList: FormPriorityItem[] | undefined): string {
|
||||
if (!Array.isArray(priorityList) || priorityList.length === 0) return "-";
|
||||
const sorted = [...priorityList].sort((a, b) => b.priority - a.priority);
|
||||
return sorted.map((p) => `${p.type}(${p.priority})`).join(" > ");
|
||||
}
|
||||
|
||||
export function hasLinkageOverridePriority(priorityList: FormPriorityItem[] | undefined): boolean {
|
||||
if (!Array.isArray(priorityList) || priorityList.length === 0) return false;
|
||||
const linkage = priorityList.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = priorityList.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
if (!linkage || !manual) return false;
|
||||
return linkage.priority > manual.priority;
|
||||
}
|
||||
|
||||
export interface FormSpecificationInspection {
|
||||
specification: FormSpecification;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export async function inspectFormSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecificationInspection | undefined> {
|
||||
const spec = await getFormSpecification(client, corpId, specificationId);
|
||||
if (!spec) return undefined;
|
||||
|
||||
const warnings: string[] = [];
|
||||
const linkageSources = spec.components.filter(
|
||||
(c) => c.isLinkageAssignment === true || Boolean(c.assignmentRule)
|
||||
);
|
||||
const overrideTargets = spec.components.filter((c) =>
|
||||
hasLinkageOverridePriority(c.priorityList)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
if (src.isLinkageAssignment) {
|
||||
warnings.push(
|
||||
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 开启了联动赋值 (isLinkageAssignment=true, assignmentRule=${src.assignmentRule || "-"})`
|
||||
);
|
||||
} else if (src.assignmentRule) {
|
||||
warnings.push(
|
||||
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 配置了联动规则 (assignmentRule=${src.assignmentRule}, 当前 isLinkageAssignment=false)`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (linkageSources.length > 0 && overrideTargets.length > 0) {
|
||||
const targetNames = overrideTargets.map((t) => `${t.label || t.name}(${t.name})`).join("、");
|
||||
warnings.push(
|
||||
`优先级覆盖风险: 字段 [${targetNames}] 的赋值优先级中 LINKAGE_ASSIGNMENT 高于 MANUALLY_FILL_IN(如 LINKAGE_ASSIGNMENT(10) > MANUALLY_FILL_IN(5)),当关联业务对象触发联动赋值时,手动填写或工作流 API 显式传入的值将被联动值覆盖!`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
specification: spec,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
getRawBillFlow,
|
||||
getFormSpecification,
|
||||
type FormSpecification,
|
||||
type FormSpecificationComponent,
|
||||
type FormPriorityItem,
|
||||
};
|
||||
|
||||
export {
|
||||
translateBillFlowToMarkdown,
|
||||
formatBillFlowOperator,
|
||||
@@ -1612,3 +1592,4 @@ export {
|
||||
formatDynamicField,
|
||||
type TranslatorOptions,
|
||||
} from "./translator.js";
|
||||
|
||||
@@ -26,6 +26,60 @@ export const EntityListResponseSchema = z.object({
|
||||
items: z.array(EntitySchema).default([]),
|
||||
});
|
||||
|
||||
export const FormPriorityItemSchema = z
|
||||
.object({
|
||||
type: z.string(),
|
||||
label: z.string().optional().default(""),
|
||||
priority: z.number().optional(),
|
||||
value: z.number().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.transform((item) => ({
|
||||
...item,
|
||||
priority: item.priority ?? item.value ?? 0,
|
||||
}));
|
||||
|
||||
export const FormSpecificationComponentSchema = z
|
||||
.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
field: z.string().optional(),
|
||||
label: z.string().optional().default(""),
|
||||
type: z.string().default("text"),
|
||||
optional: z.boolean().optional().default(true),
|
||||
editable: z.boolean().optional().default(true),
|
||||
hidden: z.boolean().optional().default(false),
|
||||
isLinkageAssignment: z.boolean().optional().default(false),
|
||||
assignmentRule: z.string().nullable().optional(),
|
||||
priorityList: z.array(FormPriorityItemSchema).nullable().optional(),
|
||||
priority: z.array(FormPriorityItemSchema).nullable().optional(),
|
||||
entityId: z.string().nullable().optional(),
|
||||
referenceData: z.string().nullable().optional(),
|
||||
dimensionId: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.transform((comp) => ({
|
||||
...comp,
|
||||
name: comp.name || comp.field || comp.label || "",
|
||||
priorityList: comp.priorityList ?? comp.priority ?? [],
|
||||
entityId: comp.entityId ?? comp.referenceData ?? null,
|
||||
}));
|
||||
|
||||
export const FormSpecificationSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string().optional().default(""),
|
||||
type: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
configs: z.unknown().optional(),
|
||||
components: z.array(FormSpecificationComponentSchema).optional().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FormPriorityItem = z.infer<typeof FormPriorityItemSchema>;
|
||||
export type FormSpecificationComponent = z.infer<typeof FormSpecificationComponentSchema>;
|
||||
export type FormSpecification = z.infer<typeof FormSpecificationSchema>;
|
||||
|
||||
// ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)─────────────────────
|
||||
|
||||
export const RawBillMoneySchema = z.object({
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { z } from "zod";
|
||||
import { getEasoClient } from "../../core/http/unity-client.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { fetchStaffs } from "./api.js";
|
||||
@@ -67,45 +66,3 @@ export async function getStaffById(
|
||||
|
||||
return found || null;
|
||||
}
|
||||
|
||||
// ── MCP Tool Definitions ──────────────────────────────────────────────────────
|
||||
|
||||
export const contactTools = [
|
||||
{
|
||||
name: "contact_search",
|
||||
description: "在当前企业通讯录中模糊检索员工(支持姓名、邮箱、手机号、工号)",
|
||||
parameters: z.object({
|
||||
keyword: z.string().describe("检索关键词,如姓名、邮箱前缀、手机号或工号"),
|
||||
limit: z.number().optional().describe("最大返回条数,默认 20"),
|
||||
}),
|
||||
handler: async (corp: CorpConfig, params: { keyword: string; limit?: number }) => {
|
||||
const results = await searchStaffs(corp, params);
|
||||
return { count: results.length, staffs: results };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "contact_get",
|
||||
description: "根据员工 staffId 或工号精准获取员工详细档案",
|
||||
parameters: z.object({
|
||||
staffId: z.string().describe("员工的完整 staffId 或 ID"),
|
||||
}),
|
||||
handler: async (corp: CorpConfig, params: { staffId: string }) => {
|
||||
const staff = await getStaffById(corp, params.staffId);
|
||||
if (!staff) {
|
||||
throw new Error(`未找到员工: ${params.staffId}`);
|
||||
}
|
||||
return staff;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "contact_list",
|
||||
description: "查看企业通讯录(带默认 20 条防爆截断与总数保护)",
|
||||
parameters: z.object({
|
||||
limit: z.number().optional().describe("截断返回条数,默认 20"),
|
||||
allowFull: z.boolean().optional().describe("是否强制全量输出(大企业请谨慎使用)"),
|
||||
}),
|
||||
handler: async (corp: CorpConfig, params: { limit?: number; allowFull?: boolean }) => {
|
||||
return await listStaffsProtected(corp, params);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -30,15 +30,20 @@ hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get <应用> <业务对象> <记录ID>
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--raw] [--dry-run|--yes]
|
||||
hose-use platform record batch-edit <应用> <业务对象> [--ids=id1,id2|--filter=...] --data='{"field": "val"}' [--concurrency=8] [--dry-run|--yes]
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
|
||||
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only]
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
|
||||
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
|
||||
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
|
||||
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
|
||||
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
DatalinkEntitySchema,
|
||||
DatalinkPlatformDetailSchema,
|
||||
type DatalinkEntity,
|
||||
type DatalinkField,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkPlatformDetail,
|
||||
type DatalinkRecord,
|
||||
@@ -266,6 +267,248 @@ export async function editRecord(
|
||||
return (json.value ?? json.data ?? json) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const REFERENCE_FIELD_TYPES = new Set([
|
||||
"dimension",
|
||||
"dataLink",
|
||||
"staff",
|
||||
"department",
|
||||
"role",
|
||||
"reference",
|
||||
]);
|
||||
|
||||
const SYSTEM_RECORD_KEYS = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"active",
|
||||
"visibility",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"corporationId",
|
||||
"platformId",
|
||||
"ownerId",
|
||||
"creatorId",
|
||||
"form",
|
||||
"fieldAuth",
|
||||
"actions",
|
||||
"source",
|
||||
"sourceId",
|
||||
]);
|
||||
|
||||
function extractReferenceId(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("standard" in obj) return undefined;
|
||||
if (typeof obj.id === "string" && obj.id) return obj.id;
|
||||
if (obj.dataLink && typeof obj.dataLink === "object" && !Array.isArray(obj.dataLink)) {
|
||||
const dl = obj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
if (obj.data && typeof obj.data === "object" && !Array.isArray(obj.data)) {
|
||||
const dataObj = obj.data as Record<string, unknown>;
|
||||
if (typeof dataObj.id === "string" && dataObj.id) return dataObj.id;
|
||||
if (dataObj.dataLink && typeof dataObj.dataLink === "object" && !Array.isArray(dataObj.dataLink)) {
|
||||
const dl = dataObj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function normalizeRecordFieldValue(
|
||||
value: unknown,
|
||||
fieldDef?: DatalinkField
|
||||
): unknown {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return "";
|
||||
const isRefType = fieldDef ? REFERENCE_FIELD_TYPES.has(fieldDef.type) : false;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => {
|
||||
const refId = extractReferenceId(item);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "object" && "standard" in (value as Record<string, unknown>)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const refId = extractReferenceId(value);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function resolveEntityFieldKey(
|
||||
inputKey: string,
|
||||
entityId: string,
|
||||
fields: DatalinkField[] = [],
|
||||
existingForm: Record<string, unknown> = {}
|
||||
): { key: string; fieldDef?: DatalinkField } {
|
||||
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const exactByName = fields.find((f) => f.name === inputKey);
|
||||
if (exactByName) {
|
||||
return { key: exactByName.name, fieldDef: exactByName };
|
||||
}
|
||||
const prefixedKey = `E_${bareEntityId}_${inputKey}`;
|
||||
const byPrefixedName = fields.find((f) => f.name === prefixedKey);
|
||||
if (byPrefixedName) {
|
||||
return { key: byPrefixedName.name, fieldDef: byPrefixedName };
|
||||
}
|
||||
const byLabel = fields.find((f) => f.label === inputKey);
|
||||
if (byLabel && byLabel.name) {
|
||||
return { key: byLabel.name, fieldDef: byLabel };
|
||||
}
|
||||
if (inputKey.startsWith(`E_${bareEntityId}_`)) {
|
||||
return { key: inputKey };
|
||||
}
|
||||
if (prefixedKey in existingForm) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
if (fields.some((f) => f.name.startsWith(`E_${bareEntityId}_`)) && !(inputKey in existingForm)) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
return { key: inputKey };
|
||||
}
|
||||
|
||||
export interface SafeRecordEditOptions {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
fields?: DatalinkField[];
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建安全的业务对象记录 Read-Modify-Write 编辑 Payload:
|
||||
* 1. 自动提取并保留原记录全部 E_<entityId>_* 及已有业务字段;
|
||||
* 2. 自动将 dimension / dataLink / staff / department 等引用对象 { id: "ID01..." } 归一化为字符串 ID;
|
||||
* 3. 自动保留 active 与 visibility(将 staff/role/department 映射为 staffs/roles/departments);
|
||||
* 4. 支持按完整字段名(E_<entityId>_xxx)或简写字段显示名/后缀(我方签约主体、name、code)合并变更。
|
||||
*/
|
||||
export function buildSafeRecordEditPayload(
|
||||
options: SafeRecordEditOptions
|
||||
): DatalinkRecordEditPayload {
|
||||
const bareEntityId = options.entityId.startsWith("$")
|
||||
? options.entityId.slice(1)
|
||||
: options.entityId;
|
||||
const bareRecordId = options.recordId.startsWith("$")
|
||||
? options.recordId.slice(1)
|
||||
: options.recordId;
|
||||
const fields = options.fields ?? [];
|
||||
const detailObj = asRecord(options.detail);
|
||||
const nestedData = asRecord(detailObj.data);
|
||||
const record = asRecord(
|
||||
detailObj.dataLink ?? nestedData.dataLink ?? detailObj
|
||||
);
|
||||
|
||||
const mergedForm: Record<string, unknown> = {};
|
||||
const fieldByName = new Map<string, DatalinkField>();
|
||||
for (const f of fields) {
|
||||
if (f.name) fieldByName.set(f.name, f);
|
||||
}
|
||||
|
||||
// 1. 提取 record.form 中的字段(兼容测试与部分特殊实体结构)
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
const fDef = fieldByName.get(k);
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 提取原记录中的 E_<entityId>_* 字段与 schema 中定义的业务字段
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (SYSTEM_RECORD_KEYS.has(k)) continue;
|
||||
const fDef = fieldByName.get(k);
|
||||
if (k.startsWith(entityPrefix) || k.startsWith("E_") || fDef) {
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 合并用户传入的 patchForm(支持字段名、中文显示名或后缀简写)
|
||||
for (const [rawKey, rawVal] of Object.entries(options.patchForm)) {
|
||||
const { key, fieldDef } = resolveEntityFieldKey(
|
||||
rawKey,
|
||||
bareEntityId,
|
||||
fields,
|
||||
mergedForm
|
||||
);
|
||||
mergedForm[key] = normalizeRecordFieldValue(rawVal, fieldDef);
|
||||
}
|
||||
|
||||
// 4. 保留 active 与 visibility
|
||||
const resolvedActive =
|
||||
options.active !== undefined
|
||||
? options.active
|
||||
: typeof record.active === "boolean"
|
||||
? record.active
|
||||
: true;
|
||||
|
||||
const rawVis = asRecord(record.visibility);
|
||||
const normalizeRefIdList = (list: unknown): string[] => {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list
|
||||
.map((item) =>
|
||||
typeof item === "string"
|
||||
? item
|
||||
: item && typeof item === "object" && typeof (item as Record<string, unknown>).id === "string"
|
||||
? String((item as Record<string, unknown>).id)
|
||||
: undefined
|
||||
)
|
||||
.filter((item): item is string => Boolean(item));
|
||||
};
|
||||
|
||||
const visibility = {
|
||||
fullVisible:
|
||||
typeof rawVis.fullVisible === "boolean" ? rawVis.fullVisible : true,
|
||||
staffs: normalizeRefIdList(rawVis.staffs ?? rawVis.staff),
|
||||
roles: normalizeRefIdList(rawVis.roles ?? rawVis.role),
|
||||
departments: normalizeRefIdList(rawVis.departments ?? rawVis.department),
|
||||
departmentsIncludeChildren:
|
||||
typeof rawVis.departmentsIncludeChildren === "boolean"
|
||||
? rawVis.departmentsIncludeChildren
|
||||
: false,
|
||||
};
|
||||
|
||||
return {
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
active: resolvedActive,
|
||||
form: mergedForm,
|
||||
visibility,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全编辑单条业务对象记录(Read-Modify-Write 模式)。
|
||||
*/
|
||||
export async function safeEditRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: Omit<SafeRecordEditOptions, "detail"> & {
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
}
|
||||
): Promise<{
|
||||
payload: DatalinkRecordEditPayload;
|
||||
result: Record<string, unknown>;
|
||||
}> {
|
||||
const detail =
|
||||
options.detail ?? (await getRecordDetail(client, corpId, options.recordId));
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
...options,
|
||||
detail,
|
||||
});
|
||||
const result = await editRecord(client, corpId, payload);
|
||||
return { payload, result };
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
export async function recomputeRecordLedger(
|
||||
client: KyInstance,
|
||||
@@ -278,3 +521,4 @@ export async function recomputeRecordLedger(
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
getPlatform,
|
||||
getRecordDetail,
|
||||
@@ -9,7 +10,13 @@ import {
|
||||
searchEntityRecords,
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import { buildKeywordFilter, selectRecordFields } from "./services.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
@@ -167,5 +174,217 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
|
||||
expect(result.id).toBe("ok");
|
||||
});
|
||||
|
||||
test("buildSafeRecordEditPayload 执行 Read-Modify-Write 安全合并并归一化嵌套引用 ID 与 visibility", async () => {
|
||||
const fields = [
|
||||
{ name: "E_e1_name", label: "合同名称", type: "text" },
|
||||
{ name: "E_e1_company", label: "我方签约主体", type: "dimension" },
|
||||
{ name: "E_e1_supplier", label: "供应商", type: "supplier" },
|
||||
{ name: "E_e1_amount", label: "合同金额", type: "money" },
|
||||
];
|
||||
const detail = {
|
||||
dataLink: {
|
||||
id: "ID01VSau4VJWSH",
|
||||
active: true,
|
||||
E_e1_name: "年度采购合同",
|
||||
E_e1_company: null,
|
||||
E_e1_supplier: { id: "ID01SUP123", name: "测试供应商" },
|
||||
E_e1_amount: { standard: "1000.00", standardUnit: "元", standardScale: 2 },
|
||||
visibility: {
|
||||
fullVisible: false,
|
||||
staff: [{ id: "staff-1" }],
|
||||
role: ["role-1"],
|
||||
department: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
entityId: "e1",
|
||||
recordId: "ID01VSau4VJWSH",
|
||||
detail,
|
||||
fields: fields as any,
|
||||
patchForm: {
|
||||
我方签约主体: "ID01RnG3b79daL",
|
||||
},
|
||||
});
|
||||
|
||||
expect(payload.dataLinkEntityId).toBe("e1");
|
||||
expect(payload.dataLinkId).toBe("ID01VSau4VJWSH");
|
||||
expect(payload.active).toBe(true);
|
||||
expect(payload.form.E_e1_name).toBe("年度采购合同");
|
||||
expect(payload.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(payload.form.E_e1_supplier).toBe("ID01SUP123");
|
||||
expect(payload.form.E_e1_amount).toBe(
|
||||
JSON.stringify({
|
||||
standard: "1000.00",
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
})
|
||||
);
|
||||
expect(payload.visibility).toEqual({
|
||||
fullVisible: false,
|
||||
staffs: ["staff-1"],
|
||||
roles: ["role-1"],
|
||||
departments: [],
|
||||
departmentsIncludeChildren: false,
|
||||
});
|
||||
|
||||
let postUrl = "";
|
||||
let postBody: any = null;
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
postUrl = url;
|
||||
postBody = options.json;
|
||||
return { json: async () => ({ value: { id: "ID01VSau4VJWSH" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
await editRecord(client, "corp-1", payload);
|
||||
expect(postUrl).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(postBody.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(postBody.visibility.staffs).toEqual(["staff-1"]);
|
||||
});
|
||||
|
||||
test("fetchAllEntityRecords 自动分页拉取全量记录", async () => {
|
||||
const calls: Array<{ start: number; count: number }> = [];
|
||||
const client = {
|
||||
post: async (_url: string, options: any) => {
|
||||
const limit = options.json.query.limit;
|
||||
calls.push(limit);
|
||||
if (limit.start === 0) {
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [
|
||||
{ id: "r-1", dataLink: { id: "r-1" } },
|
||||
{ id: "r-2", dataLink: { id: "r-2" } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "r-3", dataLink: { id: "r-3" } }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await fetchAllEntityRecords(client, "corp-1", "entity-1", { pageSize: 2 });
|
||||
expect(calls).toEqual([
|
||||
{ start: 0, count: 2 },
|
||||
{ start: 2, count: 2 },
|
||||
]);
|
||||
expect(result.data).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("auditEntityRecords 巡检必填缺失、停用引用与跨台账同名字段同步差异", () => {
|
||||
const childEntity = {
|
||||
id: "e_plan",
|
||||
name: "支付计划表",
|
||||
fields: [
|
||||
{ name: "E_e_plan_code", label: "编码", type: "text", optional: true },
|
||||
{ name: "E_e_plan_company", label: "我方签约主体", type: "dimension", optional: false },
|
||||
{
|
||||
name: "E_e_plan_contract",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: true,
|
||||
entityId: "e_contract",
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{
|
||||
id: "plan-1",
|
||||
dataLink: {
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
active: true,
|
||||
E_e_plan_company: null,
|
||||
E_e_plan_contract: {
|
||||
id: "contract-1",
|
||||
name: "测试合同",
|
||||
active: false,
|
||||
data: {
|
||||
dataLink: {
|
||||
id: "contract-1",
|
||||
code: "HT-001",
|
||||
active: false,
|
||||
E_e_contract_company: {
|
||||
id: "ID01RnG3b79daL",
|
||||
name: "北京转转精神科技有限责任公司",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const report = auditEntityRecords(records as any, childEntity as any, {
|
||||
checkFields: ["我方签约主体"],
|
||||
});
|
||||
|
||||
expect(report.totalRecords).toBe(1);
|
||||
expect(report.summary.missingFieldCount).toBe(1);
|
||||
expect(report.summary.disabledReferenceCount).toBe(1);
|
||||
expect(report.summary.crossLedgerMissingSyncCount).toBe(1);
|
||||
expect(report.suggestedPatches).toEqual([
|
||||
{
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
form: {
|
||||
E_e_plan_company: "ID01RnG3b79daL",
|
||||
},
|
||||
reason: "我方签约主体 <- 北京转转精神科技有限责任公司 (ID01RnG3b79daL)",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("batchSafeEditRecords 支持 dryRun 预览与并发安全合并", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
name: "合同流程",
|
||||
fields: [{ name: "E_e1_company", label: "我方签约主体", type: "dimension" }],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({
|
||||
value: {
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
active: true,
|
||||
E_e1_company: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const results = await batchSafeEditRecords(
|
||||
client,
|
||||
"corp-1",
|
||||
entity as any,
|
||||
[{ recordId: "r-1", patchForm: { 我方签约主体: "ID01RnG3b79daL" } }],
|
||||
{ dryRun: true }
|
||||
);
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0]?.status).toBe("preview");
|
||||
expect(results[0]?.payload?.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,71 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
|
||||
import type {
|
||||
DatalinkEntity,
|
||||
DatalinkField,
|
||||
DatalinkPlatformDetail,
|
||||
DatalinkRecord,
|
||||
DatalinkRecordEditPayload,
|
||||
DatalinkRecordPage,
|
||||
} from "./types.js";
|
||||
|
||||
export type { SafeRecordEditOptions } from "./api.js";
|
||||
|
||||
export function listPlatforms(...args: Parameters<typeof api.listPlatforms>) {
|
||||
return api.listPlatforms(...args);
|
||||
}
|
||||
|
||||
export function listAllPlatforms(...args: Parameters<typeof api.listAllPlatforms>) {
|
||||
return api.listAllPlatforms(...args);
|
||||
}
|
||||
|
||||
export function getPlatform(...args: Parameters<typeof api.getPlatform>) {
|
||||
return api.getPlatform(...args);
|
||||
}
|
||||
|
||||
export function listPlatformEntities(...args: Parameters<typeof api.listPlatformEntities>) {
|
||||
return api.listPlatformEntities(...args);
|
||||
}
|
||||
|
||||
export function searchEntityRecords(...args: Parameters<typeof api.searchEntityRecords>) {
|
||||
return api.searchEntityRecords(...args);
|
||||
}
|
||||
|
||||
export function listImportJobs(...args: Parameters<typeof api.listImportJobs>) {
|
||||
return api.listImportJobs(...args);
|
||||
}
|
||||
|
||||
export function getImportResult(...args: Parameters<typeof api.getImportResult>) {
|
||||
return api.getImportResult(...args);
|
||||
}
|
||||
|
||||
export function toggleRecordState(...args: Parameters<typeof api.toggleRecordState>) {
|
||||
return api.toggleRecordState(...args);
|
||||
}
|
||||
|
||||
export function getRecordDetail(...args: Parameters<typeof api.getRecordDetail>) {
|
||||
return api.getRecordDetail(...args);
|
||||
}
|
||||
|
||||
export function getRecordFormSchema(...args: Parameters<typeof api.getRecordFormSchema>) {
|
||||
return api.getRecordFormSchema(...args);
|
||||
}
|
||||
|
||||
export function editRecord(...args: Parameters<typeof api.editRecord>) {
|
||||
return api.editRecord(...args);
|
||||
}
|
||||
|
||||
export function buildSafeRecordEditPayload(...args: Parameters<typeof api.buildSafeRecordEditPayload>) {
|
||||
return api.buildSafeRecordEditPayload(...args);
|
||||
}
|
||||
|
||||
export function safeEditRecord(...args: Parameters<typeof api.safeEditRecord>) {
|
||||
return api.safeEditRecord(...args);
|
||||
}
|
||||
|
||||
export function recomputeRecordLedger(...args: Parameters<typeof api.recomputeRecordLedger>) {
|
||||
return api.recomputeRecordLedger(...args);
|
||||
}
|
||||
|
||||
function matches(value: unknown, target: string): boolean {
|
||||
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
||||
@@ -35,14 +100,21 @@ export function buildKeywordFilter(keyword: string): string {
|
||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
||||
}
|
||||
|
||||
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
|
||||
export function selectRecordFields(
|
||||
record: Record<string, unknown>,
|
||||
fields: string[],
|
||||
definitions: DatalinkField[] = []
|
||||
): Record<string, unknown> {
|
||||
if (fields.length === 0) return record;
|
||||
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const dataLink =
|
||||
record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find((field) => field.name === selector || field.label === selector);
|
||||
const definition = definitions.find(
|
||||
(field) => field.name === selector || field.label === selector
|
||||
);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
}
|
||||
@@ -50,3 +122,493 @@ export function selectRecordFields(record: Record<string, unknown>, fields: stri
|
||||
? { ...record, dataLink: selected }
|
||||
: selected;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。
|
||||
*/
|
||||
export async function fetchAllEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000));
|
||||
let start = 0;
|
||||
let total = 0;
|
||||
const allData: DatalinkRecord[] = [];
|
||||
let firstPage: DatalinkRecordPage | undefined;
|
||||
|
||||
while (true) {
|
||||
const page = await api.searchEntityRecords(client, corpId, entityId, {
|
||||
start,
|
||||
count: pageSize,
|
||||
filterBy: options.filterBy,
|
||||
orderBy: options.orderBy,
|
||||
});
|
||||
firstPage ??= page;
|
||||
total = page.total;
|
||||
if (page.data.length === 0) break;
|
||||
allData.push(...page.data);
|
||||
start += page.data.length;
|
||||
if (allData.length >= total || page.data.length < pageSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
total: Math.max(total, allData.length),
|
||||
data: allData,
|
||||
actions: firstPage?.actions ?? [],
|
||||
components: firstPage?.components ?? [],
|
||||
path: firstPage?.path,
|
||||
template: firstPage?.template,
|
||||
};
|
||||
}
|
||||
|
||||
export interface DatalinkAuditIssue {
|
||||
recordId: string;
|
||||
recordCode: string;
|
||||
recordName: string;
|
||||
active: boolean;
|
||||
type:
|
||||
| "MISSING_FIELD"
|
||||
| "DISABLED_REFERENCE"
|
||||
| "CROSS_LEDGER_MISSING_SYNC"
|
||||
| "CROSS_LEDGER_MISMATCH";
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
message: string;
|
||||
linkedField?: string;
|
||||
linkedFieldLabel?: string;
|
||||
linkedRecordId?: string;
|
||||
actualId?: string;
|
||||
actualName?: string;
|
||||
expectedId?: string;
|
||||
expectedName?: string;
|
||||
}
|
||||
|
||||
export interface DatalinkAuditReport {
|
||||
entityId: string;
|
||||
entityName: string;
|
||||
totalRecords: number;
|
||||
auditedRecords: number;
|
||||
healthyRecords: number;
|
||||
affectedRecordCount: number;
|
||||
issueCount: number;
|
||||
summary: {
|
||||
missingFieldCount: number;
|
||||
disabledReferenceCount: number;
|
||||
crossLedgerMissingSyncCount: number;
|
||||
crossLedgerMismatchCount: number;
|
||||
};
|
||||
issues: DatalinkAuditIssue[];
|
||||
suggestedPatches: Array<{
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
form: Record<string, string>;
|
||||
reason: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function isEmptyFieldValue(value: unknown): boolean {
|
||||
if (value === undefined || value === null || value === "") return true;
|
||||
if (Array.isArray(value)) return value.length === 0;
|
||||
if (typeof value === "object") {
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("id" in obj) {
|
||||
return obj.id === undefined || obj.id === null || obj.id === "";
|
||||
}
|
||||
if ("standard" in obj) {
|
||||
return obj.standard === undefined || obj.standard === null || obj.standard === "";
|
||||
}
|
||||
return Object.keys(obj).length === 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractRefIdAndName(value: unknown): {
|
||||
id?: string;
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
} {
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return { id: value.trim() };
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return {};
|
||||
}
|
||||
const obj = value as Record<string, unknown>;
|
||||
const nestedData =
|
||||
obj.data && typeof obj.data === "object"
|
||||
? (obj.data as Record<string, unknown>)
|
||||
: undefined;
|
||||
const nestedDl =
|
||||
nestedData?.dataLink && typeof nestedData.dataLink === "object"
|
||||
? (nestedData.dataLink as Record<string, unknown>)
|
||||
: obj.dataLink && typeof obj.dataLink === "object"
|
||||
? (obj.dataLink as Record<string, unknown>)
|
||||
: undefined;
|
||||
const id =
|
||||
typeof obj.id === "string" && obj.id.trim()
|
||||
? obj.id.trim()
|
||||
: typeof nestedDl?.id === "string" && nestedDl.id.trim()
|
||||
? nestedDl.id.trim()
|
||||
: undefined;
|
||||
const name =
|
||||
typeof obj.name === "string" && obj.name.trim()
|
||||
? obj.name.trim()
|
||||
: typeof nestedDl?.name === "string" && nestedDl.name.trim()
|
||||
? nestedDl.name.trim()
|
||||
: undefined;
|
||||
const active =
|
||||
typeof obj.active === "boolean"
|
||||
? obj.active
|
||||
: typeof nestedDl?.active === "boolean"
|
||||
? nestedDl.active
|
||||
: undefined;
|
||||
return { id, name, active };
|
||||
}
|
||||
|
||||
/**
|
||||
* 对业务对象记录集合执行数据健康度体检:
|
||||
* 1. 必填/关键字段缺失检查 (MISSING_FIELD)
|
||||
* 2. 关联对象/档案停用检查 (DISABLED_REFERENCE)
|
||||
* 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH)
|
||||
*/
|
||||
export function auditEntityRecords(
|
||||
records: DatalinkRecord[],
|
||||
entity: DatalinkEntity,
|
||||
options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {}
|
||||
): DatalinkAuditReport {
|
||||
const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id;
|
||||
const nameField = entity.fields.find(
|
||||
(f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name")
|
||||
);
|
||||
const codeField = entity.fields.find(
|
||||
(f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code")
|
||||
);
|
||||
|
||||
// 解析需要检查缺失的字段集合
|
||||
const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean);
|
||||
const fieldsToCheck: DatalinkField[] =
|
||||
explicitSelectors.length > 0
|
||||
? explicitSelectors.map((selector) => {
|
||||
const found = entity.fields.find(
|
||||
(f) =>
|
||||
f.name === selector ||
|
||||
f.label === selector ||
|
||||
f.name === `E_${bareEntityId}_${selector}`
|
||||
);
|
||||
return (
|
||||
found ?? {
|
||||
name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`,
|
||||
label: selector,
|
||||
type: "text",
|
||||
}
|
||||
);
|
||||
})
|
||||
: entity.fields.filter(
|
||||
(f) =>
|
||||
f.optional === false ||
|
||||
f.type === "dimension" ||
|
||||
f.type === "dataLink"
|
||||
);
|
||||
|
||||
const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink");
|
||||
const dimensionFields = entity.fields.filter((f) => f.type === "dimension");
|
||||
|
||||
const issues: DatalinkAuditIssue[] = [];
|
||||
const suggestedPatchesMap = new Map<
|
||||
string,
|
||||
{ id: string; code: string; name: string; form: Record<string, string>; reasons: string[] }
|
||||
>();
|
||||
const affectedRecordIds = new Set<string>();
|
||||
let auditedRecords = 0;
|
||||
|
||||
let missingFieldCount = 0;
|
||||
let disabledReferenceCount = 0;
|
||||
let crossLedgerMissingSyncCount = 0;
|
||||
let crossLedgerMismatchCount = 0;
|
||||
|
||||
for (const rawRecord of records) {
|
||||
const dl =
|
||||
rawRecord.dataLink &&
|
||||
typeof rawRecord.dataLink === "object" &&
|
||||
!Array.isArray(rawRecord.dataLink)
|
||||
? (rawRecord.dataLink as Record<string, unknown>)
|
||||
: (rawRecord as Record<string, unknown>);
|
||||
const recordId = String(dl.id ?? rawRecord.id ?? "");
|
||||
const active = (dl.active ?? rawRecord.active) !== false;
|
||||
if (options.activeOnly && !active) continue;
|
||||
|
||||
auditedRecords++;
|
||||
const recordName = String(
|
||||
dl.name ??
|
||||
dl["名称"] ??
|
||||
(nameField ? dl[nameField.name] : undefined) ??
|
||||
dl[`E_${bareEntityId}_name`] ??
|
||||
""
|
||||
);
|
||||
const recordCode = String(
|
||||
dl.code ??
|
||||
dl["编码"] ??
|
||||
(codeField ? dl[codeField.name] : undefined) ??
|
||||
dl[`E_${bareEntityId}_code`] ??
|
||||
""
|
||||
);
|
||||
|
||||
const getFieldVal = (field: DatalinkField): unknown =>
|
||||
dl[field.name] ??
|
||||
dl[`E_${bareEntityId}_${field.name}`] ??
|
||||
(dl.form && typeof dl.form === "object"
|
||||
? (dl.form as Record<string, unknown>)[field.name]
|
||||
: undefined) ??
|
||||
dl[field.label];
|
||||
|
||||
// 1. 必填/关键字段缺失检查
|
||||
for (const field of fieldsToCheck) {
|
||||
const val = getFieldVal(field);
|
||||
if (isEmptyFieldValue(val)) {
|
||||
missingFieldCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "MISSING_FIELD",
|
||||
field: field.name,
|
||||
fieldLabel: field.label || field.name,
|
||||
message: `字段 [${field.label || field.name}] (${field.name}) 为空`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 关联对象/档案停用检查
|
||||
for (const field of entity.fields) {
|
||||
if (field.type !== "dimension" && field.type !== "dataLink") continue;
|
||||
const val = getFieldVal(field);
|
||||
const items = Array.isArray(val) ? val : val ? [val] : [];
|
||||
for (const item of items) {
|
||||
const refInfo = extractRefIdAndName(item);
|
||||
if (refInfo.active === false) {
|
||||
disabledReferenceCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "DISABLED_REFERENCE",
|
||||
field: field.name,
|
||||
fieldLabel: field.label || field.name,
|
||||
actualId: refInfo.id,
|
||||
actualName: refInfo.name,
|
||||
message: `字段 [${field.label || field.name}] 引用的${
|
||||
field.type === "dataLink" ? "业务对象记录" : "维度档案"
|
||||
} [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 跨表关联同名维度一致性检查
|
||||
for (const linkField of dataLinkFields) {
|
||||
const linkVal = getFieldVal(linkField);
|
||||
if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue;
|
||||
const linkObj = linkVal as Record<string, unknown>;
|
||||
const parentDl =
|
||||
linkObj.data &&
|
||||
typeof linkObj.data === "object" &&
|
||||
(linkObj.data as Record<string, unknown>).dataLink &&
|
||||
typeof (linkObj.data as Record<string, unknown>).dataLink === "object"
|
||||
? ((linkObj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: linkObj.dataLink && typeof linkObj.dataLink === "object"
|
||||
? (linkObj.dataLink as Record<string, unknown>)
|
||||
: linkObj;
|
||||
const linkedRecordId = String(parentDl.id ?? linkObj.id ?? "");
|
||||
|
||||
for (const dimField of dimensionFields) {
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
const suffix = dimField.name.startsWith(entityPrefix)
|
||||
? dimField.name.slice(entityPrefix.length)
|
||||
: dimField.name.replace(/^E_[^_]+_/, "");
|
||||
const parentKey = Object.keys(parentDl).find(
|
||||
(k) =>
|
||||
k === dimField.label ||
|
||||
k === suffix ||
|
||||
k.endsWith(`_${suffix}`) ||
|
||||
(Boolean(dimField.label) && k.endsWith(`_${dimField.label}`))
|
||||
);
|
||||
if (!parentKey) continue;
|
||||
|
||||
const parentRef = extractRefIdAndName(parentDl[parentKey]);
|
||||
if (!parentRef.id) continue;
|
||||
|
||||
const childRef = extractRefIdAndName(getFieldVal(dimField));
|
||||
if (!childRef.id) {
|
||||
crossLedgerMissingSyncCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${
|
||||
linkField.label || linkField.name
|
||||
}] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${
|
||||
parentRef.id
|
||||
}),建议回填修复`;
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "CROSS_LEDGER_MISSING_SYNC",
|
||||
field: dimField.name,
|
||||
fieldLabel: dimField.label || dimField.name,
|
||||
linkedField: linkField.name,
|
||||
linkedFieldLabel: linkField.label || linkField.name,
|
||||
linkedRecordId,
|
||||
expectedId: parentRef.id,
|
||||
expectedName: parentRef.name,
|
||||
message: reason,
|
||||
});
|
||||
|
||||
const existingPatch = suggestedPatchesMap.get(recordId) ?? {
|
||||
id: recordId,
|
||||
code: recordCode,
|
||||
name: recordName,
|
||||
form: {},
|
||||
reasons: [],
|
||||
};
|
||||
existingPatch.form[dimField.name] = parentRef.id;
|
||||
existingPatch.reasons.push(
|
||||
`${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})`
|
||||
);
|
||||
suggestedPatchesMap.set(recordId, existingPatch);
|
||||
} else if (childRef.id !== parentRef.id) {
|
||||
crossLedgerMismatchCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "CROSS_LEDGER_MISMATCH",
|
||||
field: dimField.name,
|
||||
fieldLabel: dimField.label || dimField.name,
|
||||
linkedField: linkField.name,
|
||||
linkedFieldLabel: linkField.label || linkField.name,
|
||||
linkedRecordId,
|
||||
actualId: childRef.id,
|
||||
actualName: childRef.name,
|
||||
expectedId: parentRef.id,
|
||||
expectedName: parentRef.name,
|
||||
message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${
|
||||
childRef.name || childRef.id
|
||||
}] (${childRef.id}) 与关联 [${
|
||||
linkField.label || linkField.name
|
||||
}] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${
|
||||
parentRef.id
|
||||
}) 不一致`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({
|
||||
id: item.id,
|
||||
code: item.code,
|
||||
name: item.name,
|
||||
form: item.form,
|
||||
reason: item.reasons.join("; "),
|
||||
}));
|
||||
|
||||
return {
|
||||
entityId: entity.id,
|
||||
entityName: entity.name,
|
||||
totalRecords: options.total ?? records.length,
|
||||
auditedRecords,
|
||||
healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size),
|
||||
affectedRecordCount: affectedRecordIds.size,
|
||||
issueCount: issues.length,
|
||||
summary: {
|
||||
missingFieldCount,
|
||||
disabledReferenceCount,
|
||||
crossLedgerMissingSyncCount,
|
||||
crossLedgerMismatchCount,
|
||||
},
|
||||
issues,
|
||||
suggestedPatches,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BatchEditTargetItem {
|
||||
recordId: string;
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
export interface BatchEditItemResult {
|
||||
recordId: string;
|
||||
status: "preview" | "updated" | "failed";
|
||||
payload?: DatalinkRecordEditPayload;
|
||||
result?: Record<string, unknown>;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function batchSafeEditRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entity: DatalinkEntity,
|
||||
targets: BatchEditTargetItem[],
|
||||
options: { concurrency?: number; dryRun?: boolean } = {}
|
||||
): Promise<BatchEditItemResult[]> {
|
||||
const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32));
|
||||
const results: BatchEditItemResult[] = new Array(targets.length);
|
||||
let cursor = 0;
|
||||
|
||||
const worker = async () => {
|
||||
while (true) {
|
||||
const idx = cursor++;
|
||||
if (idx >= targets.length) break;
|
||||
const target = targets[idx];
|
||||
try {
|
||||
const detail = await api.getRecordDetail(client, corpId, target.recordId);
|
||||
const payload = api.buildSafeRecordEditPayload({
|
||||
entityId: entity.id,
|
||||
recordId: target.recordId,
|
||||
detail,
|
||||
fields: entity.fields,
|
||||
patchForm: target.patchForm,
|
||||
active: target.active,
|
||||
});
|
||||
if (options.dryRun) {
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "preview",
|
||||
payload,
|
||||
};
|
||||
} else {
|
||||
const res = await api.editRecord(client, corpId, payload);
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "updated",
|
||||
payload,
|
||||
result: res,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(concurrency, targets.length) }, () => worker())
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import * as api from "./api.js";
|
||||
|
||||
const clientSchema = z.object({
|
||||
corp: z.object({ credentials: z.object({ corpId: z.string() }) }).passthrough(),
|
||||
ekbClient: z.any(),
|
||||
});
|
||||
|
||||
export const datalinkTools = [
|
||||
{
|
||||
name: "datalink_platform_list",
|
||||
description: "列出当前企业账号可见的启用自建应用(可传入 all=true 查看包含模板平台的完整列表)",
|
||||
parameters: z.object({
|
||||
all: z.boolean().optional().describe("是否拉取包含 HAB 模板与全量平台列表"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { all?: boolean } = {}) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const platforms = params.all
|
||||
? await api.listAllPlatforms(ekbClient, corp.credentials.corpId)
|
||||
: await api.listPlatforms(ekbClient, corp.credentials.corpId);
|
||||
return { platforms };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_platform_get",
|
||||
description: "获取自建应用详情以及应用管理员、人员、角色和部门可见权限",
|
||||
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
|
||||
handler: async (clients: unknown, params: { platformId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.getPlatform(ekbClient, corp.credentials.corpId, params.platformId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_entity_list",
|
||||
description: "获取一个自建应用下的业务对象目录、字段、操作和可见性配置",
|
||||
parameters: z.object({ platformId: z.string().describe("自建应用 ID") }),
|
||||
handler: async (clients: unknown, params: { platformId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return { entities: await api.listPlatformEntities(ekbClient, corp.credentials.corpId, params.platformId) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_search",
|
||||
description: "分页检索业务对象记录,支持 DataLink filterBy 表达式",
|
||||
parameters: z.object({
|
||||
entityId: z.string().describe("业务对象 ID"),
|
||||
start: z.number().int().min(0).optional(),
|
||||
count: z.number().int().min(1).max(1000).optional(),
|
||||
filterBy: z.string().optional().describe("DataLink 原生过滤表达式"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { entityId: string; start?: number; count?: number; filterBy?: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.searchEntityRecords(ekbClient, corp.credentials.corpId, params.entityId, params);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_import_jobs",
|
||||
description: "查看业务对象的导入任务和最近导入结果",
|
||||
parameters: z.object({ entityId: z.string().describe("业务对象 ID") }),
|
||||
handler: async (clients: unknown, params: { entityId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const [jobs, result] = await Promise.all([
|
||||
api.listImportJobs(ekbClient, corp.credentials.corpId, params.entityId),
|
||||
api.getImportResult(ekbClient, corp.credentials.corpId, params.entityId),
|
||||
]);
|
||||
return { jobs, latestResult: result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_get",
|
||||
description: "获取单条业务对象记录的完整详情(模板、字段值、可见性及历史等)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.getRecordDetail(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_toggle",
|
||||
description: "切换业务对象记录的停启用状态 (active: true <-> false)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
state: z.boolean().optional().describe("目标状态 (true 为启用,false 为停用,不传则自动翻转)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string; state?: boolean }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
const result = await api.toggleRecordState(ekbClient, corp.credentials.corpId, params.recordId, params.state);
|
||||
return { success: true, ...result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_edit",
|
||||
description: "编辑更新业务对象记录的字段值",
|
||||
parameters: z.object({
|
||||
entityId: z.string().describe("业务对象 ID"),
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
form: z.record(z.string(), z.unknown()).describe("待更新的表单字段键值对"),
|
||||
active: z.boolean().optional().describe("停启用状态"),
|
||||
visibility: z.record(z.string(), z.unknown()).optional().describe("可见性配置"),
|
||||
}),
|
||||
handler: async (
|
||||
clients: unknown,
|
||||
params: {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
form: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
visibility?: Record<string, unknown>;
|
||||
}
|
||||
) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.editRecord(ekbClient, corp.credentials.corpId, {
|
||||
dataLinkEntityId: params.entityId,
|
||||
dataLinkId: params.recordId,
|
||||
form: params.form,
|
||||
active: params.active,
|
||||
visibility: params.visibility,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "datalink_record_recompute",
|
||||
description: "重新计算指定业务对象记录下的全部台账信息",
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("业务对象记录 ID (dataLinkId)"),
|
||||
}),
|
||||
handler: async (clients: unknown, params: { recordId: string }) => {
|
||||
const { corp, ekbClient } = clientSchema.parse(clients);
|
||||
return api.recomputeRecordLedger(ekbClient, corp.credentials.corpId, params.recordId);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export type DatalinkTool = (typeof datalinkTools)[number];
|
||||
@@ -1,4 +1,3 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import { listDimensionCatalogs, listDimensionItems } from "./api.js";
|
||||
@@ -53,21 +52,3 @@ export async function resolveDimension(
|
||||
if (!dimension) return undefined;
|
||||
return { dimension, items: await getDimensionItems(client, corpId, dimension) };
|
||||
}
|
||||
|
||||
export const dimensionTools = [
|
||||
{
|
||||
name: "dimension_list",
|
||||
description: "列出企业档案管理中的系统/自定义档案维度目录",
|
||||
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
|
||||
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const items = await searchDimensions(
|
||||
await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp)),
|
||||
corp.corpId || corp.id,
|
||||
{ name: params.keyword }
|
||||
);
|
||||
return { count: items.length, dimensions: items.slice(0, params.count ?? 100) };
|
||||
},
|
||||
},
|
||||
];
|
||||
+90
-15
@@ -1,27 +1,102 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { getDatabase } from "../../core/db/index.js";
|
||||
import type { EventRecord } from "./types.js";
|
||||
|
||||
interface PersistedEvents { version: 1; events: Record<string, number>; }
|
||||
interface PersistedEvents {
|
||||
version: 1;
|
||||
events: Record<string, number>;
|
||||
}
|
||||
|
||||
const MAX_EVENTS = 2000;
|
||||
|
||||
export class EventStore {
|
||||
constructor(private readonly filePath: string) {}
|
||||
private read(): PersistedEvents {
|
||||
if (!existsSync(this.filePath)) return { version: 1, events: {} };
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedEvents>;
|
||||
return { version: 1, events: parsed.events && typeof parsed.events === "object" ? parsed.events : {} };
|
||||
} catch { return { version: 1, events: {} }; }
|
||||
private readonly scopeKey: string;
|
||||
private readonly jsonPath?: string;
|
||||
private readonly customDb?: Database;
|
||||
|
||||
constructor(scopeOrFilePath = "default", db?: Database) {
|
||||
this.scopeKey = scopeOrFilePath;
|
||||
this.customDb = db;
|
||||
if (scopeOrFilePath.endsWith(".json")) {
|
||||
this.jsonPath = scopeOrFilePath;
|
||||
}
|
||||
}
|
||||
has(id: string): boolean { return Object.prototype.hasOwnProperty.call(this.read().events, id); }
|
||||
|
||||
private get db(): Database {
|
||||
return this.customDb ?? getDatabase();
|
||||
}
|
||||
|
||||
private readJson(): PersistedEvents {
|
||||
if (!this.jsonPath || !existsSync(this.jsonPath)) {
|
||||
return { version: 1, events: {} };
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.jsonPath, "utf8")) as Partial<PersistedEvents>;
|
||||
return {
|
||||
version: 1,
|
||||
events: parsed.events && typeof parsed.events === "object" ? parsed.events : {},
|
||||
};
|
||||
} catch {
|
||||
return { version: 1, events: {} };
|
||||
}
|
||||
}
|
||||
|
||||
has(id: string): boolean {
|
||||
if (this.jsonPath && existsSync(this.jsonPath)) {
|
||||
if (Object.prototype.hasOwnProperty.call(this.readJson().events, id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const row = this.db
|
||||
.query("SELECT 1 FROM observed_events WHERE scope_key = ? AND id = ? LIMIT 1")
|
||||
.get(this.scopeKey, id);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
commit(records: EventRecord[]): void {
|
||||
if (!records.length) return;
|
||||
const data = this.read();
|
||||
const merged = { ...data.events };
|
||||
for (const record of records) merged[record.id] = record.observedAt;
|
||||
const entries = Object.entries(merged).sort((a, b) => a[1] - b[1]).slice(-MAX_EVENTS);
|
||||
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`, { mode: 0o600 });
|
||||
|
||||
const db = this.db;
|
||||
const upsert = db.prepare(`
|
||||
INSERT INTO observed_events (scope_key, id, corp_id, kind, observed_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(scope_key, id) DO UPDATE SET observed_at = excluded.observed_at
|
||||
`);
|
||||
|
||||
const tx = db.transaction((items: EventRecord[]) => {
|
||||
for (const record of items) {
|
||||
upsert.run(this.scopeKey, record.id, record.corpId, record.kind, record.observedAt);
|
||||
}
|
||||
db.run(
|
||||
`
|
||||
DELETE FROM observed_events
|
||||
WHERE scope_key = ? AND id NOT IN (
|
||||
SELECT id FROM observed_events
|
||||
WHERE scope_key = ?
|
||||
ORDER BY observed_at DESC
|
||||
LIMIT ?
|
||||
)
|
||||
`,
|
||||
[this.scopeKey, this.scopeKey, MAX_EVENTS]
|
||||
);
|
||||
});
|
||||
tx(records);
|
||||
|
||||
if (this.jsonPath) {
|
||||
const data = this.readJson();
|
||||
const merged = { ...data.events };
|
||||
for (const record of records) merged[record.id] = record.observedAt;
|
||||
const entries = Object.entries(merged)
|
||||
.sort((a, b) => a[1] - b[1])
|
||||
.slice(-MAX_EVENTS);
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
FeeTypeComponent,
|
||||
FeeTypeCreateInput,
|
||||
@@ -447,102 +446,3 @@ export async function getFeeTypeFieldsList(
|
||||
requisitionFields: (detail.specifications?.requisitionComponents ?? []).map(mapComponent),
|
||||
};
|
||||
}
|
||||
|
||||
// ── MCP Tool Definitions ─────────────────────────────────────────────────────
|
||||
|
||||
export const feetypeTools = [
|
||||
{
|
||||
name: "feetype_list",
|
||||
description: "查询企业费用类型树或平铺列表 (可按关键词筛选、包含已停用)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
keyword: z.string().optional().describe("搜索关键词 (名称/编码/全路径)"),
|
||||
all: z.boolean().optional().default(false).describe("是否包含已停用的费用类型"),
|
||||
flat: z.boolean().optional().default(false).describe("是否以平铺列表格式返回"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return listFeeTypes(client, args.corpId, {
|
||||
keyword: args.keyword,
|
||||
all: args.all,
|
||||
flat: args.flat,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_get",
|
||||
description: "获取单个费用类型的详细配置与字段规格",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
includeSpecs: z.boolean().optional().default(false).describe("是否包含报账与申请字段规格定义"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return getFeeTypeDetail(client, args.corpId, args.target, {
|
||||
includeSpecs: args.includeSpecs,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_create",
|
||||
description: "新建费用类型 (支持指定父级节点、编码自增与继承字段规则)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
name: z.string().describe("费用类型名称"),
|
||||
code: z.string().optional().describe("费用编码 (不提供则系统自增生成)"),
|
||||
parentId: z.string().optional().describe("父级费用类型 ID、编码或名称 (不提供则建为顶级)"),
|
||||
enName: z.string().optional().describe("英文名称"),
|
||||
description: z.string().optional().describe("描述信息"),
|
||||
color: z.string().optional().describe("标识颜色 (如 #90caf9)"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return createFeeType(client, args.corpId, args);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_update",
|
||||
description: "修改费用类型属性 (名称、编码、英文名、颜色、图标或描述)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
name: z.string().optional().describe("新名称"),
|
||||
code: z.string().optional().describe("新编码"),
|
||||
enName: z.string().optional().describe("新英文名"),
|
||||
description: z.string().optional().describe("新描述"),
|
||||
color: z.string().optional().describe("新颜色"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return updateFeeTypeInfo(client, args.corpId, args.target, args);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_toggle",
|
||||
description: "停用或启用费用类型",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("费用类型 ID、编码或名称"),
|
||||
action: z.enum(["disable", "enable"]).describe("执行动作: disable 停用, enable 启用"),
|
||||
recursive: z.boolean().optional().default(true).describe("启用时是否递归启用子节点"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
if (args.action === "disable") {
|
||||
return disableFeeTypeItem(client, args.corpId, args.target);
|
||||
} else {
|
||||
return enableFeeTypeItem(client, args.corpId, args.target, {
|
||||
recursive: args.recursive,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "feetype_move",
|
||||
description: "移动费用类型至新的父级节点 (传入 root 移至根目录)",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
target: z.string().describe("待移动的费用类型 ID、编码或名称"),
|
||||
parent: z.string().describe("目标父级费用类型 ID、编码或名称 (传入 'root' 为移至顶级)"),
|
||||
}),
|
||||
handler: async (client: KyInstance, args: any) => {
|
||||
return moveFeeTypeItem(client, args.corpId, args.target, args.parent);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1,16 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { getRolePermissions } from "./api.js";
|
||||
|
||||
export async function getPermissions(client: KyInstance, corpId: string) { return getRolePermissions(client, corpId); }
|
||||
|
||||
export const permissionTools = [{
|
||||
name: "permission_role_get",
|
||||
description: "读取当前企业角色模型的权限开关(只读)",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: any) => {
|
||||
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const client = await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp));
|
||||
return getPermissions(client, corp.corpId || corp.id);
|
||||
},
|
||||
}];
|
||||
export async function getPermissions(client: KyInstance, corpId: string) {
|
||||
return getRolePermissions(client, corpId);
|
||||
}
|
||||
@@ -6,9 +6,20 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
|
||||
|
||||
```text
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义
|
||||
├── api.ts # HTTP 传输层
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]
|
||||
```
|
||||
|
||||
## 详细文档
|
||||
|
||||
@@ -13,8 +13,102 @@ describe("Workflow static analysis", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
|
||||
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
|
||||
});
|
||||
it("reports empty scripts and branches", () => {
|
||||
it("reports empty scripts, branches, and disabled workflow state", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["WORKFLOW_DISABLED", "EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
});
|
||||
|
||||
it("detects UNSAFE_SKIP_WITHOUT_STATUS_GUARD and LINKAGE_PRIORITY_OVERRIDE", () => {
|
||||
const wf = {
|
||||
id: "886351399301758976",
|
||||
label: "【生产】每30分钟创建采购申请单",
|
||||
state: 1,
|
||||
version: "10",
|
||||
tasks: [
|
||||
{
|
||||
name: "every_0",
|
||||
type: "every",
|
||||
label: "循环每条支付计划",
|
||||
groupName: "control",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
tasks: [
|
||||
{
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
type: "flow-create-task",
|
||||
label: "创建预付申请单",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 0],
|
||||
status: "",
|
||||
onError: { defaultAction: "SKIP" },
|
||||
inputs: {
|
||||
specificationId: "ID01TxgE3fhD6n",
|
||||
form: {
|
||||
u_关联合同流程: "{{every_0.item.E_contract}}",
|
||||
u_我方签约主体: "{{every_0.item.E_company}}",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ekuaibao_datalink_edit_0",
|
||||
type: "ekuaibao-datalink-edit",
|
||||
label: "更新支付计划状态为创建成功",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0, 1],
|
||||
status: "",
|
||||
inputs: {
|
||||
dataLinkId: "{{every_0.item.id}}",
|
||||
form: {
|
||||
状态: "创建成功",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const specifications = {
|
||||
ID01TxgE3fhD6n: {
|
||||
id: "ID01TxgE3fhD6n",
|
||||
name: "预付申请单",
|
||||
form: [
|
||||
{
|
||||
id: "f1",
|
||||
name: "u_关联合同流程",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: false,
|
||||
entityId: "e23d0d5451b1ccabfd7a",
|
||||
assignmentRule: "ID01TRWvYFAulh",
|
||||
isLinkageAssignment: false,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "f2",
|
||||
name: "u_我方签约主体",
|
||||
label: "我方签约主体",
|
||||
type: "dimension",
|
||||
optional: false,
|
||||
isLinkageAssignment: true,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any, { specifications: specifications as any });
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,400 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode { type: string; name: string; label: string; path: string; orderIndex: number; levelIndex: number[]; children: WorkflowAstNode[]; }
|
||||
export interface WorkflowDependency { path: string; taskType: string; references: string[]; }
|
||||
export interface WorkflowDiagnostic { severity: "warning" | "error"; code: string; path: string; message: string; }
|
||||
export interface WorkflowAnalysis { workflow: { id: string; label: string; state: number; version: string }; ast: WorkflowAstNode[]; dependencies: WorkflowDependency[]; diagnostics: WorkflowDiagnostic[]; }
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
"crontab",
|
||||
"clock",
|
||||
"condition",
|
||||
"every",
|
||||
"stop",
|
||||
"http",
|
||||
"flow-detail",
|
||||
"code",
|
||||
"code-js2",
|
||||
"ekuaibao-datalink-filter",
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
"ekuaibao-datalink-delete",
|
||||
"data-convert",
|
||||
"flow-create-task",
|
||||
]);
|
||||
|
||||
const KNOWN_TYPES = new Set(["webhook", "condition", "every", "stop", "http", "flow-detail", "code", "code-js2", "ekuaibao-datalink-filter", "ekuaibao-datalink-create", "data-convert", "flow-create-task"]);
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [...code.matchAll(/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g)].map((match) => (match[1] || match[2] || "").trim()).filter(Boolean);
|
||||
const values = [
|
||||
...code.matchAll(
|
||||
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
||||
),
|
||||
]
|
||||
.map((match) => (match[1] || match[2] || "").trim())
|
||||
.filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] { return tasks.map((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); return { type: task.type, name: task.name, label: task.label || task.displayName || "", path, orderIndex: task.orderIndex, levelIndex: task.levelIndex, children: toAst(task.tasks || [], path) }; }); }
|
||||
export function analyzeWorkflow(detail: WorkflowDetail): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks); const dependencies: WorkflowDependency[] = []; const diagnostics: WorkflowDiagnostic[] = [];
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "") => tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); if (refs.length) dependencies.push({ path, taskType: task.type, references: refs }); if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) diagnostics.push({ severity: "error", code: "EMPTY_CODE", path, message: "代码节点没有可执行脚本" }); if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) diagnostics.push({ severity: "warning", code: "EMPTY_BRANCH", path, message: `${task.type} 控制节点没有子节点` }); if (!KNOWN_TYPES.has(task.type)) diagnostics.push({ severity: "warning", code: "UNKNOWN_TASK_TYPE", path, message: `未收录的节点类型: ${task.type}` }); visit(task.tasks || [], path); });
|
||||
visit(detail.tasks); return { workflow: { id: detail.id, label: detail.label, state: detail.state, version: detail.version }, ast, dependencies, diagnostics };
|
||||
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
||||
return tasks.map((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
return {
|
||||
type: task.type,
|
||||
name: task.name,
|
||||
label: task.label || task.displayName || "",
|
||||
path,
|
||||
orderIndex: task.orderIndex,
|
||||
levelIndex: task.levelIndex,
|
||||
children: toAst(task.tasks || [], path),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
||||
return raw.specificationId.trim();
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const found = task.inputs.find((item) => item.key === "specificationId");
|
||||
if (found && typeof found.value === "string" && found.value.trim()) {
|
||||
return found.value.trim();
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
||||
if (typeof specId === "string" && specId.trim()) {
|
||||
return specId.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getTaskFormEntries(
|
||||
task: WorkflowTask
|
||||
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (Array.isArray(raw.form)) {
|
||||
return raw.form.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (raw.form && typeof raw.form === "object") {
|
||||
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const formInput = task.inputs.find((item) => item.key === "form");
|
||||
if (formInput && Array.isArray(formInput.value)) {
|
||||
return formInput.value.filter(
|
||||
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formInput && formInput.value && typeof formInput.value === "object") {
|
||||
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const formVal = (raw.inputs as Record<string, unknown>).form;
|
||||
if (Array.isArray(formVal)) {
|
||||
return formVal.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formVal && typeof formVal === "object") {
|
||||
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||||
const ids = new Set<string>();
|
||||
const walk = (tasks: WorkflowTask[]) => {
|
||||
for (const task of tasks) {
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
if (specId) ids.add(specId);
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
walk(task.tasks);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(detail.tasks || []);
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||||
if (task.type !== "condition") return false;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
||||
const serialized = JSON.stringify(filterSource);
|
||||
if (
|
||||
serialized.includes(`${targetTaskName}.$status`) ||
|
||||
serialized.includes(`${targetTaskName}.status`) ||
|
||||
serialized.includes(`${targetTaskName}.result`) ||
|
||||
serialized.includes(`${targetTaskName}.data`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
serialized.includes(targetTaskName) &&
|
||||
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
||||
);
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
tasks: WorkflowTask[],
|
||||
basePath: string,
|
||||
createTaskName: string
|
||||
): Array<{ task: WorkflowTask; path: string }> {
|
||||
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
tasks.forEach((task, idx) => {
|
||||
const path = `${basePath}.${idx}`;
|
||||
if (task.type === "ekuaibao-datalink-edit") {
|
||||
found.push({ task, path });
|
||||
return;
|
||||
}
|
||||
if (taskGuardsStatusOf(task, createTaskName)) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
export function analyzeWorkflow(
|
||||
detail: WorkflowDetail,
|
||||
options: AnalyzeWorkflowOptions = {}
|
||||
): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks);
|
||||
const dependencies: WorkflowDependency[] = [];
|
||||
const diagnostics: WorkflowDiagnostic[] = [];
|
||||
|
||||
if (detail.state === 0) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "WORKFLOW_DISABLED",
|
||||
path: "workflow",
|
||||
message:
|
||||
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
||||
});
|
||||
}
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
const refs = referencesFromTask(task);
|
||||
if (refs.length) {
|
||||
dependencies.push({ path, taskType: task.type, references: refs });
|
||||
}
|
||||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "EMPTY_CODE",
|
||||
path,
|
||||
message: "代码节点没有可执行脚本",
|
||||
});
|
||||
}
|
||||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "EMPTY_BRANCH",
|
||||
path,
|
||||
message: `${task.type} 控制节点没有子节点`,
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
path,
|
||||
message: `未收录的节点类型: ${task.type}`,
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||||
if (insideEvery && task.type === "flow-create-task") {
|
||||
const onError = (task as Record<string, unknown>).onError as
|
||||
| { defaultAction?: string }
|
||||
| undefined;
|
||||
if (onError?.defaultAction === "SKIP") {
|
||||
const subsequentSiblings = tasks.slice(index + 1);
|
||||
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
subsequentSiblings.forEach((sibling, relIdx) => {
|
||||
const siblingIndex = index + 1 + relIdx;
|
||||
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
||||
if (sibling.type === "ekuaibao-datalink-edit") {
|
||||
unguardedEdits.push({ task: sibling, path: siblingPath });
|
||||
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
||||
unguardedEdits.push(
|
||||
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
for (const edit of unguardedEdits) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||||
path: edit.path,
|
||||
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
const spec = specId ? options.specifications?.[specId] : undefined;
|
||||
const formEntries = getTaskFormEntries(task).filter(
|
||||
(entry) =>
|
||||
entry.value !== undefined &&
|
||||
entry.value !== null &&
|
||||
String(entry.value).trim() !== ""
|
||||
);
|
||||
|
||||
const specComponents =
|
||||
spec?.components ??
|
||||
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
||||
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
||||
: []);
|
||||
|
||||
if (spec && specComponents.length && formEntries.length > 0) {
|
||||
const matchedComponents = specComponents.filter((comp) => {
|
||||
const compKey = comp.name || comp.field || "";
|
||||
return formEntries.some(
|
||||
(entry) =>
|
||||
(Boolean(compKey) && entry.key === compKey) ||
|
||||
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
||||
);
|
||||
});
|
||||
|
||||
const linkageSources = matchedComponents.filter(
|
||||
(comp) =>
|
||||
Boolean(comp.assignmentRule) ||
|
||||
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
const srcKey = src.name || src.field || src.label || "";
|
||||
const overrideTargets = matchedComponents
|
||||
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
||||
.map((comp) => {
|
||||
const list = comp.priorityList || comp.priority || [];
|
||||
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
const linkagePriority = linkage?.priority ?? linkage?.value;
|
||||
const manualPriority = manual?.priority ?? manual?.value;
|
||||
if (
|
||||
linkagePriority !== undefined &&
|
||||
manualPriority !== undefined &&
|
||||
linkagePriority > manualPriority
|
||||
) {
|
||||
return {
|
||||
comp,
|
||||
compKey: comp.name || comp.field || comp.label || "",
|
||||
linkagePriority,
|
||||
manualPriority,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||||
|
||||
if (overrideTargets.length > 0) {
|
||||
const affectedDesc = overrideTargets
|
||||
.map(
|
||||
(t) =>
|
||||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||||
)
|
||||
.join("、");
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||||
path,
|
||||
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
|
||||
visit(detail.tasks);
|
||||
return {
|
||||
workflow: {
|
||||
id: detail.id,
|
||||
label: detail.label,
|
||||
state: detail.state,
|
||||
version: detail.version,
|
||||
},
|
||||
ast,
|
||||
dependencies,
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
+113
-5
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
PlatformSchema,
|
||||
WorkflowPageSchema,
|
||||
@@ -9,6 +10,10 @@ import {
|
||||
WorkflowSnapshotPageSchema,
|
||||
WorkflowLogPageSchema,
|
||||
WorkflowJobSchema,
|
||||
WorkflowJobDetailSchema,
|
||||
WorkflowTaskExecutionSchema,
|
||||
WorkflowExecutionPageSchema,
|
||||
WorkflowExecutionLogSchema,
|
||||
WorkflowDslSchema,
|
||||
StaffSchema,
|
||||
WebhookInfoSchema,
|
||||
@@ -16,10 +21,35 @@ import {
|
||||
} from "./types.js";
|
||||
import type { WorkflowState } from "./types.js";
|
||||
|
||||
// Helper to unwrap { data: T } response
|
||||
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const json = (await response.json()) as { data: unknown };
|
||||
return schema.parse(json.data);
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const raw = await response.json();
|
||||
const record =
|
||||
raw !== null && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
const code = record?.code;
|
||||
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
|
||||
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
|
||||
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
|
||||
|
||||
if (hasCodeError || payload === null || payload === undefined) {
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
|
||||
// Helper for simple success responses
|
||||
@@ -146,7 +176,7 @@ export async function toggleWorkflow(
|
||||
return ok(response);
|
||||
}
|
||||
|
||||
// ── 运行中的任务(Piper)──────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情(Piper)────────────────────────────────────
|
||||
|
||||
export async function listRunningJobs(
|
||||
client: KyInstance,
|
||||
@@ -159,6 +189,83 @@ export async function listRunningJobs(
|
||||
return unwrap(response, z.array(WorkflowJobSchema));
|
||||
}
|
||||
|
||||
export async function getJob(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowJobDetail> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}`);
|
||||
return unwrap(response, WorkflowJobDetailSchema);
|
||||
}
|
||||
|
||||
export async function getJobExecutionTree(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { page?: number; pageSize?: number } = {}
|
||||
): Promise<import("./types.js").WorkflowTaskExecution[]> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution`, {
|
||||
searchParams: {
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 100),
|
||||
},
|
||||
});
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([z.array(WorkflowTaskExecutionSchema), WorkflowExecutionPageSchema])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
export async function getJobFailedExecutions(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level/failed`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([WorkflowExecutionPageSchema, z.array(WorkflowTaskExecutionSchema)])
|
||||
);
|
||||
if (Array.isArray(parsed)) {
|
||||
return {
|
||||
number: 1,
|
||||
size: parsed.length,
|
||||
totalPages: 1,
|
||||
totalItems: parsed.length,
|
||||
items: parsed,
|
||||
};
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export async function getJobExecutionLevel(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { parentId: string; page?: number; pageSize?: number }
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level`, {
|
||||
searchParams: {
|
||||
parentId: options.parentId,
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 20),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowExecutionPageSchema);
|
||||
}
|
||||
|
||||
export async function getExecutionLogs(
|
||||
client: KyInstance,
|
||||
executionId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionLog[]> {
|
||||
const response = await client.get(`api/easo/executions/${executionId}/logs`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([
|
||||
z.array(WorkflowExecutionLogSchema),
|
||||
z.object({ items: z.array(WorkflowExecutionLogSchema).default([]) }).passthrough(),
|
||||
])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
// ── DSL 配置(Piper)──────────────────────────────────────────────────────────
|
||||
|
||||
export async function listDsl(
|
||||
@@ -199,3 +306,4 @@ export async function sampleWorkflowData(
|
||||
const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`);
|
||||
return WorkflowSampleDataSchema.parse(await response.json());
|
||||
}
|
||||
|
||||
@@ -16,6 +16,82 @@ export interface PlatformClients {
|
||||
easoClient: KyInstance;
|
||||
}
|
||||
|
||||
export function listPlatforms(...args: Parameters<typeof api.listPlatforms>) {
|
||||
return api.listPlatforms(...args);
|
||||
}
|
||||
|
||||
export function listWorkflows(...args: Parameters<typeof api.listWorkflows>) {
|
||||
return api.listWorkflows(...args);
|
||||
}
|
||||
|
||||
export function getWorkflowStats(...args: Parameters<typeof api.getWorkflowStats>) {
|
||||
return api.getWorkflowStats(...args);
|
||||
}
|
||||
|
||||
export function getWorkflowCharge(...args: Parameters<typeof api.getWorkflowCharge>) {
|
||||
return api.getWorkflowCharge(...args);
|
||||
}
|
||||
|
||||
export function getWorkflowDetail(...args: Parameters<typeof api.getWorkflowDetail>) {
|
||||
return api.getWorkflowDetail(...args);
|
||||
}
|
||||
|
||||
export function updateWorkflow(...args: Parameters<typeof api.updateWorkflow>) {
|
||||
return api.updateWorkflow(...args);
|
||||
}
|
||||
|
||||
export function listWorkflowSnapshots(...args: Parameters<typeof api.listWorkflowSnapshots>) {
|
||||
return api.listWorkflowSnapshots(...args);
|
||||
}
|
||||
|
||||
export function listWorkflowLogs(...args: Parameters<typeof api.listWorkflowLogs>) {
|
||||
return api.listWorkflowLogs(...args);
|
||||
}
|
||||
|
||||
export function toggleWorkflow(...args: Parameters<typeof api.toggleWorkflow>) {
|
||||
return api.toggleWorkflow(...args);
|
||||
}
|
||||
|
||||
export function listRunningJobs(...args: Parameters<typeof api.listRunningJobs>) {
|
||||
return api.listRunningJobs(...args);
|
||||
}
|
||||
|
||||
export function getJob(...args: Parameters<typeof api.getJob>) {
|
||||
return api.getJob(...args);
|
||||
}
|
||||
|
||||
export function getJobExecutionTree(...args: Parameters<typeof api.getJobExecutionTree>) {
|
||||
return api.getJobExecutionTree(...args);
|
||||
}
|
||||
|
||||
export function getJobFailedExecutions(...args: Parameters<typeof api.getJobFailedExecutions>) {
|
||||
return api.getJobFailedExecutions(...args);
|
||||
}
|
||||
|
||||
export function getJobExecutionLevel(...args: Parameters<typeof api.getJobExecutionLevel>) {
|
||||
return api.getJobExecutionLevel(...args);
|
||||
}
|
||||
|
||||
export function getExecutionLogs(...args: Parameters<typeof api.getExecutionLogs>) {
|
||||
return api.getExecutionLogs(...args);
|
||||
}
|
||||
|
||||
export function listDsl(...args: Parameters<typeof api.listDsl>) {
|
||||
return api.listDsl(...args);
|
||||
}
|
||||
|
||||
export function listStaffs(...args: Parameters<typeof api.listStaffs>) {
|
||||
return api.listStaffs(...args);
|
||||
}
|
||||
|
||||
export function getWebhookInfo(...args: Parameters<typeof api.getWebhookInfo>) {
|
||||
return api.getWebhookInfo(...args);
|
||||
}
|
||||
|
||||
export function sampleWorkflowData(...args: Parameters<typeof api.sampleWorkflowData>) {
|
||||
return api.sampleWorkflowData(...args);
|
||||
}
|
||||
|
||||
// ── 服务层:跨应用聚合 ───────────────────────────────────────────────────────
|
||||
|
||||
export interface ListAllWorkflowsOptions {
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import * as api from "./api.js";
|
||||
import {
|
||||
PlatformClients,
|
||||
listAllWorkflows,
|
||||
findWorkflowsByTaskType,
|
||||
} from "./services.js";
|
||||
|
||||
// ── 精简核心 MCP Tools (其余功能均由 CLI 和底层 SDK 直接提供) ──────────────────
|
||||
|
||||
export const platformTools = [
|
||||
{
|
||||
name: "platform_workflow_list_all",
|
||||
description: "跨所有启用自建应用汇总工作流列表,返回带 platformId/platformName 的聚合结果",
|
||||
parameters: z.object({
|
||||
page: z.number().optional().describe("页码,默认 1"),
|
||||
pageSize: z.number().optional().describe("每页数量,默认 20"),
|
||||
}),
|
||||
handler: async (
|
||||
clients: PlatformClients,
|
||||
params: { page?: number; pageSize?: number }
|
||||
) => {
|
||||
return await listAllWorkflows(clients, params);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "platform_workflow_detail",
|
||||
description: "获取工作流节点与 DSL 配置详情",
|
||||
parameters: z.object({
|
||||
pipelineId: z.string().describe("工作流 ID"),
|
||||
}),
|
||||
handler: async (
|
||||
{ easoClient }: PlatformClients,
|
||||
params: { pipelineId: string }
|
||||
) => {
|
||||
return await api.getWorkflowDetail(easoClient, params.pipelineId);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export type PlatformTool = (typeof platformTools)[number];
|
||||
@@ -338,17 +338,87 @@ export const WorkflowChargeSchema = z.object({
|
||||
remaining: z.number().default(0),
|
||||
});
|
||||
|
||||
// ── 运行中的任务 ──────────────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
|
||||
|
||||
export const WorkflowJobSchema = z.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string(),
|
||||
status: z.string().default(""),
|
||||
startTime: z.string().optional(),
|
||||
endTime: z.string().optional(),
|
||||
startTime: z.union([z.string(), z.number()]).optional(),
|
||||
endTime: z.union([z.string(), z.number()]).optional(),
|
||||
triggerType: z.string().default(""),
|
||||
});
|
||||
|
||||
export const WorkflowJobDetailSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
status: z.string().default(""),
|
||||
runType: z.string().default(""),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
inputs: z.any().optional(),
|
||||
outputs: z.any().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionErrorSchema = z
|
||||
.object({
|
||||
message: z.string().default(""),
|
||||
stackTrace: z.array(z.string()).nullish().transform((v) => v ?? []),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionLogSchema = z
|
||||
.object({
|
||||
id: z.union([z.string(), z.number()]).optional(),
|
||||
level: z.string().default("INFO"),
|
||||
message: z.string().default(""),
|
||||
createAt: z.union([z.string(), z.number()]).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowTaskExecutionSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
parentId: z.string().nullable().optional(),
|
||||
jobId: z.string().optional(),
|
||||
pipelineId: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
displayName: z.string().nullable().optional(),
|
||||
label: z.string().nullable().optional(),
|
||||
type: z.string().default(""),
|
||||
orderIndex: z.number().optional(),
|
||||
levelIndex: z.array(z.number()).optional(),
|
||||
status: z.string().default(""),
|
||||
executionTime: z.number().optional(),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
currentLoopPath: z.string().nullable().optional(),
|
||||
error: WorkflowExecutionErrorSchema.nullable().optional(),
|
||||
output: z.any().optional(),
|
||||
form: z.record(z.string(), z.any()).nullable().optional(),
|
||||
details: z.record(z.string(), z.any()).nullable().optional(),
|
||||
executionLogs: z.array(z.any()).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionPageSchema = z
|
||||
.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(20),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z
|
||||
.array(z.union([WorkflowTaskExecutionSchema, z.array(WorkflowTaskExecutionSchema)]))
|
||||
.default([])
|
||||
.transform((arr) => arr.flat()),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// ── DSL 配置 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const WorkflowDslSchema = z.object({
|
||||
@@ -423,6 +493,11 @@ export type WorkflowLogItem = z.infer<typeof WorkflowLogItemSchema>;
|
||||
export type WorkflowLogPage = z.infer<typeof WorkflowLogPageSchema>;
|
||||
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
|
||||
export type WorkflowJob = z.infer<typeof WorkflowJobSchema>;
|
||||
export type WorkflowJobDetail = z.infer<typeof WorkflowJobDetailSchema>;
|
||||
export type WorkflowExecutionError = z.infer<typeof WorkflowExecutionErrorSchema>;
|
||||
export type WorkflowExecutionLog = z.infer<typeof WorkflowExecutionLogSchema>;
|
||||
export type WorkflowTaskExecution = z.infer<typeof WorkflowTaskExecutionSchema>;
|
||||
export type WorkflowExecutionPage = z.infer<typeof WorkflowExecutionPageSchema>;
|
||||
export type WorkflowDsl = z.infer<typeof WorkflowDslSchema>;
|
||||
export type Staff = z.infer<typeof StaffSchema>;
|
||||
export type WebhookInfo = z.infer<typeof WebhookInfoSchema>;
|
||||
@@ -431,3 +506,4 @@ export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
|
||||
export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
|
||||
export type TaskMatch = z.infer<typeof TaskMatchSchema>;
|
||||
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { getDatabase } from "../../core/db/index.js";
|
||||
|
||||
export interface WorkflowErrorAlert {
|
||||
id: string;
|
||||
@@ -21,31 +23,110 @@ export interface WorkflowAlertCheckResult {
|
||||
newAlerts: WorkflowErrorAlert[];
|
||||
}
|
||||
|
||||
/** 本地持久化工作流错误指纹,避免定时检查时重复提醒同一错误计数。 */
|
||||
/** 本地持久化工作流错误指纹(统一落盘至 core/db SQLite,兼容显式 JSON 状态文件)。 */
|
||||
export class WorkflowAlertStore {
|
||||
constructor(private readonly filePath: string) {}
|
||||
private readonly scopeKey: string;
|
||||
private readonly jsonPath?: string;
|
||||
private readonly customDb?: Database;
|
||||
|
||||
constructor(scopeOrFilePath = "default", db?: Database) {
|
||||
this.scopeKey = scopeOrFilePath;
|
||||
this.customDb = db;
|
||||
if (scopeOrFilePath.endsWith(".json")) {
|
||||
this.jsonPath = scopeOrFilePath;
|
||||
}
|
||||
}
|
||||
|
||||
private get db(): Database {
|
||||
return this.customDb ?? getDatabase();
|
||||
}
|
||||
|
||||
private read(): PersistedAlerts {
|
||||
if (!existsSync(this.filePath)) return { version: 1, alerts: {} };
|
||||
try {
|
||||
const value = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedAlerts>;
|
||||
return { version: 1, alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {} };
|
||||
} catch {
|
||||
return { version: 1, alerts: {} };
|
||||
const dbRows = this.db
|
||||
.query(
|
||||
"SELECT id, error_count, observed_at FROM workflow_error_alerts WHERE scope_key = ?"
|
||||
)
|
||||
.all(this.scopeKey) as Array<{
|
||||
id: string;
|
||||
error_count: number;
|
||||
observed_at: number;
|
||||
}>;
|
||||
|
||||
if (dbRows.length > 0) {
|
||||
const alerts: Record<string, { errorCount: number; lastSeen: number }> = {};
|
||||
for (const row of dbRows) {
|
||||
alerts[row.id] = { errorCount: row.error_count, lastSeen: row.observed_at };
|
||||
}
|
||||
return { version: 1, alerts };
|
||||
}
|
||||
|
||||
if (this.jsonPath && existsSync(this.jsonPath)) {
|
||||
try {
|
||||
const value = JSON.parse(readFileSync(this.jsonPath, "utf8")) as Partial<PersistedAlerts>;
|
||||
return {
|
||||
version: 1,
|
||||
alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {},
|
||||
};
|
||||
} catch {
|
||||
return { version: 1, alerts: {} };
|
||||
}
|
||||
}
|
||||
|
||||
return { version: 1, alerts: {} };
|
||||
}
|
||||
|
||||
observe(alerts: WorkflowErrorAlert[]): WorkflowAlertCheckResult {
|
||||
const data = this.read();
|
||||
const activeIds = new Set(alerts.map((alert) => alert.id));
|
||||
const newAlerts = alerts.filter((alert) => data.alerts[alert.id]?.errorCount !== alert.errorCount);
|
||||
const newAlerts = alerts.filter(
|
||||
(alert) => data.alerts[alert.id]?.errorCount !== alert.errorCount
|
||||
);
|
||||
const updated = { ...data.alerts };
|
||||
for (const id of Object.keys(updated)) {
|
||||
if (!activeIds.has(id)) delete updated[id];
|
||||
}
|
||||
for (const alert of alerts) updated[alert.id] = { errorCount: alert.errorCount, lastSeen: alert.observedAt };
|
||||
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`, { mode: 0o600 });
|
||||
for (const alert of alerts) {
|
||||
updated[alert.id] = { errorCount: alert.errorCount, lastSeen: alert.observedAt };
|
||||
}
|
||||
|
||||
const db = this.db;
|
||||
const upsert = db.prepare(`
|
||||
INSERT INTO workflow_error_alerts (
|
||||
scope_key, id, pipeline_id, platform_id, pipeline_name, error_count, state, observed_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(scope_key, id) DO UPDATE SET
|
||||
pipeline_name = excluded.pipeline_name,
|
||||
error_count = excluded.error_count,
|
||||
state = excluded.state,
|
||||
observed_at = excluded.observed_at
|
||||
`);
|
||||
|
||||
const tx = db.transaction((items: WorkflowErrorAlert[]) => {
|
||||
db.run("DELETE FROM workflow_error_alerts WHERE scope_key = ?", [this.scopeKey]);
|
||||
for (const alert of items) {
|
||||
upsert.run(
|
||||
this.scopeKey,
|
||||
alert.id,
|
||||
alert.pipelineId,
|
||||
alert.platformId,
|
||||
alert.pipelineName,
|
||||
alert.errorCount,
|
||||
alert.state,
|
||||
alert.observedAt
|
||||
);
|
||||
}
|
||||
});
|
||||
tx(alerts);
|
||||
|
||||
if (this.jsonPath) {
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
}
|
||||
|
||||
return { activeAlerts: alerts, newAlerts };
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,19 @@ import {
|
||||
} from "./workflow-state.js";
|
||||
import { WorkflowDetailSchema } from "./types.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
import { listWorkflowSnapshots, listWorkflowLogs, toggleWorkflow, updateWorkflow } from "./api.js";
|
||||
import {
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
getJobExecutionLevel,
|
||||
getJobExecutionTree,
|
||||
getJobFailedExecutions,
|
||||
getWorkflowDetail,
|
||||
listWorkflowSnapshots,
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
updateWorkflow,
|
||||
} from "./api.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "./workflow-alert-store.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
@@ -150,4 +162,144 @@ describe("workflow draft state machine", () => {
|
||||
expect(failed.status).toBe("failed");
|
||||
expect(failed.error).toBe("网络错误");
|
||||
});
|
||||
|
||||
it("throws structured AuthenticationError or EkbApiError when Piper unwrap receives null data or non-200 code", async () => {
|
||||
const unauthorizedClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 401, message: "登录已过期", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(unauthorizedClient, "wf-1")).rejects.toBeInstanceOf(AuthenticationError);
|
||||
|
||||
const nullDataClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 200, msg: "pipeline not found", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(nullDataClient, "wf-1")).rejects.toBeInstanceOf(EkbApiError);
|
||||
});
|
||||
|
||||
it("calls the 5 Piper Job diagnostic endpoints and parses execution trees, failed nodes, child levels, and logs", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options?: any) => {
|
||||
if (url === "api/easo/jobs/892809886382563347") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
id: "892809886382563347",
|
||||
pipelineId: "886351399301758976",
|
||||
label: "每30分钟创建采购申请单",
|
||||
state: "COMPLETED",
|
||||
successTaskCount: 5,
|
||||
errorTaskCount: 1,
|
||||
hasError: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809893789696012",
|
||||
jobId: "892809886382563347",
|
||||
name: "every_0",
|
||||
label: "循环",
|
||||
type: "every",
|
||||
state: "COMPLETED",
|
||||
levelIndex: [0],
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level/failed") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809900000000001",
|
||||
jobId: "892809886382563347",
|
||||
parentId: "892809893789696012",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
label: "创建预付申请单",
|
||||
type: "flow-create-task",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level") {
|
||||
expect(options?.searchParams).toEqual({
|
||||
parentId: "892809893789696012",
|
||||
number: "1",
|
||||
pageSize: "20",
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
number: 1,
|
||||
size: 20,
|
||||
totalPages: 1,
|
||||
totalItems: 1,
|
||||
items: [
|
||||
[
|
||||
{
|
||||
id: "892809900000000001",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/executions/892809893789696012/logs") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
total: 1,
|
||||
items: [{ id: "log-1", message: "MVEL script executed", level: "INFO" }],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
throw new Error(`Unexpected URL: ${url}`);
|
||||
},
|
||||
} as any;
|
||||
|
||||
const job = await getJob(client, "892809886382563347");
|
||||
expect(job.hasError).toBe(true);
|
||||
expect(job.errorTaskCount).toBe(1);
|
||||
|
||||
const tree = await getJobExecutionTree(client, "892809886382563347");
|
||||
expect(tree).toHaveLength(1);
|
||||
expect(tree[0]?.name).toBe("every_0");
|
||||
|
||||
const failed = await getJobFailedExecutions(client, "892809886382563347");
|
||||
expect(failed.items).toHaveLength(1);
|
||||
expect((failed.items[0]?.outputs as any)?.error).toBe("我方签约主体未填写");
|
||||
|
||||
const level = await getJobExecutionLevel(client, "892809886382563347", {
|
||||
parentId: "892809893789696012",
|
||||
});
|
||||
expect(level.items).toHaveLength(1);
|
||||
|
||||
const logs = await getExecutionLogs(client, "892809893789696012");
|
||||
expect(logs[0]?.message).toBe("MVEL script executed");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
|
||||
export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "failed";
|
||||
@@ -19,9 +20,9 @@ function pathParts(path: string): string[] {
|
||||
.split(".")
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
if (!parts.length) throw new Error("工作流配置路径不能为空");
|
||||
if (!parts.length) throw new ValidationError("工作流配置路径不能为空");
|
||||
if (parts.some((part) => !/^[A-Za-z_$][\w$-]*$/.test(part) && !/^\d+$/.test(part))) {
|
||||
throw new Error(`工作流配置路径非法: ${path}`);
|
||||
throw new ValidationError(`工作流配置路径非法: ${path}`);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
@@ -40,12 +41,12 @@ export function applyWorkflowPathPatch(
|
||||
let cursor: any = patched;
|
||||
for (const part of parts.slice(0, -1)) {
|
||||
if (cursor === null || typeof cursor !== "object" || !(part in cursor)) {
|
||||
throw new Error(`工作流配置路径不存在: ${path}`);
|
||||
throw new NotFoundError(`工作流配置路径不存在: ${path}`);
|
||||
}
|
||||
cursor = cursor[part];
|
||||
}
|
||||
if (cursor === null || typeof cursor !== "object") {
|
||||
throw new Error(`工作流配置路径不可写: ${path}`);
|
||||
throw new ValidationError(`工作流配置路径不可写: ${path}`);
|
||||
}
|
||||
cursor[parts.at(-1)!] = value;
|
||||
return patched as WorkflowDetail;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { getGlobalCache } from "../../core/cache/index.js";
|
||||
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
|
||||
@@ -64,18 +63,3 @@ export async function getRoleMembers(
|
||||
if (!role) return undefined;
|
||||
return { role, members: await listRoleMembers(client, corpId, role.id) };
|
||||
}
|
||||
|
||||
export const roleTools = [
|
||||
{
|
||||
name: "role_list",
|
||||
description: "列出当前企业角色定义与角色组",
|
||||
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
|
||||
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const client = await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp));
|
||||
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
|
||||
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
|
||||
},
|
||||
},
|
||||
];
|
||||
+52
-5
@@ -2,18 +2,49 @@ import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { URL } from "node:url";
|
||||
import { runCli } from "../cli/runner.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { getOpenApiSchema } from "../core/embedded-openapi.js";
|
||||
import { getOpenApiSchema } from "../packaging/embedded-openapi.js";
|
||||
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
|
||||
export function isTrustedOrigin(originHeader: string | undefined): boolean {
|
||||
if (!originHeader) return true; // non-browser / same-origin requests without Origin header
|
||||
const allowedOriginEnv = process.env.HOSE_HTTP_CORS_ORIGIN?.trim();
|
||||
if (allowedOriginEnv === "*") return true;
|
||||
if (allowedOriginEnv && originHeader === allowedOriginEnv) return true;
|
||||
try {
|
||||
const parsed = new URL(originHeader);
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
return host === "127.0.0.1" || host === "localhost" || host === "::1" || host === "[::1]";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function checkHttpAuth(req: IncomingMessage): boolean {
|
||||
const requiredToken = process.env.HOSE_HTTP_TOKEN?.trim();
|
||||
if (!requiredToken) return true;
|
||||
const authHeader = req.headers.authorization || "";
|
||||
return authHeader === `Bearer ${requiredToken}`;
|
||||
}
|
||||
|
||||
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
// 1. CORS headers
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
|
||||
const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
|
||||
const trustedOrigin = isTrustedOrigin(origin);
|
||||
|
||||
// 1. CORS headers: only grant CORS to local/trusted origins instead of blind wildcard RCE
|
||||
if (trustedOrigin) {
|
||||
res.setHeader("Access-Control-Allow-Origin", origin || "http://127.0.0.1");
|
||||
res.setHeader("Vary", "Origin");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
|
||||
}
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
if (!trustedOrigin) {
|
||||
sendError(res, 403, "Forbidden cross-origin preflight request");
|
||||
return;
|
||||
}
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
return;
|
||||
@@ -71,6 +102,14 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
|
||||
// 3. Command Execution Endpoint: POST /api/cli
|
||||
if (method === "POST" && pathname === "/api/cli") {
|
||||
if (!trustedOrigin) {
|
||||
sendError(res, 403, "Forbidden: untrusted cross-origin request to /api/cli");
|
||||
return;
|
||||
}
|
||||
if (!checkHttpAuth(req)) {
|
||||
sendError(res, 401, "Unauthorized: valid Bearer token required");
|
||||
return;
|
||||
}
|
||||
const body = (await parseJsonBody(req)) as Record<string, unknown> | null;
|
||||
const command = (typeof body?.command === "string" ? body.command : "").trim();
|
||||
if (!command) {
|
||||
@@ -104,6 +143,14 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
|
||||
// 4. RESTful: GET /v1/corps
|
||||
if (method === "GET" && pathname === "/v1/corps") {
|
||||
if (!trustedOrigin) {
|
||||
sendError(res, 403, "Forbidden: untrusted cross-origin request to /v1/corps");
|
||||
return;
|
||||
}
|
||||
if (!checkHttpAuth(req)) {
|
||||
sendError(res, 401, "Unauthorized: valid Bearer token required");
|
||||
return;
|
||||
}
|
||||
const configs = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
sendJson(res, 200, {
|
||||
|
||||
+30
-6
@@ -16,10 +16,12 @@ describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
test("GET / 返回服务概览与 CORS 标头", async () => {
|
||||
const res = await fetch(`${baseUrl}/`);
|
||||
test("GET / 返回服务概览与本地 CORS 标头", async () => {
|
||||
const res = await fetch(`${baseUrl}/`, {
|
||||
headers: { Origin: "http://localhost:3000" },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("http://localhost:3000");
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.name).toBe("hose-use");
|
||||
expect(json.version).toBe(VERSION);
|
||||
@@ -78,6 +80,19 @@ describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||
expect(json.stdout).toContain(`hose-use v${VERSION}`);
|
||||
});
|
||||
|
||||
test("POST /api/cli 拒绝来自非授信外部 Origin 的跨站命令执行请求 (防 CSRF RCE)", async () => {
|
||||
const res = await fetch(`${baseUrl}/api/cli`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: "https://evil.example.com",
|
||||
},
|
||||
body: JSON.stringify({ command: "version" }),
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.headers.get("access-control-allow-origin")).toBeNull();
|
||||
});
|
||||
|
||||
test("GET /v1/corps 返回企业列表与运行模式", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`);
|
||||
expect(res.status).toBe(200);
|
||||
@@ -87,10 +102,19 @@ describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||
expect(Array.isArray(json.corps)).toBe(true);
|
||||
});
|
||||
|
||||
test("OPTIONS /v1/corps 处理 CORS 跨域预检", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
|
||||
test("OPTIONS /v1/corps 允许本地 Origin 预检并拦截未知外部 Origin", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`, {
|
||||
method: "OPTIONS",
|
||||
headers: { Origin: "http://127.0.0.1:8888" },
|
||||
});
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:8888");
|
||||
|
||||
const blocked = await fetch(`${baseUrl}/v1/corps`, {
|
||||
method: "OPTIONS",
|
||||
headers: { Origin: "https://attacker.example.com" },
|
||||
});
|
||||
expect(blocked.status).toBe(403);
|
||||
});
|
||||
});
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+11
-59
@@ -43,24 +43,13 @@ describe("hose-use MCP server & hose_cli single-gate pattern", () => {
|
||||
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("resolves HOSE_MCP_MODE to single gateway mode", () => {
|
||||
expect(resolveMcpMode()).toBe("single");
|
||||
expect(resolveMcpMode("single")).toBe("single");
|
||||
});
|
||||
|
||||
test("advertises only hose_cli in single mode and executes commands in-process", async () => {
|
||||
const server = createServer({ mode: "single" });
|
||||
test("advertises only hose_cli and executes commands in-process", async () => {
|
||||
const server = createServer();
|
||||
const client = new Client({ name: "hose-use-test-client", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
@@ -105,50 +94,13 @@ describe("hose-use MCP server & hose_cli single-gate pattern", () => {
|
||||
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");
|
||||
// Calling unknown tool returns error
|
||||
const unknownToolResult = await client.callTool({
|
||||
name: "legacy_removed_tool",
|
||||
arguments: {},
|
||||
});
|
||||
expect(unknownToolResult.isError).toBe(true);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
|
||||
+53
-232
@@ -1,27 +1,17 @@
|
||||
import { Server } from "@modelcontextprotocol/server";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
||||
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 { createSessionClient, getUnityClient } from "./core/http/index.js";
|
||||
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
|
||||
import { authTools } from "./core/auth/tools.js";
|
||||
import { platformTools } from "./domains/platform/tools.js";
|
||||
import { datalinkTools } from "./domains/datalink/tools.js";
|
||||
import { billTools } from "./domains/bill/tools.js";
|
||||
import { feetypeTools } from "./domains/feetype/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 const HOSE_MCP_MODE_ENV = "HOSE_MCP_MODE";
|
||||
export const HOSE_MCP_ENABLED_ENV = "HOSE_USE_MCP_ENABLED";
|
||||
|
||||
export type HoseMcpMode = "single" | "all" | "legacy";
|
||||
export type HoseMcpMode = "single";
|
||||
|
||||
const serverEntryFile = fileURLToPath(import.meta.url);
|
||||
const appRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\")
|
||||
@@ -33,11 +23,7 @@ export function resolveMcpEnabled(value = process.env[HOSE_MCP_ENABLED_ENV]): bo
|
||||
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
||||
}
|
||||
|
||||
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";
|
||||
export function resolveMcpMode(_value = process.env[HOSE_MCP_MODE_ENV]): HoseMcpMode {
|
||||
return "single";
|
||||
}
|
||||
|
||||
@@ -132,47 +118,8 @@ export function cliResult(result: CliResult): {
|
||||
};
|
||||
}
|
||||
|
||||
function formatError(error: unknown): {
|
||||
content: Array<{ type: "text"; text: string }>;
|
||||
isError: true;
|
||||
} {
|
||||
if (error instanceof NotLoggedInError) {
|
||||
return {
|
||||
content: [{ type: "text", text: "未配置企业,请先添加企业配置或登录" }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof AuthenticationError) {
|
||||
return {
|
||||
content: [{ type: "text", text: `认证失败: ${error.message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof EkbError) {
|
||||
return {
|
||||
content: [{ type: "text", text: `错误 [${error.code}]: ${error.message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return {
|
||||
content: [{ type: "text", text: `参数错误: ${error.message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean } = {}) {
|
||||
export function createServer(options: { mode?: string; enabled?: boolean } = {}) {
|
||||
const enabled = options.enabled ?? resolveMcpEnabled();
|
||||
const mode = options.mode ?? resolveMcpMode();
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
@@ -186,48 +133,32 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
|
||||
}
|
||||
);
|
||||
|
||||
const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools, ...feetypeTools];
|
||||
|
||||
// 注册工具列表
|
||||
// 注册单工具网关
|
||||
server.setRequestHandler("tools/list", async () => {
|
||||
if (!enabled) {
|
||||
return { tools: [] };
|
||||
}
|
||||
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, including workflow get/patch/save/publish/history/logs/check. 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: 'workflow check --json', 'workflow publish <pipelineId>', or 'workflow get <pipelineId> --json -o workflow.json'.",
|
||||
return {
|
||||
tools: [
|
||||
{
|
||||
name: HOSE_CLI_TOOL_NAME,
|
||||
description:
|
||||
"Run hose-use CLI commands, including workflow get/patch/save/publish/history/logs/check. 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: 'workflow check --json', 'workflow publish <pipelineId>', or 'workflow get <pipelineId> --json -o workflow.json'.",
|
||||
},
|
||||
},
|
||||
required: ["command"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
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 };
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
// 处理工具调用
|
||||
@@ -241,155 +172,45 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
|
||||
}
|
||||
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 {
|
||||
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 || {});
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
const result = await authTool.handler({ corpContext }, parsed.data as never);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// 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: "未配置企业,请先调用 auth login 登录或 auth import 导入凭证",
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
const platformTool = platformTools.find((t) => t.name === name);
|
||||
if (platformTool) {
|
||||
const parsed = platformTool.parameters.safeParse(args || {});
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
const sessionClient = await createSessionClient(currentCorp);
|
||||
const { client: unityClient } = await getUnityClient(currentCorp);
|
||||
const result = await platformTool.handler(
|
||||
{ corp: currentCorp, ekbClient: sessionClient, easoClient: unityClient },
|
||||
parsed.data as never
|
||||
);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// DataLink 应用/业务对象/记录工具
|
||||
const datalinkTool = datalinkTools.find((t) => t.name === name);
|
||||
if (datalinkTool) {
|
||||
const parsed = datalinkTool.parameters.safeParse(args || {});
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
const sessionClient = await createSessionClient(currentCorp);
|
||||
const result = await datalinkTool.handler(
|
||||
{ corp: currentCorp, ekbClient: sessionClient },
|
||||
parsed.data as never
|
||||
);
|
||||
return {
|
||||
content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result, null, 2) }],
|
||||
};
|
||||
}
|
||||
|
||||
if (name !== HOSE_CLI_TOOL_NAME) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `未知工具: ${name}。在单工具网关模式下,请通过 ${HOSE_CLI_TOOL_NAME} 调用。`,
|
||||
text: `未知工具: ${name}。请通过 ${HOSE_CLI_TOOL_NAME} 调用 CLI 命令。`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
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 formatError(error);
|
||||
return cliResult({
|
||||
stdout: "",
|
||||
stderr: error instanceof Error ? error.message : String(error),
|
||||
exitCode: 1,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user