70 files changed
+2422
-837
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.22",
|
||||
"version": "0.9.0",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.22)
|
||||
# hose-use (v0.9.0)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.22",
|
||||
"version": "0.9.0",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -58,7 +58,7 @@ test("source and freshly packaged plugin preserve offline review and MCP contrac
|
||||
const result = Bun.spawnSync([
|
||||
process.execPath, ...entry, "workflow", "eval-script", "--file", file,
|
||||
"--type", fixture.type, "--corp", "smoke", "--stateless", "--json",
|
||||
], { cwd: pluginRoot, env, timeout: 10000 });
|
||||
], { cwd: pluginRoot, env, timeout: 30000 });
|
||||
expect(result.exitCode).toBe(fixture.error ? 1 : 0);
|
||||
const report = JSON.parse(result.stdout.toString());
|
||||
expect(report.success).toBe(!fixture.error);
|
||||
|
||||
+18
-11
@@ -99,25 +99,30 @@ function installBinary(localBinary: string, targetPath: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function syncAgentSkill(): string | undefined {
|
||||
const source = join(ROOT, "skills", "hose-use");
|
||||
const target = join(homedir(), ".agents", "skills", "hose-use");
|
||||
if (!existsSync(source)) return undefined;
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
cpSync(source, target, { recursive: true, force: true });
|
||||
return target;
|
||||
function syncAgentSkills(): string[] {
|
||||
const synced: string[] = [];
|
||||
for (const name of ["hose-use", "hose-aipro"]) {
|
||||
const source = join(ROOT, "skills", name);
|
||||
const target = join(homedir(), ".agents", "skills", name);
|
||||
if (existsSync(source)) {
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
cpSync(source, target, { recursive: true, force: true });
|
||||
synced.push(target);
|
||||
}
|
||||
}
|
||||
return synced;
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)): Promise<number> {
|
||||
const options = parseDevOverrideArgs(argv);
|
||||
const targetPath = options.targetPath || resolveTargetBinaryPath();
|
||||
|
||||
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use");
|
||||
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use / hose-aipro");
|
||||
console.error(` 工作区: ${ROOT}`);
|
||||
console.error(` 目标: ${targetPath}`);
|
||||
|
||||
if (options.dryRun) {
|
||||
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/hose-use");
|
||||
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/{hose-use,hose-aipro}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -132,8 +137,10 @@ export async function main(argv = process.argv.slice(2)): Promise<number> {
|
||||
}
|
||||
|
||||
try {
|
||||
const skillTarget = syncAgentSkill();
|
||||
if (skillTarget) console.error(`✓ [dev:override] 已同步 Agent Skill: ${skillTarget}`);
|
||||
const skillTargets = syncAgentSkills();
|
||||
if (skillTargets.length > 0) {
|
||||
console.error(`✓ [dev:override] 已同步 Agent Skills:\n${skillTargets.map((t) => ` ${t}`).join("\n")}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`);
|
||||
}
|
||||
|
||||
@@ -58,15 +58,19 @@ export function bumpVersion(ROOT: string, input: string, rebuild = () => {
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
// 3. skills/hose-use/SKILL.md & skills/hose-aipro/SKILL.md
|
||||
for (const subSkill of ["hose-use", "hose-aipro"]) {
|
||||
const skillPath = join(ROOT, "skills", subSkill, "SKILL.md");
|
||||
if (existsSync(skillPath)) {
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(new RegExp(`# ${subSkill} \\(v\\d+\\.\\d+\\.\\d+(?:-[A-Za-z0-9.-]+)?\\)`, "g"), `# ${subSkill} (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?:/g, `v${nextVersion}:`);
|
||||
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log(`✓ Updated skills/${subSkill}/SKILL.md`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. specs/hose-open-api/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "hose-open-api", "openapi.yaml");
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
---
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.0
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.0)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
---
|
||||
|
||||
## 体系架构与协同边界 (Ecosystem & Boundaries)
|
||||
|
||||
`hose-aipro` 与通用平台工具 `hose-use` 保持严格的正交分离与协同:
|
||||
|
||||
| 维度 | `hose-aipro` (本技能) | `hose-use` (配套平台工具) |
|
||||
|---|---|---|
|
||||
| **核心职责** | 确定性审批仲裁、事实证据打标、审核要点清单、硬门禁阻断、审计轨迹 | 企业租户配置、账密登录、单据检索、工作流、DataLink、自定义对象等 |
|
||||
| **命令行** | `hose-aipro <子命令>` | `hose-use <子命令>` |
|
||||
| **Skill 目录** | `~/.agents/skills/hose-aipro` | `~/.agents/skills/hose-use` |
|
||||
| **共享基础设施** | 共享企业租户配置(`~/.config/hose-use/enterprises/`)与凭据体系 | 共享企业租户配置与凭据体系 |
|
||||
| **打包与安装** | 单一二进制(Unix Multicall Binary),安装与自升级自动同步 | 单一二进制(Unix Multicall Binary),安装与自升级自动同步 |
|
||||
| **服务互启互关** | `hose-aipro hose-use <start\|stop\|restart\|status>`(控制 hose-use 进程) | `hose-use aipro <start\|stop\|restart\|status>`(控制 hose-aipro 进程) |
|
||||
| **自升级命令** | `hose-aipro update [check\|--changelog]`(与 hose-use 完全一致) | `hose-use update [check\|--changelog]`(与 hose-aipro 完全一致) |
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **强确定性硬条款阻断**:AI 仅负责对事实证据进行核验与状态打标(`PASS` / `FAIL` / `SKIP`);下游流转动作(同意 / 驳回 / 转人工)由本地网关根据【硬性 / 弹性 / 建议 / 特殊】硬编码规则进行物理裁决,切断模型幻觉可能导致的违规放行。
|
||||
> 如需管理企业账套、工作流或基础单据数据,请直接使用配套的 `hose-use` 命令行与 `hose-use` Skill。
|
||||
|
||||
---
|
||||
|
||||
## 快速自省与运行上下文 (Zero-Source-Reading)
|
||||
|
||||
在开始执行任何审批仲裁任务前,优先执行自省命令建立当前上下文:
|
||||
|
||||
```bash
|
||||
# 1. 查看 AI PRO 网关状态与当前连接企业
|
||||
hose-aipro status [--json]
|
||||
# 别名: hose-aipro whoami, hose-aipro context
|
||||
|
||||
# 2. 查看审批规则场景库
|
||||
hose-aipro scopes
|
||||
|
||||
# 3. 查看特定场景下的审核要点清单
|
||||
hose-aipro points 1
|
||||
# 或通过场景名查看: hose-aipro points 差旅报销
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 核心审批仲裁全流程 (End-to-End Workflow)
|
||||
|
||||
```text
|
||||
1. 挂载单据 2. 录入事实证据 3. 确定性仲裁 4. 审计溯源
|
||||
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
|
||||
│ hose-aipro bind │ ───> │ hose-aipro review│ ───> │hose-aipro decide │ ───> │ hose-aipro logs │
|
||||
│ 绑定单号与场景要点 │ │ PASS/FAIL/SKIP │ │ 硬门禁裁决与流转 │ │ 全链路不可篡改审计 │
|
||||
└──────────────────┘ └──────────────────┘ └──────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
### 1. 挂载绑定要点 (`bind`)
|
||||
将目标审批单据与特定审核场景的规则要点关联并初始化会话:
|
||||
```bash
|
||||
hose-aipro bind S26000001 1
|
||||
# 或指定企业: hose-aipro bind S26000001 1 --corp=test-corp
|
||||
```
|
||||
|
||||
### 2. 查看审核清单 (`checklist`)
|
||||
检查当前单据各要点的当前核验状态:
|
||||
```bash
|
||||
hose-aipro checklist S26000001
|
||||
```
|
||||
|
||||
### 3. 事实证据核验与打标 (`review`)
|
||||
针对各项条款录入客观核验证据并打标:
|
||||
```bash
|
||||
# 方式 A: 批量 JSON 打标
|
||||
hose-aipro review S26000001 --findings='[{"index":1,"status":"PASS","evidence":"发票真伪查验通过"},{"index":2,"status":"FAIL","reasoning":"超标200元"}]'
|
||||
|
||||
# 方式 B: 单项打标
|
||||
hose-aipro review S26000001 --point=2 --status=FAIL --reason="住宿费用超出差旅标准 200 元"
|
||||
```
|
||||
|
||||
### 4. 确定性网关仲裁 (`decide`)
|
||||
根据打标结果进行门禁判定:
|
||||
```bash
|
||||
# 预审模拟(Dry Run,仅计算仲裁裁决,不向云端提交真实流转动作)
|
||||
hose-aipro decide S26000001
|
||||
|
||||
# 真实执行(必须追加 --apply --yes)
|
||||
hose-aipro decide S26000001 --apply --yes
|
||||
```
|
||||
|
||||
### 5. 审计流水追溯 (`logs`)
|
||||
```bash
|
||||
hose-aipro logs S26000001
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 本机常驻服务与跨进程管理 (Daemon & Peer Control)
|
||||
|
||||
`hose-aipro` 拥有独立的常驻 HTTP 守护进程(默认端口 `8889`),并能直接启停本机的 `hose-use` 服务(默认端口 `8888`):
|
||||
|
||||
```bash
|
||||
# 管理 hose-aipro 自身的服务 (端口 8889)
|
||||
hose-aipro service start
|
||||
hose-aipro service status
|
||||
hose-aipro service logs
|
||||
hose-aipro service stop
|
||||
|
||||
# 管理本机的 hose-use 服务 (端口 8888)
|
||||
hose-aipro hose-use start
|
||||
hose-aipro hose-use status
|
||||
hose-aipro hose-use stop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 统一自升级与技能管理 (Update & Skill)
|
||||
|
||||
由于 `hose-aipro` 与 `hose-use` 由单一多呼叫二进制(Multicall Binary)构建,升级与技能操作保持完全统一:
|
||||
|
||||
```bash
|
||||
# 检查与执行版本自升级(同时更新 hose-aipro 与 hose-use)
|
||||
hose-aipro update
|
||||
hose-aipro update check
|
||||
hose-aipro update --changelog
|
||||
|
||||
# 查看与安装全局 Agent Skill
|
||||
hose-aipro skill status
|
||||
hose-aipro skill install --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 详细业务与专卷参考
|
||||
|
||||
深入细节请查阅对应参考文档:
|
||||
- 审批裁决、打标语义与规约语法:[references/approval.md](./references/approval.md)
|
||||
- 常驻服务与 HTTP 接口规范:[references/service.md](./references/service.md)
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
command: "hose-aipro"
|
||||
default_args: []
|
||||
@@ -0,0 +1,10 @@
|
||||
# hose-aipro 参考专卷索引 (references)
|
||||
|
||||
本目录是随 `hose-aipro` 分发的业务操作与服务管理参考,供 [hose-aipro Skill 入口](../SKILL.md) 按任务读取。
|
||||
|
||||
## 参考清单
|
||||
|
||||
| 文档 | 主题 |
|
||||
|---|---|
|
||||
| [approval.md](./approval.md) | AI PRO 审批核验流程、确定性网关仲裁规则与语法等级 |
|
||||
| [service.md](./service.md) | 常驻守护进程管理、HTTP 接口与对 hose-use 的跨进程启停控制 |
|
||||
@@ -1,14 +1,14 @@
|
||||
# 合思 AI PRO 确定性审批仲裁网关 (Approval Gateway & AI PRO Guide)
|
||||
# 合思 AI PRO 确定性审批仲裁网关专卷 (Approval Gateway & Rules)
|
||||
|
||||
本参考专卷面向开发者与 AI 智能体,系统说明 `hose-aipro` 命令行、确定性网关仲裁机制与本地规约管理。
|
||||
本参考专卷系统说明 `hose-aipro` 命令行、确定性网关仲裁机制与本地规约管理。
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构与定位
|
||||
|
||||
- **双向命令入口**:可通过独立二进制 `hose-aipro <子命令>` 或统一入口 `hose-use aipro <子命令>` 唤起。
|
||||
- **共享统一上下文**:`hose-aipro` 与 `hose-use` 共享相同的企业租户配置(`~/.config/hose-use/config.json` 与 `enterprises` 凭证目录)。
|
||||
- **零源码阅读自省**:运行 `hose-aipro status` 或 `hose-use context` 即可直接构建完整的运行时上下文,无需翻阅代码。
|
||||
- **独立专属入口**:通过 `hose-aipro <子命令>` 执行所有审批、核验与仲裁动作。
|
||||
- **共享统一上下文**:`hose-aipro` 与 `hose-use` 共享相同的企业租户配置(`~/.config/hose-use/enterprises/` 凭据目录与 `config.json`)。
|
||||
- **零源码阅读自省**:运行 `hose-aipro status` 即可直接构建完整的审批与企业上下文,无需翻阅代码。
|
||||
- **强确定性硬条款阻断**:AI 仅负责事实核验打标(PASS / FAIL / SKIP);下游流转动作(同意 / 驳回 / 转人工)由本地网关根据【硬性 / 弹性 / 建议 / 特殊】分级硬编码规则仲裁,物理切断幻觉可能导致的违规放行。
|
||||
|
||||
---
|
||||
@@ -25,8 +25,6 @@ hose-aipro status --json
|
||||
### 步骤 1:查看规约场景索引库
|
||||
```bash
|
||||
hose-aipro scopes
|
||||
# 或使用 hose-use:
|
||||
hose-use rule scopes
|
||||
```
|
||||
- 输出本地 SQLite 数据库中所有生效场景(如 `#1 差旅报销`、`#2 业务招待`)及规则条数。
|
||||
|
||||
@@ -52,8 +50,8 @@ hose-aipro checklist S26000001
|
||||
|
||||
### 步骤 5:逐项录入事实核验打标
|
||||
```bash
|
||||
# 批量快速打标:
|
||||
hose-aipro review S26000001 --eval "1=PASS:发票合规; 2=FAIL:住宿超标; 3=SKIP"
|
||||
# 批量打标:
|
||||
hose-aipro review S26000001 --findings='[{"index":1,"status":"PASS","evidence":"发票合规"},{"index":2,"status":"FAIL","reasoning":"住宿超标"}]'
|
||||
|
||||
# 单项精准打标:
|
||||
hose-aipro review S26000001 --point 2 --status FAIL --reason "住宿费超过差旅标准 200 元"
|
||||
@@ -0,0 +1,57 @@
|
||||
# hose-aipro 常驻服务与跨进程管理专卷 (Service & Daemon)
|
||||
|
||||
本参考专卷说明 `hose-aipro` 的常驻守护进程体系、HTTP 网关接口与对 `hose-use` 的跨进程管理能力。
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构定位
|
||||
|
||||
`hose-aipro` 拥有独立的常驻后台 HTTP 守护进程(默认端口 `8889`,与 `hose-use` 的 `8888` 隔离):
|
||||
|
||||
- **PID 文件**: `~/.config/hose-use/aipro-service.pid`
|
||||
- **日志文件**: `~/.config/hose-use/aipro-service.log`
|
||||
- **默认监听地址**: `http://127.0.0.1:8889`
|
||||
- **HTTP 接口**:
|
||||
- `GET /`: 返回服务元数据
|
||||
- `GET /health`: 健康探针
|
||||
- `GET /v1/status`: 当前 AI PRO 网关与企业上下文
|
||||
- `POST /api/cli`: HTTP 版 CLI 执行网关
|
||||
|
||||
---
|
||||
|
||||
## 2. hose-aipro 自身服务管理
|
||||
|
||||
```bash
|
||||
# 启动后台常驻网关
|
||||
hose-aipro service start
|
||||
|
||||
# 查看服务运行状态
|
||||
hose-aipro service status
|
||||
hose-aipro service status --json
|
||||
|
||||
# 查看后台运行日志
|
||||
hose-aipro service logs
|
||||
|
||||
# 重启后台服务
|
||||
hose-aipro service restart
|
||||
|
||||
# 停止后台服务
|
||||
hose-aipro service stop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 对本机 hose-use 服务的跨进程管理
|
||||
|
||||
通过 `hose-aipro hose-use <action>` 可以直接控制本机的通用平台守护进程:
|
||||
|
||||
```bash
|
||||
# 启动本机的 hose-use 服务 (端口 8888)
|
||||
hose-aipro hose-use start
|
||||
|
||||
# 查看本机的 hose-use 服务状态
|
||||
hose-aipro hose-use status
|
||||
|
||||
# 停止本机的 hose-use 服务
|
||||
hose-aipro hose-use stop
|
||||
```
|
||||
@@ -2,24 +2,29 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.22
|
||||
version: 0.9.0
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.22)
|
||||
# hose-use (v0.9.0)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
---
|
||||
|
||||
## 本套件结构(先看这里)
|
||||
## 本套件结构与独立配套技能(先看这里)
|
||||
|
||||
本 skill 是**合思/易快报系列的唯一入口**,下级技能不在模型目录中,按需读取:
|
||||
- **`hose-use`(本技能)**:合思企业级 SaaS 底层入口(登录、租户、单据、通讯录、档案、费用类型、角色、待办、自建应用、工作流、应用中心、守护进程)。
|
||||
- **`hose-aipro`(独立配套技能)**:合思 AI PRO 确定性审批仲裁网关(审核要点、事实证据打标、确定性硬门禁仲裁、审批日志)。通过独立命令 `hose-aipro` 运行。
|
||||
- **服务互启互关**:在 `hose-use` 中可通过 `hose-use aipro <start|stop|restart|status>` 管理本机的 `hose-aipro` 常驻服务;反之在 `hose-aipro` 中可通过 `hose-aipro hose-use <start|stop|restart|status>` 管理本机的 `hose-use` 服务。
|
||||
- **单一二进制与统一升级**:`hose-use` 与 `hose-aipro` 由单一多呼叫二进制(Unix Multicall Binary)打包分发,运行 `hose-use update` 或 `hose-aipro update` 均可同时升级两套命令行与对应的两个 Skill。
|
||||
|
||||
| 需要做什么 | 去哪里 |
|
||||
|---|---|
|
||||
| 登录/租户/单据/审批/通讯录/档案/费用类型/角色/待办/应用商店/守护进程 | 本文件下方路由表;细节读 `references/*.md` |
|
||||
| 登录/租户/单据/通讯录/档案/费用类型/角色/待办/应用商店/守护进程 | 本文件下方路由表;细节读 `references/*.md` |
|
||||
| AI PRO 确定性审批仲裁、事实证据打标与要点清单 | 请使用独立配套技能 `hose-aipro` 与命令行 `hose-aipro` |
|
||||
| 本机 AI PRO 审批网关常驻服务管理 | `hose-use aipro <start\|stop\|restart\|status>`;细节读 `references/service.md` |
|
||||
| 写或排错**工作流 MVEL 代码节点**脚本 | `multi/ekuaibao-mvel/SKILL.md` |
|
||||
| **批量开通工作流节点**(从浏览器 curl 提取 token/corpId/baseUrl) | `multi/ekuaibao-nodes/SKILL.md` |
|
||||
|
||||
@@ -92,10 +97,9 @@ metadata:
|
||||
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|
||||
|---|---|---|
|
||||
| 全局运行上下文 / 身份诊断 / 免读源码自省 | `hose-use context [--json]`, `hose-use status` | [references/auth.md](./references/auth.md) |
|
||||
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](./references/approval.md) |
|
||||
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](./references/approval.md) |
|
||||
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](./references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](./references/approval.md) |
|
||||
| AI PRO 确定性审批仲裁全流程 / 事实证据核验 | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [独立技能 hose-aipro](../hose-aipro/SKILL.md) |
|
||||
| 本机 AI PRO 审批网关常驻服务启停与管理 | `hose-use aipro <start\|stop\|restart\|status>` | [references/service.md](./references/service.md) |
|
||||
| 本地审批规约场景与规则管理 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/service.md](./references/service.md) |
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](./references/auth.md) |
|
||||
| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](./references/auth.md) |
|
||||
| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link <url> --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](./references/auth.md) |
|
||||
|
||||
@@ -27,11 +27,16 @@ description: |
|
||||
## 执行
|
||||
|
||||
```bash
|
||||
curl -s -X POST 'https://d9jxeccs5j.sealosgzg.site/hose-workflow-node' \
|
||||
# 网关地址优先取环境变量 HOSE_GRAY_GATEWAY_URL(尾部斜杠会自动忽略),未配置时用内置默认地址
|
||||
GATEWAY="${HOSE_GRAY_GATEWAY_URL:-https://d9jxeccs5j.sealosgzg.site}"
|
||||
curl -s -X POST "${GATEWAY%/}/hose-workflow-node" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}'
|
||||
```
|
||||
|
||||
> 网关托管在第三方域,实例可能被回收或迁移。CLI 侧同样支持 `HOSE_GRAY_GATEWAY_URL` 覆盖;
|
||||
> 网关不可用时不要自行改用其他地址,先确认变量指向的实例仍然有效。
|
||||
|
||||
可选参数:
|
||||
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
|
||||
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
| [auth.md](./auth.md) | 登录、企业身份与运行模式 |
|
||||
| [assist-platform.md](./assist-platform.md) | 协助平台、工单及代客登录 |
|
||||
| [bill.md](./bill.md) | 单据、费用明细、复制与写入操作 |
|
||||
| [approval.md](./approval.md) | AI PRO 确定性审批与规则 |
|
||||
| [workflow.md](./workflow.md) | 自建应用、工作流、节点、调试和恢复 |
|
||||
| [contact.md](./contact.md) | 通讯录与员工档案 |
|
||||
| [dimension.md](./dimension.md) | 自定义档案和核算维度 |
|
||||
|
||||
@@ -42,6 +42,25 @@ hose-use service poll --corp=<corpId>
|
||||
hose-use service poll --corp=<corpId> --limit=100 --json
|
||||
```
|
||||
|
||||
### 管理本机配套的 hose-aipro 服务 (`hose-use aipro`)
|
||||
|
||||
在 `hose-use` 中可直接管理本机的 `hose-aipro` 审批网关守护进程:
|
||||
|
||||
```bash
|
||||
# 启动本机配套的 hose-aipro 审批网关常驻服务 (默认端口 8889)
|
||||
hose-use aipro start
|
||||
|
||||
# 查看 hose-aipro 服务状态
|
||||
hose-use aipro status
|
||||
|
||||
# 查看 hose-aipro 服务日志
|
||||
hose-use aipro logs
|
||||
|
||||
# 重启 / 停止 hose-aipro 服务
|
||||
hose-use aipro restart
|
||||
hose-use aipro stop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 前台 HTTP 服务 (`http` / `serve`)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.22
|
||||
version: 0.9.0
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.22",
|
||||
"version": "0.9.0",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -3,6 +3,13 @@ import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeDatabase, getDatabase } from "./core/db/index.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
import { COMMAND_METADATA } from "./cli/command-metadata.js";
|
||||
import {
|
||||
AIPRO_COMMAND_REGISTRY,
|
||||
findAiProCommand,
|
||||
isSaasPlatformCommand,
|
||||
SAAS_PLATFORM_COMMANDS,
|
||||
} from "./cli/aipro-registry.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
beforeEach(() => {
|
||||
@@ -159,4 +166,60 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
expect(blockReject.stderr).toContain("不存在任何【硬性】或【弹性】违规条款");
|
||||
expect(blockReject.stderr).toContain("严禁无故或恶意驳回");
|
||||
});
|
||||
|
||||
test("二级公共命令一致性:update、skill 与 service 正常执行", async () => {
|
||||
// 1. update --dry-run
|
||||
const updateRes = await runAiProCli(["update", "--dry-run", "--json"]);
|
||||
expect(updateRes.exitCode).toBe(0);
|
||||
const updateData = JSON.parse(updateRes.stdout);
|
||||
expect(updateData.dryRun).toBe(true);
|
||||
|
||||
// 2. skill status
|
||||
const skillRes = await runAiProCli(["skill", "status", "--json"]);
|
||||
expect(skillRes.exitCode).toBe(0);
|
||||
const skillData = JSON.parse(skillRes.stdout);
|
||||
expect(skillData["hose-use"]).toBeDefined();
|
||||
expect(skillData["hose-aipro"]).toBeDefined();
|
||||
|
||||
// 3. service status (hose-aipro 自身)
|
||||
const serviceRes = await runAiProCli(["service", "status", "--json"]);
|
||||
expect(serviceRes.exitCode).toBe(0);
|
||||
const serviceData = JSON.parse(serviceRes.stdout);
|
||||
expect(serviceData.serviceName).toBe("hose-aipro");
|
||||
expect(serviceData.port).toBe(8889);
|
||||
|
||||
// 4. hose-use 服务跨进程管理 (hose-aipro hose-use status)
|
||||
const peerRes = await runAiProCli(["hose-use", "status", "--json"]);
|
||||
expect(peerRes.exitCode).toBe(0);
|
||||
const peerData = JSON.parse(peerRes.stdout);
|
||||
expect(peerData.serviceName).toBe("hose-use");
|
||||
expect(peerData.port).toBe(8888);
|
||||
|
||||
// 5. SaaS 命令在 hose-aipro 下友好重定向提示
|
||||
const billRes = await runAiProCli(["bill", "list"]);
|
||||
expect(billRes.exitCode).toBe(1);
|
||||
expect(billRes.stderr).toContain("属于合思企业平台能力,由 hose-use 命令行提供");
|
||||
});
|
||||
|
||||
test("声明式注册表规范性:所有命令与别名同元数据严格对齐", () => {
|
||||
const meta = COMMAND_METADATA["hose-aipro"];
|
||||
expect(meta).toBeDefined();
|
||||
|
||||
// 1. 注册表中的每一个命令都在 metadata.commands 中有说明
|
||||
for (const cmd of AIPRO_COMMAND_REGISTRY) {
|
||||
expect(meta.commands[cmd.name]).toBeDefined();
|
||||
}
|
||||
|
||||
// 2. 所有的别名都能正确通过 findAiProCommand 查找到原命令
|
||||
for (const [alias, canonical] of Object.entries(meta.commandAliases)) {
|
||||
const def = findAiProCommand(alias);
|
||||
expect(def).toBeDefined();
|
||||
expect(def?.name).toBe(canonical);
|
||||
}
|
||||
|
||||
// 3. 所有的 SaaS 重定向命令都正确标记
|
||||
for (const saasCmd of SAAS_PLATFORM_COMMANDS) {
|
||||
expect(isSaasPlatformCommand(saasCmd)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
+31
-82
@@ -9,21 +9,12 @@ import {
|
||||
ApprovalRepository,
|
||||
ApprovalGatewayBlockedError,
|
||||
} from "./domains/approval/index.js";
|
||||
import { formatVersionLabel, getVersionInfo } from "./version.js";
|
||||
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./cli/commands/aipro/status.js";
|
||||
import {
|
||||
handleAiProChecklist,
|
||||
handleAiProPoints,
|
||||
handleAiProRules,
|
||||
handleAiProScopes,
|
||||
} from "./cli/commands/aipro/rules.js";
|
||||
import {
|
||||
handleAiProBind,
|
||||
handleAiProDecide,
|
||||
handleAiProInit,
|
||||
handleAiProReview,
|
||||
handleAiProTranslate,
|
||||
} from "./cli/commands/aipro/session.js";
|
||||
findAiProCommand,
|
||||
isSaasPlatformCommand,
|
||||
handleSaasPlatformRedirect,
|
||||
} from "./cli/aipro-registry.js";
|
||||
import { handleAiProHelp } from "./cli/commands/aipro/status.js";
|
||||
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
|
||||
export async function runAiProCli(
|
||||
@@ -51,10 +42,21 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
const corp = runtime.selectedCorp;
|
||||
const previewPositional = parsed.positional || [];
|
||||
const previewCommand = (previewPositional[0] || "help").toLowerCase();
|
||||
const mutating = ["init", "start", "bind", "mount", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(previewCommand) || (["points", "clauses"].includes(previewCommand) && previewPositional.length >= 3);
|
||||
if (mutating && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview({ ...parsed, raw: ["aipro", ...rawArgs] }, runtime, "预览 AI PRO 审批操作", stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定", { action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
|
||||
const previewDef = findAiProCommand(previewCommand);
|
||||
const isMutating = typeof previewDef?.mutating === "function"
|
||||
? previewDef.mutating(parsed, previewPositional)
|
||||
: Boolean(previewDef?.mutating);
|
||||
|
||||
if (isMutating && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
{ ...parsed, raw: ["hose-aipro", ...rawArgs] },
|
||||
runtime,
|
||||
"预览 AI PRO 审批操作",
|
||||
stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定",
|
||||
{ action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) }
|
||||
);
|
||||
}
|
||||
|
||||
const repo = new ApprovalRepository();
|
||||
const service = new ApprovalService(repo);
|
||||
let cachedSession: Awaited<ReturnType<typeof getSessionClientForRuntime>> | undefined;
|
||||
@@ -95,74 +97,21 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson(getVersionInfo("hose-aipro")) + "\n"
|
||||
: `${formatVersionLabel("hose-aipro")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
if (booleanOption(parsed.options, ["version", "v"])) {
|
||||
const versionDef = findAiProCommand("version");
|
||||
if (versionDef) return await versionDef.handler(ctx);
|
||||
}
|
||||
|
||||
switch (command) {
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "context":
|
||||
case "info":
|
||||
return await handleAiProStatus(ctx);
|
||||
|
||||
case "init":
|
||||
case "start":
|
||||
return await handleAiProInit(ctx);
|
||||
|
||||
case "scopes":
|
||||
case "index":
|
||||
case "indexes":
|
||||
return await handleAiProScopes(ctx);
|
||||
|
||||
case "translate":
|
||||
case "doc":
|
||||
case "markdown":
|
||||
case "render":
|
||||
return await handleAiProTranslate(ctx);
|
||||
|
||||
case "rules":
|
||||
case "rule":
|
||||
return await handleAiProRules(ctx);
|
||||
|
||||
case "bind":
|
||||
case "mount":
|
||||
return await handleAiProBind(ctx);
|
||||
|
||||
case "points":
|
||||
case "clauses":
|
||||
return await handleAiProPoints(ctx);
|
||||
|
||||
case "checklist":
|
||||
case "list":
|
||||
return await handleAiProChecklist(ctx);
|
||||
|
||||
case "review":
|
||||
case "eval":
|
||||
case "evaluate":
|
||||
return await handleAiProReview(ctx);
|
||||
|
||||
case "decide":
|
||||
case "approve":
|
||||
case "reject":
|
||||
return await handleAiProDecide(ctx);
|
||||
|
||||
case "logs":
|
||||
case "log":
|
||||
case "history":
|
||||
case "trail":
|
||||
return await handleAiProLogs(ctx);
|
||||
|
||||
case "help":
|
||||
default:
|
||||
return handleAiProHelp(ctx);
|
||||
const commandDef = findAiProCommand(command);
|
||||
if (commandDef) {
|
||||
return await commandDef.handler(ctx);
|
||||
}
|
||||
|
||||
if (isSaasPlatformCommand(command)) {
|
||||
return handleSaasPlatformRedirect(command, positional);
|
||||
}
|
||||
|
||||
return await handleAiProHelp(ctx);
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
repo.logAiProAction({
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
## 文件职责
|
||||
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)及统一导出。新增命令先声明元数据,再在此注册处理器。
|
||||
- `aipro-registry.ts`:`AIPRO_COMMAND_REGISTRY` AI PRO 确定性审批命令的声明式注册表(命令名称、别名、突变标记 `mutating`、处理器 `handler`)与 SaaS 重定向判定。与 `registry.ts` 保持完全一致的声明式设计。
|
||||
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./commands/aipro/status.js";
|
||||
import {
|
||||
handleAiProChecklist,
|
||||
handleAiProPoints,
|
||||
handleAiProRules,
|
||||
handleAiProScopes,
|
||||
} from "./commands/aipro/rules.js";
|
||||
import {
|
||||
handleAiProBind,
|
||||
handleAiProDecide,
|
||||
handleAiProInit,
|
||||
handleAiProReview,
|
||||
handleAiProTranslate,
|
||||
} from "./commands/aipro/session.js";
|
||||
import { handleUpdateCommand } from "./commands/update/index.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { formatVersionLabel, getVersionInfo } from "../version.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import type { AiProExecutionContext } from "./commands/aipro/types.js";
|
||||
import type { CliParsedArgs, CliResult } from "./types.js";
|
||||
|
||||
export type AiProMutatingCheck =
|
||||
| boolean
|
||||
| ((parsed: CliParsedArgs, positional: string[]) => boolean);
|
||||
|
||||
export interface AiProCommandDefinition {
|
||||
name: string;
|
||||
summary: string;
|
||||
aliases?: readonly string[];
|
||||
mutating?: AiProMutatingCheck;
|
||||
handler: (ctx: AiProExecutionContext) => Promise<CliResult> | CliResult;
|
||||
}
|
||||
|
||||
export const AIPRO_COMMAND_REGISTRY: readonly AiProCommandDefinition[] = [
|
||||
{
|
||||
name: "status",
|
||||
summary: "查看网关状态",
|
||||
aliases: ["whoami", "context", "info"],
|
||||
handler: (ctx) => handleAiProStatus(ctx),
|
||||
},
|
||||
{
|
||||
name: "init",
|
||||
summary: "初始化审批上下文",
|
||||
aliases: ["start"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProInit(ctx),
|
||||
},
|
||||
{
|
||||
name: "scopes",
|
||||
summary: "列出审批规则场景",
|
||||
aliases: ["index", "indexes"],
|
||||
handler: (ctx) => handleAiProScopes(ctx),
|
||||
},
|
||||
{
|
||||
name: "translate",
|
||||
summary: "转译单据",
|
||||
aliases: ["doc", "markdown", "render"],
|
||||
handler: (ctx) => handleAiProTranslate(ctx),
|
||||
},
|
||||
{
|
||||
name: "rules",
|
||||
summary: "查看审批规则",
|
||||
aliases: ["rule"],
|
||||
handler: (ctx) => handleAiProRules(ctx),
|
||||
},
|
||||
{
|
||||
name: "bind",
|
||||
summary: "绑定单据",
|
||||
aliases: ["mount"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProBind(ctx),
|
||||
},
|
||||
{
|
||||
name: "points",
|
||||
summary: "查看审核要点",
|
||||
aliases: ["clauses"],
|
||||
mutating: (_parsed, positional) => positional.length >= 3,
|
||||
handler: (ctx) => handleAiProPoints(ctx),
|
||||
},
|
||||
{
|
||||
name: "checklist",
|
||||
summary: "查看核验清单",
|
||||
aliases: ["list"],
|
||||
handler: (ctx) => handleAiProChecklist(ctx),
|
||||
},
|
||||
{
|
||||
name: "review",
|
||||
summary: "核验要点",
|
||||
aliases: ["eval", "evaluate"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProReview(ctx),
|
||||
},
|
||||
{
|
||||
name: "decide",
|
||||
summary: "执行仲裁",
|
||||
aliases: ["approve", "reject"],
|
||||
mutating: true,
|
||||
handler: (ctx) => handleAiProDecide(ctx),
|
||||
},
|
||||
{
|
||||
name: "logs",
|
||||
summary: "查看审批日志",
|
||||
aliases: ["log", "history", "trail"],
|
||||
handler: (ctx) => handleAiProLogs(ctx),
|
||||
},
|
||||
{
|
||||
name: "service",
|
||||
summary: "管理本机 hose-aipro 常驻服务",
|
||||
aliases: ["daemon"],
|
||||
handler: async (ctx) => {
|
||||
const subTarget = ctx.positional[1]?.toLowerCase();
|
||||
if (subTarget === "hose-use" || subTarget === "hose") {
|
||||
return handleServiceCommand(
|
||||
{ ...ctx.parsed, action: ctx.positional[2] || "status", args: ctx.positional.slice(3) },
|
||||
ctx.runtime,
|
||||
"hose-use"
|
||||
);
|
||||
}
|
||||
return handleServiceCommand(
|
||||
{ ...ctx.parsed, action: ctx.positional[1] || "status", args: ctx.positional.slice(2) },
|
||||
ctx.runtime,
|
||||
"hose-aipro"
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "hose-use",
|
||||
summary: "管理本机 hose-use 常驻服务",
|
||||
aliases: ["hose"],
|
||||
handler: async (ctx) => {
|
||||
const subAction = (ctx.positional[1] || "status").toLowerCase();
|
||||
const serviceActions = ["start", "stop", "restart", "status", "logs", "log", "run"];
|
||||
if (serviceActions.includes(subAction)) {
|
||||
return handleServiceCommand(
|
||||
{ ...ctx.parsed, action: subAction, args: ctx.positional.slice(2) },
|
||||
ctx.runtime,
|
||||
"hose-use"
|
||||
);
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] 运行 hose-use ${subAction} 可直接调用合思企业平台命令。\n` +
|
||||
`如需管理本机的 hose-use 常驻服务,请运行:\n` +
|
||||
` hose-aipro hose-use <start|stop|restart|status|logs>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
summary: "检查并升级版本",
|
||||
aliases: ["self-update"],
|
||||
handler: async (ctx) => handleUpdateCommand(ctx.parsed, ctx.runtime),
|
||||
},
|
||||
{
|
||||
name: "skill",
|
||||
summary: "管理 Agent 技能",
|
||||
aliases: ["skills"],
|
||||
handler: async (ctx) => handleSkillCommand(ctx.parsed, ctx.runtime),
|
||||
},
|
||||
{
|
||||
name: "version",
|
||||
summary: "查看版本信息",
|
||||
aliases: ["v"],
|
||||
handler: async (ctx) => ({
|
||||
stdout: ctx.jsonMode
|
||||
? printJson(getVersionInfo("hose-aipro")) + "\n"
|
||||
: `${formatVersionLabel("hose-aipro")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "help",
|
||||
summary: "查看帮助说明",
|
||||
handler: (ctx) => handleAiProHelp(ctx),
|
||||
},
|
||||
];
|
||||
|
||||
const aiproCommandMap = new Map<string, AiProCommandDefinition>();
|
||||
for (const def of AIPRO_COMMAND_REGISTRY) {
|
||||
aiproCommandMap.set(def.name.toLowerCase(), def);
|
||||
for (const alias of def.aliases || []) {
|
||||
aiproCommandMap.set(alias.toLowerCase(), def);
|
||||
}
|
||||
}
|
||||
|
||||
export function findAiProCommand(name: string): AiProCommandDefinition | undefined {
|
||||
return aiproCommandMap.get(name.toLowerCase());
|
||||
}
|
||||
|
||||
export const SAAS_PLATFORM_COMMANDS = [
|
||||
"bill",
|
||||
"flow",
|
||||
"workflow",
|
||||
"platform",
|
||||
"datalink",
|
||||
"auth",
|
||||
"corps",
|
||||
"contact",
|
||||
"feetype",
|
||||
"dimension",
|
||||
"role",
|
||||
"permission",
|
||||
"keys",
|
||||
"store",
|
||||
"message",
|
||||
"task",
|
||||
"config",
|
||||
"mcp",
|
||||
"assist-platform",
|
||||
] as const;
|
||||
|
||||
export function isSaasPlatformCommand(command: string): boolean {
|
||||
return (SAAS_PLATFORM_COMMANDS as readonly string[]).includes(command.toLowerCase());
|
||||
}
|
||||
|
||||
export function handleSaasPlatformRedirect(
|
||||
command: string,
|
||||
positional: string[] = []
|
||||
): CliResult {
|
||||
const subArgs = positional.slice(1).join(" ");
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] ${command} 属于合思企业平台能力,由 hose-use 命令行提供。\n` +
|
||||
`请直接运行: hose-use ${command}${subArgs ? ` ${subArgs}` : ""}\n\n` +
|
||||
`如需管理本机的 hose-use 常驻服务,请运行:\n` +
|
||||
` hose-aipro hose-use <start|stop|restart|status|logs>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -5,10 +5,12 @@ import { tmpdir } from "node:os";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
import { runCli } from "./runner.js";
|
||||
import { closeDatabase } from "../core/db/index.js";
|
||||
|
||||
const keys = ["HOSE_APPROVAL_DB", "HOSE_ENTERPRISES_DIR", "HOSE_CONFIG_FILE"] as const;
|
||||
const original = keys.map(key => process.env[key]);
|
||||
afterEach(() => { closeDatabase(); keys.forEach((key, i) => { if (original[i] === undefined) delete process.env[key]; else process.env[key] = original[i]; }); });
|
||||
test("approval and aipro dry-runs override apply/yes without requests or database creation", async () => {
|
||||
|
||||
test("aipro dry-runs override apply/yes without requests or database creation", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-approval-preview-"));
|
||||
const corps = join(root, "corps"); mkdirSync(corps);
|
||||
writeFileSync(join(corps, "corp.json"), JSON.stringify({ id: "corp", name: "Preview", source: "manual", credentials: { accessToken: "fixture", corpId: "corp", staffId: "staff" } }));
|
||||
@@ -19,15 +21,16 @@ test("approval and aipro dry-runs override apply/yes without requests or databas
|
||||
let requests = 0;
|
||||
globalThis.fetch = (async () => { requests++; throw new Error("No network during preview"); }) as any;
|
||||
try {
|
||||
for (const action of ["points", "review", "decide", "approve", "reject"]) {
|
||||
const result = await runCli(["approval", action, "SN", "--apply", "--yes", "--dry-run", "--json"]);
|
||||
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
}
|
||||
for (const action of ["init", "bind", "review", "decide", "approve", "reject"]) {
|
||||
const result = await runAiProCli([action, "approve", "--run", "ABC123", "--apply", "--yes", "--dry-run", "--json"]);
|
||||
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-use aipro ");
|
||||
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-aipro ");
|
||||
}
|
||||
// hose-use approval 重定向测试
|
||||
const redirect = await runCli(["approval", "decide", "S123"]);
|
||||
expect(redirect.exitCode).toBe(1);
|
||||
expect(redirect.stderr).toContain("hose-aipro");
|
||||
|
||||
expect(requests).toBe(0); expect(existsSync(process.env.HOSE_APPROVAL_DB)).toBe(false);
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
+71
-16
@@ -32,20 +32,23 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
flags: { ...flagList("offline cached", "boolean") }
|
||||
},
|
||||
"aipro": {
|
||||
"summary": "AI PRO 确定性审批仲裁",
|
||||
"usage": "hose-use aipro <子命令>",
|
||||
"summary": "管理本机 hose-aipro 审批网关常驻服务",
|
||||
"usage": "hose-use aipro <start|stop|restart|status|logs>",
|
||||
"commands": {
|
||||
"status": "查看网关状态",
|
||||
"bind": "绑定单据",
|
||||
"review": "核验要点",
|
||||
"decide": "执行仲裁",
|
||||
"init": "初始化审批上下文",
|
||||
"scopes": "列出审批规则场景",
|
||||
"translate": "转译单据",
|
||||
"rules": "查看审批规则",
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"logs": "查看审批日志",
|
||||
"start": "启动本机 hose-aipro 网关服务",
|
||||
"stop": "停止本机 hose-aipro 网关服务",
|
||||
"restart": "重启本机 hose-aipro 网关服务",
|
||||
"status": "查看本机 hose-aipro 网关服务状态",
|
||||
"logs": "查看本机 hose-aipro 网关服务日志",
|
||||
"bind": "绑定单据 (已独立为 hose-aipro bind)",
|
||||
"review": "核验要点 (已独立为 hose-aipro review)",
|
||||
"decide": "执行仲裁 (已独立为 hose-aipro decide)",
|
||||
"init": "初始化审批会话 (已独立为 hose-aipro init)",
|
||||
"scopes": "列出审批规则场景 (已独立为 hose-aipro scopes)",
|
||||
"translate": "转译单据 (已独立为 hose-aipro translate)",
|
||||
"rules": "查看审批规则 (已独立为 hose-aipro rules)",
|
||||
"points": "查看审核要点 (已独立为 hose-aipro points)",
|
||||
"checklist": "查看核验清单 (已独立为 hose-aipro checklist)",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [],
|
||||
@@ -71,7 +74,59 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"history": "logs",
|
||||
"trail": "logs"
|
||||
},
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings i id index indexes limit m message n opinion p point proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings host i id index indexes limit m message n opinion p point port proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
},
|
||||
"hose-aipro": {
|
||||
"summary": "合思 AI PRO 确定性审批仲裁网关",
|
||||
"usage": "hose-aipro <子命令>",
|
||||
"commands": {
|
||||
"status": "查看网关状态",
|
||||
"bind": "绑定单据",
|
||||
"review": "核验要点",
|
||||
"decide": "执行仲裁",
|
||||
"init": "初始化审批上下文",
|
||||
"scopes": "列出审批规则场景",
|
||||
"translate": "转译单据",
|
||||
"rules": "查看审批规则",
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"logs": "查看审批日志",
|
||||
"service": "管理本机 hose-aipro 常驻服务",
|
||||
"hose-use": "管理本机 hose-use 常驻服务",
|
||||
"update": "检查并升级版本",
|
||||
"skill": "管理 Agent 技能",
|
||||
"version": "查看版本信息",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"context": "status",
|
||||
"info": "status",
|
||||
"start": "init",
|
||||
"index": "scopes",
|
||||
"indexes": "scopes",
|
||||
"doc": "translate",
|
||||
"markdown": "translate",
|
||||
"render": "translate",
|
||||
"rule": "rules",
|
||||
"mount": "bind",
|
||||
"clauses": "points",
|
||||
"list": "checklist",
|
||||
"eval": "review",
|
||||
"evaluate": "review",
|
||||
"approve": "decide",
|
||||
"reject": "decide",
|
||||
"log": "logs",
|
||||
"history": "logs",
|
||||
"trail": "logs",
|
||||
"self-update": "update",
|
||||
"skills": "skill",
|
||||
"daemon": "service",
|
||||
"hose": "hose-use",
|
||||
"v": "version"
|
||||
},
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings host i id index indexes limit m message n opinion p point port proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
},
|
||||
"auth": {
|
||||
"summary": "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
@@ -869,11 +924,11 @@ export function localCommandFlags(area?: string, action?: string): Record<string
|
||||
|| (["bill", "flow"].includes(resolved?.area || "") && ["list", "link"].includes(canonical || "list"))
|
||||
|| (resolved?.area === "workflow" && canonical === "node")
|
||||
|| (resolved?.area === "platform" && canonical === "record")
|
||||
|| (resolved?.area === "aipro" && canonical === "bind");
|
||||
|| (["aipro", "hose-aipro"].includes(resolved?.area || "") && canonical === "bind");
|
||||
if (!localC) delete flags.c;
|
||||
if (resolved?.area === "workflow" && canonical === "create") flags.f = "value";
|
||||
// --run historically accepts a session ID and, for decide, an apply boolean.
|
||||
if (resolved?.area === "aipro" && canonical === "decide") flags.run = "boolean-or-value";
|
||||
if (["aipro", "hose-aipro"].includes(resolved?.area || "") && canonical === "decide") flags.run = "boolean-or-value";
|
||||
return flags;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,335 +0,0 @@
|
||||
import { isDryRun, mutationPreview } from "../mutation.js";
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
ApprovalGatewayBlockedError,
|
||||
FindingCheckStatus,
|
||||
} from "../../domains/approval/index.js";
|
||||
|
||||
export async function handleApprovalCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
// 解析命令层级:
|
||||
// 形式 A: hose-use approval audit points S26000001
|
||||
// 形式 B: hose-use approval points S26000001
|
||||
// 形式 C: hose-use approval audit S26000001
|
||||
let subAction = parsed.action?.toLowerCase();
|
||||
let args = [...parsed.args];
|
||||
|
||||
if (subAction === "audit" && args.length > 0) {
|
||||
const candidateSub = args[0]?.toLowerCase();
|
||||
if (["points", "inject", "checklist", "list", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(candidateSub)) {
|
||||
subAction = candidateSub;
|
||||
args.shift();
|
||||
}
|
||||
}
|
||||
|
||||
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
|
||||
|
||||
if (targetSn && isDryRun(parsed, runtime) && ["audit", "points", "inject", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(subAction || "audit")) {
|
||||
return mutationPreview(parsed, runtime, "预览审批操作", targetSn, { action: subAction || "audit", corpId, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
|
||||
}
|
||||
const client = await createSessionClient(corp);
|
||||
const service = new ApprovalService();
|
||||
|
||||
switch (subAction) {
|
||||
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
|
||||
case "points":
|
||||
case "inject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号或单据 ID: hose-use approval audit points <单号>");
|
||||
}
|
||||
|
||||
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
|
||||
const result = await service.injectAuditPoints(client, corpId, targetSn, {
|
||||
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
sn: result.bill.billCode,
|
||||
scope: result.scope,
|
||||
runId: result.run.id,
|
||||
count: result.findings.length,
|
||||
findings: result.findings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
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 = `====== 单据 ${result.bill.billCode} 明细级审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
|
||||
const tip =
|
||||
`\n[要点注入完成] 审核要点已固化至审批实例,审批链路已激活!\n` +
|
||||
`下一步: 请对要点进行事实核验判定: hose-use approval audit review ${result.bill.billCode} --eval "1=PASS; 2=FAIL:证据说明; ..."\n` +
|
||||
`完成核验后,由确定性网关仲裁审批: hose-use approval audit decide ${result.bill.billCode} --apply --yes\n`;
|
||||
|
||||
return {
|
||||
stdout: title + table + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 2. 查看当前审核要点清单与核验状态 ─────────────────────────────────────
|
||||
case "checklist":
|
||||
case "list":
|
||||
case "status": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
|
||||
}
|
||||
|
||||
const { run, findings } = service.getAuditChecklist(targetSn, corpId);
|
||||
if (!run || findings.length === 0) {
|
||||
const errorMsg =
|
||||
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`审批链路当前物理不通!请先执行: hose-use approval audit points ${targetSn} 注入审核要点清单。\n`;
|
||||
return { stdout: "", stderr: errorMsg, exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ run, findings }, runtime.outputOptions),
|
||||
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 = `====== 单据 ${targetSn} 审核要点核验进度 (总计: ${findings.length} | 待核验: ${pendingCount} | 运行决策: ${run.decision}) ======\n`;
|
||||
|
||||
return {
|
||||
stdout: title + table,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 3. 逐项核验事实打标 ──────────────────────────────────────────────────
|
||||
case "review":
|
||||
case "eval":
|
||||
case "evaluate": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-use approval audit review <单号> --eval '...'");
|
||||
}
|
||||
|
||||
const evalStr = stringOption(parsed.options, ["eval", "findings", "data", "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", "r"]);
|
||||
|
||||
const updates: Array<{
|
||||
index?: number;
|
||||
id?: string;
|
||||
status: FindingCheckStatus;
|
||||
evidence?: string;
|
||||
reasoning?: string;
|
||||
}> = [];
|
||||
|
||||
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
|
||||
updates.push({
|
||||
index: pointIndex,
|
||||
status: statusInput,
|
||||
evidence,
|
||||
reasoning,
|
||||
});
|
||||
} else if (evalStr) {
|
||||
// 解析便捷语法: "1=FAIL:未上传发票; 2=PASS; 3=SKIP; 4=FAIL:大连住宿超标且无特批"
|
||||
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
|
||||
if (match) {
|
||||
const idx = parseInt(match[1], 10);
|
||||
const status = match[2].toUpperCase() as FindingCheckStatus;
|
||||
const desc = match[3]?.trim();
|
||||
updates.push({
|
||||
index: idx,
|
||||
status,
|
||||
evidence: desc,
|
||||
reasoning: desc,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
throw new Error(
|
||||
`请提供核验判定参数,例如:\n` +
|
||||
` hose-use approval audit review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
|
||||
` 或: hose-use approval audit review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, corpId);
|
||||
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
|
||||
const rows = updatedFindings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
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 = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const msg =
|
||||
`====== 单据 ${targetSn} 核验判定已更新 (待核验剩余: ${pendingCount} 项) ======\n` +
|
||||
table +
|
||||
(pendingCount === 0
|
||||
? `\n[核验全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-use approval audit decide ${targetSn} --apply --yes\n`
|
||||
: `\n[待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
|
||||
|
||||
return { stdout: msg, stderr: "", exitCode: 0 };
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
return { stdout: "", stderr: `${err.message}\n`, exitCode: 1 };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 4. 确定性网关仲裁与审批决断 ──────────────────────────────────────────
|
||||
case "decide":
|
||||
case "approve":
|
||||
case "reject": {
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-use approval audit decide <单号> [--apply] [--yes]");
|
||||
}
|
||||
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
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("网关将向合思系统真实执行审批/驳回/留痕,确认继续?输入 yes: ");
|
||||
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
|
||||
}
|
||||
}
|
||||
|
||||
const requestedAction = subAction === "approve" ? "approve" : subAction === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
|
||||
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
|
||||
|
||||
try {
|
||||
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
|
||||
requestedAction,
|
||||
apply,
|
||||
comment: userComment,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(decisionResult, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outLines: string[] = [];
|
||||
outLines.push(`\n====== 合思 AI 确定性网关仲裁裁决书 (单号: ${targetSn}) ======`);
|
||||
outLines.push(`网关决策 : ${decisionResult.decision}`);
|
||||
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
|
||||
if (apply) {
|
||||
outLines.push(`下游动作 : 已安全执行 [${decisionResult.appliedAction}] 动作`);
|
||||
} else {
|
||||
outLines.push(`执行模式 : 预审仿真 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
|
||||
}
|
||||
outLines.push(`\n--- 审计意见文本快照 ---\n${decisionResult.decisionSummary}\n`);
|
||||
|
||||
return {
|
||||
stdout: outLines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `\n${err.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 5. 缺省:智能引导 (未注入则出要点,已注入则显示清单) ─────────────────────
|
||||
case "audit":
|
||||
case undefined: {
|
||||
if (!targetSn) {
|
||||
return {
|
||||
stdout:
|
||||
`====== 合思 AI 确定性审批网关 (hose-use approval) ======\n` +
|
||||
`用法:\n` +
|
||||
` 1. 出明细级审核要点 (规则注入) : hose-use approval audit points <单号> [--scope <场景>]\n` +
|
||||
` 2. 查看当前审核要点清单 : hose-use approval audit checklist <单号>\n` +
|
||||
` 3. 逐项录入事实核验判定 : hose-use approval audit review <单号> --eval "1=PASS; 2=FAIL:说明"\n` +
|
||||
` 4. 网关确定性仲裁与执行审批 : hose-use approval audit decide <单号> [--apply] [--yes]\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 检查当前是否已注入要点
|
||||
const { run } = service.getAuditChecklist(targetSn, corpId);
|
||||
if (!run) {
|
||||
// 自动触发第一步:注入并出审核要点
|
||||
return await handleApprovalCommand(
|
||||
{ ...parsed, action: "points", args: [targetSn] },
|
||||
runtime
|
||||
);
|
||||
} else {
|
||||
// 已有要点,展示清单与进度
|
||||
return await handleApprovalCommand(
|
||||
{ ...parsed, action: "checklist", args: [targetSn] },
|
||||
runtime
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知的审批网关动作: ${subAction}。请运行 hose-use approval audit 查看帮助。`);
|
||||
}
|
||||
}
|
||||
@@ -79,13 +79,14 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
expect(data.sessions).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use aipro status 双向桥接成功转发", async () => {
|
||||
test("hose-use aipro status 管理本机 aipro 守护进程状态", async () => {
|
||||
const res = await runCli(["aipro", "status", "--json"]);
|
||||
expect(res.exitCode).toBe(0);
|
||||
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.tool).toBe("hose-aipro");
|
||||
expect(data.ruleEngine.scopesCount).toBe(2);
|
||||
expect(data.serviceName).toBe("hose-aipro");
|
||||
expect(data.port).toBe(8889);
|
||||
expect(data.running).toBe(false);
|
||||
});
|
||||
|
||||
test("hose-aipro 帮助页在顶部动态展示当前企业页眉", async () => {
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { expect, spyOn, test } from "bun:test";
|
||||
import * as service from "../service.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { handleServiceCommand } from "./service.js";
|
||||
import {
|
||||
handleServiceCommand,
|
||||
handleAiProServiceCommand,
|
||||
handleApprovalRedirectCommand,
|
||||
} from "./service.js";
|
||||
|
||||
test("service lifecycle previews never dispatch process or state mutations", async () => {
|
||||
const dispatch = spyOn(service, "runServiceCommand").mockResolvedValue({ running: false } as any);
|
||||
try {
|
||||
@@ -13,5 +18,19 @@ test("service lifecycle previews never dispatch process or state mutations", asy
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
await handleServiceCommand(parseArgs(["service", "status"]), { jsonMode: true } as any);
|
||||
expect(dispatch).toHaveBeenCalledTimes(1);
|
||||
|
||||
// hose-use aipro status
|
||||
await handleAiProServiceCommand(parseArgs(["aipro", "status"]), { jsonMode: true } as any);
|
||||
expect(dispatch).toHaveBeenCalledTimes(2);
|
||||
|
||||
// hose-use aipro bind 重定向阻断提示
|
||||
const bindRedirect = await handleAiProServiceCommand(parseArgs(["aipro", "bind", "S123"]), { jsonMode: true } as any);
|
||||
expect(bindRedirect.exitCode).toBe(1);
|
||||
expect(bindRedirect.stderr).toContain("hose-aipro");
|
||||
|
||||
// hose-use approval 重定向提示
|
||||
const approvalRedirect = await handleApprovalRedirectCommand(parseArgs(["approval", "decide", "S123"]), { jsonMode: true } as any);
|
||||
expect(approvalRedirect.exitCode).toBe(1);
|
||||
expect(approvalRedirect.stderr).toContain("hose-aipro");
|
||||
} finally { dispatch.mockRestore(); }
|
||||
});
|
||||
+100
-21
@@ -1,8 +1,14 @@
|
||||
import { isDryRun, mutationPreview } from "../mutation.js";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../service.js";
|
||||
import {
|
||||
runServiceCommand,
|
||||
getHoseUseServiceConfig,
|
||||
getAiProServiceConfig,
|
||||
getPidFile,
|
||||
getLogFile,
|
||||
SERVICE_STATE_DIR,
|
||||
type ServiceConfig,
|
||||
type ServiceTargetName,
|
||||
} from "../service.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
@@ -10,13 +16,30 @@ import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { EventStore } from "../../domains/events/store.js";
|
||||
import { pollEvents } from "../../domains/events/poller.js";
|
||||
|
||||
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
export { SERVICE_STATE_DIR };
|
||||
|
||||
export async function handleServiceCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
runtime: CliRuntime,
|
||||
forcedTarget?: ServiceTargetName
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || parsed.args[0] || "status";
|
||||
const firstPos = (parsed.action || parsed.args[0] || "").toLowerCase();
|
||||
const secondPos = (parsed.args[0] || parsed.args[1] || "").toLowerCase();
|
||||
|
||||
let target: ServiceTargetName = forcedTarget || "hose-use";
|
||||
let action = parsed.action || parsed.args[0] || "status";
|
||||
|
||||
// 支持 hose-use service aipro <start|stop|status>
|
||||
if (!forcedTarget) {
|
||||
if (firstPos === "aipro" || firstPos === "hose-aipro") {
|
||||
target = "hose-aipro";
|
||||
action = secondPos || "status";
|
||||
} else if (firstPos === "hose-use" || firstPos === "hose") {
|
||||
target = "hose-use";
|
||||
action = secondPos || "status";
|
||||
}
|
||||
}
|
||||
|
||||
const port = numberOption(parsed.options, ["port", "p"]);
|
||||
const host = stringOption(parsed.options, ["host", "h"]);
|
||||
|
||||
@@ -30,22 +53,34 @@ export async function handleServiceCommand(
|
||||
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, "存储后端": stateFile || "SQLite (observed_events)" })}\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 = {
|
||||
appRoot: runtime.appRoot || process.cwd(),
|
||||
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
|
||||
stateDir: SERVICE_STATE_DIR,
|
||||
version: VERSION,
|
||||
launcher: runtime.launcher,
|
||||
port,
|
||||
host,
|
||||
};
|
||||
const config: ServiceConfig =
|
||||
target === "hose-aipro"
|
||||
? getAiProServiceConfig(runtime, { port, host })
|
||||
: getHoseUseServiceConfig(runtime, { port, host });
|
||||
|
||||
if (["start", "stop", "restart", "run"].includes(action) && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "管理 hose-use 服务", action, { action, port, host, stateDir: config.stateDir });
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
`管理 ${config.serviceName} 服务`,
|
||||
action,
|
||||
{ action, port, host, stateDir: config.stateDir }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runServiceCommand(action, config);
|
||||
|
||||
if (result === undefined) {
|
||||
@@ -60,7 +95,7 @@ export async function handleServiceCommand(
|
||||
if (action === "logs" || action === "log") {
|
||||
const logsResult = result as { logFile: string; lines: string[]; content: string };
|
||||
return {
|
||||
stdout: `====== hose-use 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
|
||||
stdout: `====== ${config.serviceName} 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -73,7 +108,7 @@ export async function handleServiceCommand(
|
||||
"服务状态": isRunning ? "🟢 正在运行 (Running)" : "⚪ 已停止 (Stopped)",
|
||||
...(status.pid ? { "进程 PID": status.pid } : {}),
|
||||
...(status.url ? { "服务地址": status.url } : {}),
|
||||
...(status.url ? { "交互式文档": `${status.url}/docs` } : {}),
|
||||
...(target === "hose-use" && status.url ? { "交互式文档": `${status.url}/docs` } : {}),
|
||||
...(status.url ? { "CLI 网关": `POST ${status.url}/api/cli` } : {}),
|
||||
"运行版本": status.version || config.version,
|
||||
"状态目录": status.stateDir || config.stateDir,
|
||||
@@ -81,10 +116,54 @@ export async function handleServiceCommand(
|
||||
"日志文件": status.logFile || getLogFile(config),
|
||||
};
|
||||
|
||||
const title = (status.serviceTitle as string) || config.serviceTitle || "常驻服务管理 (Service)";
|
||||
const formatted = printKeyValue(displayPairs);
|
||||
return {
|
||||
stdout: `====== hose-use 常驻服务管理 (Service) ======\n${formatted}\n`,
|
||||
stdout: `====== ${title} ======\n${formatted}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProServiceCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = (parsed.action || parsed.args[0] || "status").toLowerCase();
|
||||
const serviceActions = ["start", "stop", "restart", "status", "logs", "log", "run"];
|
||||
|
||||
if (!serviceActions.includes(action)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] AI PRO 确定性审批仲裁命令已完全独立为 hose-aipro 命令行。\n` +
|
||||
`请直接运行: hose-aipro ${action} ${parsed.args.join(" ")}\n\n` +
|
||||
`如需管理本机的 AI PRO 网关常驻服务,请运行:\n` +
|
||||
` hose-use aipro <start|stop|restart|status|logs>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
return handleServiceCommand(parsed, runtime, "hose-aipro");
|
||||
}
|
||||
|
||||
export async function handleApprovalRedirectCommand(
|
||||
parsed: CliParsedArgs,
|
||||
_runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || parsed.args[0] || "";
|
||||
const subArgs = parsed.args.slice(1).join(" ");
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[提示] 确定性审批仲裁命令已独立为 hose-aipro 命令行。\n` +
|
||||
`请直接运行: hose-aipro ${action}${subArgs ? ` ${subArgs}` : ""}\n\n` +
|
||||
`常用命令推荐:\n` +
|
||||
` • 查看要点: hose-aipro points <单号>\n` +
|
||||
` • 事实证据核验: hose-aipro review <单号> --findings='[...]'\n` +
|
||||
` • 执行审批仲裁: hose-aipro decide <单号> --apply --yes\n` +
|
||||
` • 审批日志溯源: hose-aipro logs <单号>\n` +
|
||||
` • 网关服务启停: hose-use aipro <start|stop|status>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
+97
-29
@@ -1,10 +1,15 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
EMBEDDED_SKILL_FILES,
|
||||
EMBEDDED_HOSE_USE_SKILL_FILES,
|
||||
EMBEDDED_AIPRO_SKILL_FILES,
|
||||
getDefaultGlobalSkillDir,
|
||||
getDefaultAiProGlobalSkillDir,
|
||||
getSkillContent,
|
||||
getAiProSkillContent,
|
||||
installSkillFiles,
|
||||
installHoseUseSkillFiles,
|
||||
installAiProSkillFiles,
|
||||
} from "../../packaging/embedded-skill.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
@@ -16,13 +21,16 @@ export async function handleSkillCommand(
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "status";
|
||||
const isAiProCaller =
|
||||
parsed.area === "hose-aipro" ||
|
||||
parsed.raw.some((arg) => arg.includes("hose-aipro") || arg === "aipro");
|
||||
|
||||
switch (action) {
|
||||
case "dump":
|
||||
case "cat":
|
||||
case "show":
|
||||
return {
|
||||
stdout: `${getSkillContent()}\n`,
|
||||
stdout: `${isAiProCaller ? getAiProSkillContent() : getSkillContent()}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -36,30 +44,71 @@ export async function handleSkillCommand(
|
||||
const customDir =
|
||||
stringOption(parsed.options, ["dir", "target"]) || parsed.args[0];
|
||||
|
||||
const targetDir = customDir
|
||||
? customDir
|
||||
: isLocal
|
||||
? join(process.cwd(), ".agents", "skills", "hose-use")
|
||||
: getDefaultGlobalSkillDir();
|
||||
const globalHoseDir = getDefaultGlobalSkillDir();
|
||||
const globalAiProDir = getDefaultAiProGlobalSkillDir();
|
||||
const localHoseDir = join(process.cwd(), ".agents", "skills", "hose-use");
|
||||
const localAiProDir = join(process.cwd(), ".agents", "skills", "hose-aipro");
|
||||
|
||||
const targetPolicy = customDir ? "explicit" : isLocal ? "workspace" : "global-canonical";
|
||||
const totalFiles =
|
||||
Object.keys(EMBEDDED_HOSE_USE_SKILL_FILES).length +
|
||||
Object.keys(EMBEDDED_AIPRO_SKILL_FILES).length;
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "安装 Agent Skill 文件", targetDir, {
|
||||
fileCount: Object.keys(EMBEDDED_SKILL_FILES).length,
|
||||
local: isLocal,
|
||||
targetPolicy: customDir ? "explicit" : isLocal ? "workspace" : "global-canonical",
|
||||
});
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"安装 Agent Skill 文件 (hose-use 与 hose-aipro)",
|
||||
customDir || (isLocal ? `${localHoseDir} & ${localAiProDir}` : `${globalHoseDir} & ${globalAiProDir}`),
|
||||
{
|
||||
fileCount: totalFiles,
|
||||
local: isLocal,
|
||||
targetPolicy,
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
}
|
||||
);
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "安装 Agent Skill 文件", `hose-use skill install${customDir ? ` --dir=${customDir}` : ""} --yes`);
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"安装 Agent Skill 文件",
|
||||
`${isAiProCaller ? "hose-aipro" : "hose-use"} skill install${customDir ? ` --dir=${customDir}` : ""} --yes`
|
||||
);
|
||||
|
||||
const result = installSkillFiles(targetDir);
|
||||
let installedReport: { targetDirs: string[]; filesCount: number; skills: string[] };
|
||||
|
||||
if (customDir) {
|
||||
const res = installSkillFiles(customDir);
|
||||
installedReport = {
|
||||
targetDirs: [res.targetDir],
|
||||
filesCount: res.files.length,
|
||||
skills: ["hose-use"],
|
||||
};
|
||||
} else if (isLocal) {
|
||||
const hoseRes = installHoseUseSkillFiles(localHoseDir);
|
||||
const aiproRes = installAiProSkillFiles(localAiProDir);
|
||||
installedReport = {
|
||||
targetDirs: [hoseRes.targetDir, aiproRes.targetDir],
|
||||
filesCount: hoseRes.files.length + aiproRes.files.length,
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
};
|
||||
} else {
|
||||
const hoseRes = installHoseUseSkillFiles(globalHoseDir);
|
||||
const aiproRes = installAiProSkillFiles(globalAiProDir);
|
||||
installedReport = {
|
||||
targetDirs: [hoseRes.targetDir, aiproRes.targetDir],
|
||||
filesCount: hoseRes.files.length + aiproRes.files.length,
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
installed: true,
|
||||
targetDir: result.targetDir,
|
||||
fileCount: result.files.length,
|
||||
files: result.files,
|
||||
targetDirs: installedReport.targetDirs,
|
||||
fileCount: installedReport.filesCount,
|
||||
skills: installedReport.skills,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
@@ -67,7 +116,10 @@ export async function handleSkillCommand(
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] hose-use 技能已成功安装至: ${result.targetDir}\n包含文件: ${result.files.join(", ")}\n`,
|
||||
stdout:
|
||||
`[SUCCESS] Agent 技能已成功安装:\n` +
|
||||
installedReport.targetDirs.map((d) => ` • ${d}`).join("\n") +
|
||||
`\n共 ${installedReport.filesCount} 个文件。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -75,17 +127,31 @@ export async function handleSkillCommand(
|
||||
|
||||
case "status":
|
||||
case "get": {
|
||||
const globalDir = getDefaultGlobalSkillDir();
|
||||
const localDir = join(process.cwd(), ".agents", "skills", "hose-use");
|
||||
const globalHoseDir = getDefaultGlobalSkillDir();
|
||||
const globalAiProDir = getDefaultAiProGlobalSkillDir();
|
||||
const localHoseDir = join(process.cwd(), ".agents", "skills", "hose-use");
|
||||
const localAiProDir = join(process.cwd(), ".agents", "skills", "hose-aipro");
|
||||
|
||||
const statusObj = {
|
||||
global: {
|
||||
dir: globalDir,
|
||||
installed: existsSync(join(globalDir, "SKILL.md")),
|
||||
"hose-use": {
|
||||
global: {
|
||||
dir: globalHoseDir,
|
||||
installed: existsSync(join(globalHoseDir, "SKILL.md")),
|
||||
},
|
||||
local: {
|
||||
dir: localHoseDir,
|
||||
installed: existsSync(join(localHoseDir, "SKILL.md")),
|
||||
},
|
||||
},
|
||||
local: {
|
||||
dir: localDir,
|
||||
installed: existsSync(join(localDir, "SKILL.md")),
|
||||
"hose-aipro": {
|
||||
global: {
|
||||
dir: globalAiProDir,
|
||||
installed: existsSync(join(globalAiProDir, "SKILL.md")),
|
||||
},
|
||||
local: {
|
||||
dir: localAiProDir,
|
||||
installed: existsSync(join(localAiProDir, "SKILL.md")),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -94,12 +160,14 @@ export async function handleSkillCommand(
|
||||
}
|
||||
|
||||
const output = printKeyValue({
|
||||
"全局 Skill 目录": `${globalDir} [${statusObj.global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"本地 Skill 目录": `${localDir} [${statusObj.local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-use (全局)": `${globalHoseDir} [${statusObj["hose-use"].global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-aipro (全局)": `${globalAiProDir} [${statusObj["hose-aipro"].global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-use (本地)": `${localHoseDir} [${statusObj["hose-use"].local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
"hose-aipro (本地)": `${localAiProDir} [${statusObj["hose-aipro"].local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install --yes 进行全局安装\n`,
|
||||
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 ${isAiProCaller ? "hose-aipro" : "hose-use"} skill install --yes 进行全局安装\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -29,13 +29,27 @@ export async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
}
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await toggleWorkflow(client, pipelineId, state);
|
||||
const label = state === 1 ? "🟢 启用" : "⚪ 停用";
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: printJson(result, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: result.verified ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
// 启停未回读确认时必须如实告知:不得把「请求已提交」呈现为「已生效」。
|
||||
if (!result.verified) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[WARNING] 工作流 ${pipelineId} 启停请求已提交,但${result.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${state === 1 ? "🟢 启用" : "⚪ 停用"}\n`,
|
||||
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${label}(已回读确认)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -55,7 +69,10 @@ export async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
}
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await toggleWorkflow(client, pipelineId, 1);
|
||||
const output = { success: result.success, pipelineId, published: result.success, state: 1 };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
return { stdout: result.success ? `✅ 工作流 [${pipelineId}] 已发布并启用。\n` : `❌ 工作流 [${pipelineId}] 发布失败。\n`, stderr: "", exitCode: result.success ? 0 : 1 };
|
||||
const output = { success: result.verified, pipelineId, published: result.verified, state: 1, verified: result.verified, message: result.message };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.verified ? 0 : 1 };
|
||||
if (!result.verified) {
|
||||
return { stdout: "", stderr: `❌ 工作流 [${pipelineId}] 发布状态未能确认:${result.message}\n`, exitCode: 1 };
|
||||
}
|
||||
return { stdout: `✅ 工作流 [${pipelineId}] 已发布并启用(已回读确认)。\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -3,15 +3,87 @@ import * as services from "../../../domains/platform/workflow/services.js";
|
||||
import * as shared from "./shared.js";
|
||||
import { handleWorkflowCommand } from "./index.js";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
|
||||
|
||||
afterEach(() => { mock.restore(); });
|
||||
|
||||
/** 构造支持读详情与写回的假 Piper 客户端,第二次及之后的读取返回变更后的版本。 */
|
||||
function createVersionedClient(options: {
|
||||
initialDetail: any;
|
||||
detailAfterSecondRead?: any;
|
||||
refuseChooses?: boolean;
|
||||
onPut?: () => void;
|
||||
}) {
|
||||
let reads = 0;
|
||||
return {
|
||||
get: async () => {
|
||||
reads += 1;
|
||||
const payload = reads > 1 && options.detailAfterSecondRead
|
||||
? options.detailAfterSecondRead
|
||||
: options.initialDetail;
|
||||
return Response.json({ code: 200, data: payload });
|
||||
},
|
||||
put: async (url: string, opts: any) => {
|
||||
if (String(url).includes("/chooses")) {
|
||||
if (options.refuseChooses) return Response.json({ code: 500, msg: "刷新拒绝" });
|
||||
return Response.json({ code: 200, data: [] });
|
||||
}
|
||||
options.onPut?.();
|
||||
return Response.json({ code: 200, data: opts?.json ?? options.initialDetail });
|
||||
},
|
||||
} as any;
|
||||
}
|
||||
|
||||
test("节点修改在远端版本变化时不提交完整快照", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [{ name: "code", type: "code-js2", code: "return 1", groupName: "action", orderIndex: 0, levelIndex: [0], status: "active" }] } as any;
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any);
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValueOnce(detail).mockResolvedValueOnce({ ...detail, tasksVersion: 2 });
|
||||
const save = spyOn(services, "updateWorkflow").mockResolvedValue(detail);
|
||||
let putCount = 0;
|
||||
const client = createVersionedClient({
|
||||
initialDetail: detail,
|
||||
detailAfterSecondRead: { ...detail, tasksVersion: 2 },
|
||||
onPut: () => { putCount += 1; },
|
||||
});
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client } as any);
|
||||
const runtime = { selectedCorp: { id: "corp" }, jsonMode: true } as any;
|
||||
await expect(handleWorkflowCommand(parseArgs(["workflow", "node", "edit", "wf", "code", "--code=return 2", "--yes"]), runtime)).rejects.toThrow("版本已变化");
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(putCount).toBe(0);
|
||||
});
|
||||
|
||||
test("SDK 出口在未声明期望版本时不读取详情,按原语义直接保存", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
let putCount = 0;
|
||||
const client = createVersionedClient({ initialDetail: detail, onPut: () => { putCount += 1; } });
|
||||
const result = await services.updateWorkflow(client, detail);
|
||||
expect(result.id).toBe("wf");
|
||||
expect(putCount).toBe(1);
|
||||
});
|
||||
|
||||
test("SDK 出口在 expectedVersion 一致时才允许写入", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
const client = createVersionedClient({ initialDetail: detail });
|
||||
await expect(
|
||||
services.updateWorkflow(client, detail, { expectedVersion: { version: "v1", tasksVersion: 1 } })
|
||||
).resolves.toMatchObject({ id: "wf" });
|
||||
await expect(
|
||||
services.updateWorkflow(client, detail, { expectedVersion: { version: "v1", tasksVersion: 9 } })
|
||||
).rejects.toThrow("版本已变化");
|
||||
});
|
||||
|
||||
test("第三参数沿用字符串写法时仍等价于 platformId", async () => {
|
||||
let payload: any;
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
const client = createVersionedClient({ initialDetail: detail, onPut: () => {} });
|
||||
const originalPut = client.put;
|
||||
client.put = async (url: string, opts: any) => {
|
||||
if (!String(url).includes("/chooses")) payload = opts?.json;
|
||||
return originalPut(url, opts);
|
||||
};
|
||||
await services.updateWorkflow(client, detail, "platform-9");
|
||||
expect(payload.inputs).toEqual([{ key: "$platformId", value: "platform-9" }]);
|
||||
});
|
||||
|
||||
test("chooses 刷新失败时保留主保存结果的部分成功语义", async () => {
|
||||
const detail = { id: "wf", version: "v1", tasksVersion: 1, tasks: [] } as any;
|
||||
const client = createVersionedClient({ initialDetail: detail, refuseChooses: true });
|
||||
const error = await services.updateWorkflow(client, detail).catch((err: unknown) => err);
|
||||
expect(error).toBeInstanceOf(WorkflowSavePartialError);
|
||||
});
|
||||
@@ -19,11 +19,11 @@ import { createWorkflowDetailClient, formatWorkflowVersion } from "./shared.js";
|
||||
import { handleGrantNodes, handleListAvailableNodes } from "./node-catalog.js";
|
||||
|
||||
async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0], original: WorkflowDetail, updated: WorkflowDetail, platformId?: string) {
|
||||
const remote = await getWorkflowDetail(client, original.id);
|
||||
if (remote.version !== original.version || remote.tasksVersion !== original.tasksVersion) {
|
||||
throw new ValidationError(`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 读取时 tasksVersion=${original.tasksVersion}。请重新执行命令。`);
|
||||
}
|
||||
return updateWorkflow(client, updated, platformId);
|
||||
// 并发保护由 SDK 出口统一负责,避免每个调用点各写一份、或干脆忘写。
|
||||
return updateWorkflow(client, updated, {
|
||||
platformId,
|
||||
expectedVersion: { version: original.version, tasksVersion: original.tasksVersion },
|
||||
});
|
||||
}
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
|
||||
|
||||
+7
-1
@@ -53,7 +53,13 @@ export function mutationPreview(
|
||||
changes: Record<string, unknown>
|
||||
): CliResult {
|
||||
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
|
||||
const nextAction = `hose-use ${confirmedArgs.join(" ")} --yes`;
|
||||
const isAiPro = confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "aipro";
|
||||
const binaryPrefix = isAiPro ? "hose-aipro" : "hose-use";
|
||||
const cleanArgs =
|
||||
confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "hose-use" || confirmedArgs[0] === "aipro"
|
||||
? confirmedArgs.slice(1)
|
||||
: confirmedArgs;
|
||||
const nextAction = `${binaryPrefix} ${cleanArgs.join(" ")} --yes`;
|
||||
const payload = {
|
||||
dryRun: true,
|
||||
operation,
|
||||
|
||||
+1
-1
@@ -229,7 +229,7 @@ ${Object.entries(HELP_REGISTRY).map(([area, topic]) => ` ${area.padEnd(12)}${to
|
||||
|
||||
常用示例:
|
||||
hose-use context # 一键查看全局运行上下文与身份诊断 (免读源码)
|
||||
hose-use aipro status # 查看 AI PRO 审批网关状态与当前连接企业
|
||||
hose-aipro status # 查看 AI PRO 审批网关状态与当前连接企业
|
||||
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
||||
hose-use auth status # 查看当前登录状态与活跃企业
|
||||
hose-use config paths # 查看多级企业配置目录链
|
||||
|
||||
+14
-9
@@ -13,7 +13,11 @@ import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||
import { handleBillCommand } from "./commands/bill/index.js";
|
||||
import { handleFlowCommand } from "./commands/flow.js";
|
||||
import { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import {
|
||||
handleServiceCommand,
|
||||
handleAiProServiceCommand,
|
||||
handleApprovalRedirectCommand,
|
||||
} from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
@@ -21,7 +25,6 @@ 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";
|
||||
@@ -30,6 +33,8 @@ import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js
|
||||
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
export * from "./aipro-registry.js";
|
||||
|
||||
export type CliCommandHandler = (
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
@@ -51,12 +56,12 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "aipro",
|
||||
...COMMAND_METADATA.aipro,
|
||||
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);
|
||||
},
|
||||
handler: (parsed, runtime) => handleAiProServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "hose-aipro",
|
||||
...COMMAND_METADATA["hose-aipro"],
|
||||
handler: (parsed, runtime) => handleAiProServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "auth",
|
||||
@@ -126,7 +131,7 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "approval",
|
||||
...COMMAND_METADATA.approval,
|
||||
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
|
||||
handler: (parsed, runtime) => handleApprovalRedirectCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "message",
|
||||
|
||||
+116
-19
@@ -1,9 +1,24 @@
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
|
||||
import { homedir } from "node:os";
|
||||
import {
|
||||
startHttpServer,
|
||||
DEFAULT_HTTP_PORT,
|
||||
DEFAULT_AIPRO_HTTP_PORT,
|
||||
DEFAULT_HTTP_HOST,
|
||||
} from "../http/server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import type { CliRuntime } from "./types.js";
|
||||
|
||||
export type ServiceTargetName = "hose-use" | "hose-aipro";
|
||||
|
||||
export const SERVICE_STATE_DIR =
|
||||
process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
|
||||
export type ServiceConfig = {
|
||||
serviceName?: ServiceTargetName;
|
||||
serviceTitle?: string;
|
||||
appRoot: string;
|
||||
entryFile: string;
|
||||
stateDir: string;
|
||||
@@ -14,13 +29,56 @@ export type ServiceConfig = {
|
||||
};
|
||||
port?: number;
|
||||
host?: string;
|
||||
pidFileName?: string;
|
||||
logFileName?: string;
|
||||
};
|
||||
|
||||
export function getHoseUseServiceConfig(
|
||||
runtime?: Partial<CliRuntime>,
|
||||
options?: { port?: number; host?: string }
|
||||
): ServiceConfig {
|
||||
const appRoot = runtime?.appRoot || process.cwd();
|
||||
return {
|
||||
serviceName: "hose-use",
|
||||
serviceTitle: "hose-use 常驻服务管理 (Service)",
|
||||
appRoot,
|
||||
entryFile: runtime?.entryFile || join(appRoot, "src", "cli.ts"),
|
||||
stateDir: SERVICE_STATE_DIR,
|
||||
version: VERSION,
|
||||
launcher: runtime?.launcher,
|
||||
port: options?.port,
|
||||
host: options?.host,
|
||||
pidFileName: "service.pid",
|
||||
logFileName: "service.log",
|
||||
};
|
||||
}
|
||||
|
||||
export function getAiProServiceConfig(
|
||||
runtime?: Partial<CliRuntime>,
|
||||
options?: { port?: number; host?: string }
|
||||
): ServiceConfig {
|
||||
const appRoot = runtime?.appRoot || process.cwd();
|
||||
return {
|
||||
serviceName: "hose-aipro",
|
||||
serviceTitle: "hose-aipro 审批网关常驻服务 (Service)",
|
||||
appRoot,
|
||||
entryFile: join(appRoot, "src", "aipro-cli.ts"),
|
||||
stateDir: SERVICE_STATE_DIR,
|
||||
version: VERSION,
|
||||
launcher: runtime?.launcher,
|
||||
port: options?.port,
|
||||
host: options?.host,
|
||||
pidFileName: "aipro-service.pid",
|
||||
logFileName: "aipro-service.log",
|
||||
};
|
||||
}
|
||||
|
||||
export async function runServiceCommand(
|
||||
action: string | undefined,
|
||||
config: ServiceConfig,
|
||||
options: { quiet?: boolean } = {}
|
||||
) {
|
||||
const targetLabel = config.serviceName || "hose-use";
|
||||
switch (action) {
|
||||
case "run":
|
||||
await runService(config);
|
||||
@@ -39,24 +97,32 @@ export async function runServiceCommand(
|
||||
case undefined:
|
||||
return serviceStatus(config);
|
||||
default:
|
||||
throw new Error("用法: hose-use service <start|stop|restart|status|logs|poll>");
|
||||
throw new Error(`用法: ${targetLabel} service <start|stop|restart|status|logs|poll>`);
|
||||
}
|
||||
}
|
||||
|
||||
export function serviceStatus(config: ServiceConfig) {
|
||||
const pidFile = getPidFile(config);
|
||||
const pid = readServicePid(pidFile);
|
||||
const running = pid ? isHoseServiceProcess(pid, config.appRoot) : false;
|
||||
const running = pid ? isHoseServiceProcess(pid, config.appRoot, config.serviceName) : false;
|
||||
|
||||
if (pid && !running) {
|
||||
rmSync(pidFile, { force: true });
|
||||
}
|
||||
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||
const isAiPro = config.serviceName === "hose-aipro";
|
||||
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
||||
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
return {
|
||||
running,
|
||||
serviceName: config.serviceName || "hose-use",
|
||||
serviceTitle:
|
||||
config.serviceTitle ||
|
||||
(isAiPro
|
||||
? "hose-aipro 审批网关常驻服务 (Service)"
|
||||
: "hose-use 常驻服务管理 (Service)"),
|
||||
pid: running ? pid : undefined,
|
||||
version: config.version,
|
||||
port,
|
||||
@@ -75,17 +141,24 @@ async function runService(config: ServiceConfig) {
|
||||
ensureStateDir(config.stateDir);
|
||||
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
|
||||
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||
const isAiPro = config.serviceName === "hose-aipro";
|
||||
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
||||
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
||||
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service starting on http://${host}:${port} pid=${process.pid}`);
|
||||
|
||||
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
|
||||
try {
|
||||
server = await startHttpServer({ port, host, silent: true });
|
||||
appendLog(logFile, `service listening pid=${process.pid}`);
|
||||
server = await startHttpServer({
|
||||
port,
|
||||
host,
|
||||
silent: true,
|
||||
app: isAiPro ? "hose-aipro" : "hose-use",
|
||||
});
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service listening pid=${process.pid}`);
|
||||
} catch (err: unknown) {
|
||||
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
if (readServicePid(pidFile) === process.pid) {
|
||||
rmSync(pidFile, { force: true });
|
||||
}
|
||||
@@ -100,7 +173,7 @@ async function runService(config: ServiceConfig) {
|
||||
if (readServicePid(pidFile) === process.pid) {
|
||||
rmSync(pidFile, { force: true });
|
||||
}
|
||||
appendLog(logFile, `service stopped pid=${process.pid}`);
|
||||
appendLog(logFile, `${config.serviceName || "hose-use"} service stopped pid=${process.pid}`);
|
||||
};
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
@@ -140,14 +213,14 @@ function startService(config: ServiceConfig) {
|
||||
|
||||
const pidFile = getPidFile(config);
|
||||
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
|
||||
appendLog(getLogFile(config), `service started pid=${child.pid}`);
|
||||
appendLog(getLogFile(config), `${config.serviceName || "hose-use"} service started pid=${child.pid}`);
|
||||
return { started: true, ...serviceStatus(config) };
|
||||
}
|
||||
|
||||
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
|
||||
const pidFile = getPidFile(config);
|
||||
const pid = readServicePid(pidFile);
|
||||
if (!pid || !isHoseServiceProcess(pid, config.appRoot)) {
|
||||
if (!pid || !isHoseServiceProcess(pid, config.appRoot, config.serviceName)) {
|
||||
rmSync(pidFile, { force: true });
|
||||
return options.quiet ? undefined : { stopped: false, reason: "服务未处于运行状态" };
|
||||
}
|
||||
@@ -158,7 +231,7 @@ function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
|
||||
// ignore
|
||||
}
|
||||
rmSync(pidFile, { force: true });
|
||||
appendLog(getLogFile(config), `service stop requested pid=${pid}`);
|
||||
appendLog(getLogFile(config), `${config.serviceName || "hose-use"} service stop requested pid=${pid}`);
|
||||
return options.quiet ? undefined : { stopped: true, pid };
|
||||
}
|
||||
|
||||
@@ -176,16 +249,34 @@ function readServiceLogs(config: ServiceConfig, maxLines = 50) {
|
||||
};
|
||||
}
|
||||
|
||||
export function isHoseServiceProcess(pid: number, appRoot: string): boolean {
|
||||
export function isHoseServiceProcess(
|
||||
pid: number,
|
||||
appRoot: string,
|
||||
targetName?: ServiceTargetName
|
||||
): boolean {
|
||||
if (!isProcessRunning(pid)) return false;
|
||||
|
||||
try {
|
||||
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
||||
const matchesTarget =
|
||||
const isRun = command.includes("service") && command.includes("run");
|
||||
if (!isRun) return false;
|
||||
|
||||
if (targetName === "hose-aipro") {
|
||||
return command.includes("hose-aipro") || command.includes("aipro-cli");
|
||||
}
|
||||
if (targetName === "hose-use") {
|
||||
return (
|
||||
(command.includes("hose-use") || command.includes("src/cli.ts") || command.includes(appRoot)) &&
|
||||
!command.includes("hose-aipro") &&
|
||||
!command.includes("aipro-cli")
|
||||
);
|
||||
}
|
||||
return (
|
||||
command.includes(appRoot) ||
|
||||
command.includes("hose-use") ||
|
||||
command.includes("src/cli.ts");
|
||||
return matchesTarget && command.includes("service") && command.includes("run");
|
||||
command.includes("src/cli.ts") ||
|
||||
command.includes("hose-aipro")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -201,11 +292,17 @@ function isProcessRunning(pid: number): boolean {
|
||||
}
|
||||
|
||||
export function getPidFile(config: ServiceConfig): string {
|
||||
return join(config.stateDir, "service.pid");
|
||||
const fileName =
|
||||
config.pidFileName ||
|
||||
(config.serviceName === "hose-aipro" ? "aipro-service.pid" : "service.pid");
|
||||
return join(config.stateDir, fileName);
|
||||
}
|
||||
|
||||
export function getLogFile(config: ServiceConfig): string {
|
||||
return join(config.stateDir, "service.log");
|
||||
const fileName =
|
||||
config.logFileName ||
|
||||
(config.serviceName === "hose-aipro" ? "aipro-service.log" : "service.log");
|
||||
return join(config.stateDir, fileName);
|
||||
}
|
||||
|
||||
export function readServicePid(path: string): number | undefined {
|
||||
|
||||
@@ -216,6 +216,32 @@ export const migrations: DatabaseMigration[] = [
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_workflow_alerts_scope ON workflow_error_alerts(scope_key);");
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 4,
|
||||
name: "004_approval_runs_unique_short_id",
|
||||
up(db: Database): void {
|
||||
// 存量纠偏:历史短 ID 若发生大小写不敏感碰撞,仅保留每组最新一条,其余置空
|
||||
// (被置空的记录仍可通过 UUID / 单号定位,不影响既有会话)
|
||||
db.run(`
|
||||
UPDATE approval_runs
|
||||
SET short_id = NULL
|
||||
WHERE short_id IS NOT NULL
|
||||
AND id NOT IN (
|
||||
SELECT id FROM (
|
||||
SELECT id, ROW_NUMBER() OVER (
|
||||
PARTITION BY UPPER(short_id) ORDER BY created_at DESC, id DESC
|
||||
) AS rn
|
||||
FROM approval_runs
|
||||
WHERE short_id IS NOT NULL
|
||||
) WHERE rn = 1
|
||||
);
|
||||
`);
|
||||
// short_id 必须大小写不敏感全局唯一,杜绝碰撞导致按短 ID 取错审批会话
|
||||
db.run(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_runs_short_id_unique ON approval_runs(UPPER(short_id)) WHERE short_id IS NOT NULL;"
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -298,9 +298,25 @@ export class ApprovalRepository {
|
||||
|
||||
// ===================== 审批运行与要点清单 (Runs & Findings) =====================
|
||||
|
||||
/**
|
||||
* 生成库内唯一的 6 位短 ID。
|
||||
* 迁移层已用 UPPER(short_id) 唯一索引兜底,这里再显式探测重试,
|
||||
* 避免极小概率碰撞直接把会话写到同一个短 ID 上。
|
||||
*/
|
||||
private allocateUniqueShortId(maxAttempts = 20): string {
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
const candidate = generateShortRunId();
|
||||
const hit = this.db
|
||||
.query("SELECT 1 FROM approval_runs WHERE UPPER(short_id) = UPPER(?) LIMIT 1")
|
||||
.get(candidate);
|
||||
if (!hit) return candidate;
|
||||
}
|
||||
throw new BusinessError("生成唯一审批会话短 ID 失败(连续碰撞),请稍后重试");
|
||||
}
|
||||
|
||||
public createApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
|
||||
const id = crypto.randomUUID();
|
||||
const shortId = input.shortId ?? generateShortRunId();
|
||||
const shortId = input.shortId ?? this.allocateUniqueShortId();
|
||||
const now = Date.now();
|
||||
const expiresAt = input.expiresAt ?? (now + 6 * 3600 * 1000); // 6 小时有效期
|
||||
|
||||
@@ -335,28 +351,31 @@ export class ApprovalRepository {
|
||||
const existing = this.getLatestRunBySn(input.documentSn, input.corpId ?? undefined);
|
||||
const now = Date.now();
|
||||
if (existing) {
|
||||
// 清理旧要点,重置运行记录
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
|
||||
this.db.run(
|
||||
`
|
||||
// 清理旧要点与重置运行记录必须原子完成,避免删了旧要点却没更新主记录
|
||||
const reset = this.db.transaction(() => {
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE approval_runs
|
||||
SET expires_at = ?, flow_id = ?, corp_id = ?, scope = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[
|
||||
input.expiresAt ?? (now + 6 * 3600 * 1000),
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
|
||||
now,
|
||||
existing.id,
|
||||
]
|
||||
);
|
||||
[
|
||||
input.expiresAt ?? (now + 6 * 3600 * 1000),
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
|
||||
now,
|
||||
existing.id,
|
||||
]
|
||||
);
|
||||
});
|
||||
reset();
|
||||
return this.getRunById(existing.id)!;
|
||||
}
|
||||
|
||||
@@ -491,39 +510,44 @@ export class ApprovalRepository {
|
||||
throw new NotFoundError(`审批运行记录不存在: ${runId}`);
|
||||
}
|
||||
|
||||
// 校验必须在事务外先行完成:任何非法状态都不应触发旧要点被删除
|
||||
for (const finding of findings) {
|
||||
if (!isValidFindingCheckStatus(finding.checkStatus ?? "PENDING")) throw new ValidationError("核验状态必须为 PENDING、PASS、FAIL 或 SKIP");
|
||||
}
|
||||
|
||||
// 重新挂载时清空旧要点
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
|
||||
|
||||
const now = Date.now();
|
||||
const insertStmt = this.db.prepare(`
|
||||
INSERT INTO approval_findings (
|
||||
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const f of findings) {
|
||||
const id = crypto.randomUUID();
|
||||
insertStmt.run(
|
||||
id,
|
||||
runId,
|
||||
f.ruleId ?? null,
|
||||
f.clauseText.trim(),
|
||||
f.strictness,
|
||||
f.checkStatus ?? "PENDING",
|
||||
f.evidence ?? null,
|
||||
f.reasoning ?? null,
|
||||
now
|
||||
// 清空旧要点 + 批量写入 + 回写计数必须原子完成,避免中途失败留下半残清单
|
||||
const persist = this.db.transaction(() => {
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
|
||||
|
||||
const insertStmt = this.db.prepare(`
|
||||
INSERT INTO approval_findings (
|
||||
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const f of findings) {
|
||||
insertStmt.run(
|
||||
crypto.randomUUID(),
|
||||
runId,
|
||||
f.ruleId ?? null,
|
||||
f.clauseText.trim(),
|
||||
f.strictness,
|
||||
f.checkStatus ?? "PENDING",
|
||||
f.evidence ?? null,
|
||||
f.reasoning ?? null,
|
||||
now
|
||||
);
|
||||
}
|
||||
|
||||
this.db.run(
|
||||
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
|
||||
[findings.length, now, runId]
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
this.db.run(
|
||||
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
|
||||
[findings.length, now, runId]
|
||||
);
|
||||
persist();
|
||||
|
||||
return this.getFindingsByRunId(runId);
|
||||
}
|
||||
|
||||
@@ -91,8 +91,16 @@ export class ApprovalService {
|
||||
matchedSummary = allScopes.find((s) => /差旅|出差/i.test(s.scope));
|
||||
}
|
||||
|
||||
// 默认回退至第一个场景
|
||||
matchedSummary = matchedSummary ?? allScopes[0];
|
||||
// 严禁静默回退到首个场景:用错规则集审单据(如差旅规则审办公费)比直接报错危险得多
|
||||
if (!matchedSummary) {
|
||||
const available = allScopes.map((s) => s.scope).join("、");
|
||||
if (options.scope !== undefined) {
|
||||
throw new NotFoundError(`指定场景 [${options.scope}] 不存在或无效,当前可用场景: ${available}`);
|
||||
}
|
||||
throw new ValidationError(
|
||||
`无法为单据 [${documentSn}] 自动匹配适用场景,请通过 --scope 显式指定。当前可用场景: ${available}`
|
||||
);
|
||||
}
|
||||
scopeDetail = this.repo.getScopeDetail(matchedSummary.index);
|
||||
}
|
||||
|
||||
@@ -181,7 +189,7 @@ export class ApprovalService {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何审核要点清单(要点列表为空)。\n` +
|
||||
`在没有注入审核要点的情况下,无法进行事实核验!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点清单。`
|
||||
`请先执行: hose-aipro points ${documentSn} 注入审核要点清单。`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -225,7 +233,7 @@ export class ApprovalService {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点。`
|
||||
`请先执行: hose-aipro points ${documentSn} 注入审核要点。`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ Platform 域下工作流能力的命令、协议与诊断契约。总体边界
|
||||
|
||||
`workflow save --in-place` 遇到这类部分成功仍同步本地版本,返回非零退出码、`status: "partial"`、`remoteSaved: true`、新版本和恢复命令。主保存本身失败则不改本地版本。恢复可用 `workflow refresh-chooses <pipelineId> --platform-id=<id> --yes`,只刷新元数据,不提交快照;该命令也支持 `--dry-run`。
|
||||
|
||||
启停(`toggle` / `publish`)属于生产开关:写请求按 EASO 业务码判定成败(HTTP 200 不代表成功),写成功后再回读详情确认 `state` 确实变化。回读状态与期望不一致抛 `BusinessError`(`WORKFLOW_STATE_NOT_APPLIED`);回读失败返回 `verified: false` 并给出非零退出码,不把「请求已提交」说成「已生效」。返回的 `WorkflowToggleResult` 中 `state` 为 `null` 表示未能读到服务端实际状态。
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
@@ -167,7 +169,9 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
|
||||
快照 Diff 对比节点的全部配置字段(脚本和过滤器沿用专用输出),覆盖 `mapping/inputs/fields` 及自定义配置。节点顺序或父容器变化通过 `configChanges` 中的 `$path` 表达,不依赖服务端是否重算索引。
|
||||
|
||||
灰度开通网关明确返回失败时,CLI 保留失败详情并返回非零退出码;文本输出不再宣称权限生效,JSON 中的 `success` 与退出码保持一致。
|
||||
灰度开通网关明确返回失败时,CLI 保留失败详情并返回非零退出码;文本输出不再宣称权限生效,JSON 中的 `success` 与退出码保持一致。网关既没有返回 `success`、也没有返回可识别的 `code` 时,同样判为失败而非成功——谎报开通会让下游继续报 `PERMISSION_MISSING_NODE`,比如实报错更难排查。
|
||||
|
||||
网关地址不再硬编码:可用环境变量 `HOSE_GRAY_GATEWAY_URL` 覆盖内置默认地址(原本固定的第三方托管域曾出现实例回收风险),请求路径统一为 `/hose-workflow-node`,详见 [transport/README.transport.md](./transport/README.transport.md)。传入的 `baseUrl` 只是目标租户地址,不是网关地址。
|
||||
|
||||
监听结果区分完成、超时、快照和取消:只有到达终态才发送 `job_completed`;超时发送 `timeout` 并设置 `timedOut`,取消设置 `cancelled`。CLI 超时或取消返回非零退出码;`--once` 的运行中快照仍可成功返回,且不冒充完成。持续监听的总超时预算覆盖正在跟踪的 Job。
|
||||
|
||||
@@ -224,10 +228,10 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
| [script](./script/README.script.md) | 代码节点的 JavaScript/MVEL 静态检查及本地沙箱求值 |
|
||||
| [branch](./branch/index.ts) | 根据执行记录解释条件规则及分支命中情况,证据不足时保留未知结果 |
|
||||
| [watch](./watch/README.watch.md) | 轮询工作流与 Job,跟踪节点变化并区分完成、超时和取消 |
|
||||
| [alert](./alert/index.ts) | 保存错误指纹,识别新增或变化的错误,避免重复提醒 |
|
||||
| [alert](./alert/index.ts) | 保存错误指纹,识别新增或变化的错误,避免重复提醒;SQLite 是唯一事实来源,JSON 副本导出失败会以 `exportError` 呈现而不中断巡检 |
|
||||
| [state](./state/index.ts) | 本地草稿路径补丁、状态及版本冲突判断 |
|
||||
|
||||
节点写入提交前会重新读取并比较 `version` 和 `tasksVersion`;这是一项客户端检查,不是原子条件写入,检查与提交间仍存在并发窗口。
|
||||
写入并发保护由 SDK 出口 `updateWorkflow` 提供:调用方传入 `expectedVersion: { version, tasksVersion }` 时,会在提交前重新读取远端并比较 `version` 与 `tasksVersion`,不一致抛 `ValidationError`(`WORKFLOW_VERSION_CONFLICT`)。这是一项客户端检查,不是原子条件写入,检查与提交之间仍存在并发窗口;不传期望值时按既有语义直接保存。CLI 的节点写入命令统一走这条路径,不再在命令层各自重读。
|
||||
|
||||
内部实现直接导入所属模块,不反向导入 services 门面。watch 的 tracker 使用 execution,工作流报告类型直接引用 branch/types,避免通过聚合出口形成循环。跨应用查询只通过 applications 的公开业务服务取得应用;各子模块禁止绕过服务直接调用兄弟模块 api。
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync, chmodSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { Database } from "bun:sqlite";
|
||||
import { runMigrations } from "../../../../core/db/index.js";
|
||||
import { WorkflowAlertStore, type WorkflowErrorAlert } from "./index.js";
|
||||
|
||||
/**
|
||||
* 错误指纹的持久化行为。此前这些用例写在 state/index.test.ts 里(模块归属错位),
|
||||
* 改 alert 时容易被漏跑,这里连同新增的导出失败路径一起收拢。
|
||||
*/
|
||||
function createStore(): { store: WorkflowAlertStore; cleanup: () => void; file: string } {
|
||||
const dir = mkdtempSync("hose-alert-store-");
|
||||
const file = join(dir, "alerts.json");
|
||||
const dbPath = join(dir, "state.db");
|
||||
const db = new Database(dbPath);
|
||||
runMigrations(db);
|
||||
const store = new WorkflowAlertStore(file, db);
|
||||
return { store, file, cleanup: () => { db.close(); rmSync(dir, { recursive: true, force: true }); } };
|
||||
}
|
||||
|
||||
const alert = (overrides: Partial<WorkflowErrorAlert> = {}): WorkflowErrorAlert => ({
|
||||
id: "corp:platform:wf-1",
|
||||
pipelineId: "wf-1",
|
||||
platformId: "platform-1",
|
||||
pipelineName: "测试流程",
|
||||
errorCount: 1,
|
||||
state: 0,
|
||||
observedAt: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("workflow alert store", () => {
|
||||
it("persists fingerprints and only reports changed counts", () => {
|
||||
const { store, file, cleanup } = createStore();
|
||||
try {
|
||||
expect(store.observe([alert()]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([alert({ observedAt: 2 })]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([alert({ errorCount: 2, observedAt: 3 })]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([]).newAlerts).toHaveLength(0);
|
||||
// 告警消失后再次出现,应当重新提醒
|
||||
expect(store.observe([alert({ observedAt: 4 })]).newAlerts).toHaveLength(1);
|
||||
expect(JSON.parse(readFileSync(file, "utf8")).version).toBe(1);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("clears resolved alerts only for complete scans", () => {
|
||||
const { store, cleanup } = createStore();
|
||||
try {
|
||||
expect(store.observe([alert()]).newAlerts).toHaveLength(1);
|
||||
// 扫描不完整时不清空指纹:同一条告警再次出现不再重复提醒
|
||||
store.observe([], { complete: false });
|
||||
expect(store.observe([alert({ observedAt: 2 })], { complete: false }).newAlerts).toHaveLength(0);
|
||||
// 完整扫描才清理已解决的告警,之后重现才会重新提醒
|
||||
store.observe([], { complete: true });
|
||||
expect(store.observe([alert()]).newAlerts).toHaveLength(1);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps observing when the JSON export fails", () => {
|
||||
const { store, cleanup } = createStore();
|
||||
try {
|
||||
const first = store.observe([alert()]);
|
||||
expect(first.newAlerts).toHaveLength(1);
|
||||
expect(first.exportError).toBeUndefined();
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("workflow alert store export failures", () => {
|
||||
it("surfaces the export failure without losing observed results", () => {
|
||||
const dir = mkdtempSync("hose-alert-export-");
|
||||
const nested = join(dir, "blocked");
|
||||
const unwritableFile = join(nested, "alerts.json");
|
||||
const db = new Database(join(dir, "state.db"));
|
||||
runMigrations(db);
|
||||
try {
|
||||
// 把目标目录设为不可写:SQLite 已写入,但 JSON 副本落盘必然失败
|
||||
const fs = require("node:fs");
|
||||
fs.mkdirSync(nested, { recursive: true });
|
||||
fs.chmodSync(nested, 0o500);
|
||||
const store = new WorkflowAlertStore(unwritableFile, db);
|
||||
const result = store.observe([alert()]);
|
||||
expect(result.newAlerts).toHaveLength(1);
|
||||
expect(result.exportError).toBeDefined();
|
||||
// 事实来源是 SQLite:即便副本失败,指纹依然被记住,下一轮不会重复提醒
|
||||
expect(store.observe([alert({ observedAt: 2 })]).newAlerts).toHaveLength(0);
|
||||
} finally {
|
||||
chmodSync(nested, 0o700);
|
||||
db.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,12 @@ interface PersistedAlerts {
|
||||
export interface WorkflowAlertCheckResult {
|
||||
activeAlerts: WorkflowErrorAlert[];
|
||||
newAlerts: WorkflowErrorAlert[];
|
||||
/**
|
||||
* JSON 副本导出失败的原因。SQLite 已是唯一事实来源,
|
||||
* 导出失败不能让整轮巡检判定失败——那会让调用方以为观察没完成,
|
||||
* 从而在下一次巡检时漏报新增告警。
|
||||
*/
|
||||
exportError?: string;
|
||||
}
|
||||
|
||||
/** 本地持久化工作流错误指纹(统一落盘至 core/db SQLite,兼容显式 JSON 状态文件)。 */
|
||||
@@ -120,15 +126,20 @@ export class WorkflowAlertStore {
|
||||
});
|
||||
tx(alerts);
|
||||
|
||||
let exportError: string | undefined;
|
||||
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 }
|
||||
);
|
||||
try {
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
} catch (error) {
|
||||
exportError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
|
||||
return { activeAlerts: alerts, newAlerts };
|
||||
return { activeAlerts: alerts, newAlerts, ...(exportError ? { exportError } : {}) };
|
||||
}
|
||||
}
|
||||
@@ -250,23 +250,54 @@ export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
/** 合思条件里代表「上一步执行结果」的属性名。 */
|
||||
const EXECUTION_STATUS_PROPERTIES = ["$status", "status", "result", "data"];
|
||||
|
||||
/** 条件数据来源:各处写法顺序不统一,这里固定为唯一的解析入口。 */
|
||||
function collectFilterSource(task: WorkflowTask): unknown {
|
||||
const raw = task as Record<string, unknown>;
|
||||
return raw.combineFilters ?? raw.filters ?? raw.conditions ?? raw.inputs ?? {};
|
||||
}
|
||||
|
||||
/** 收集条件节点内的全部字符串,用于逐个做引用判定。 */
|
||||
function collectReferenceStrings(source: unknown, found: string[] = []): string[] {
|
||||
if (typeof source === "string") {
|
||||
found.push(source);
|
||||
return found;
|
||||
}
|
||||
if (Array.isArray(source)) {
|
||||
for (const item of source) collectReferenceStrings(item, found);
|
||||
return found;
|
||||
}
|
||||
if (source && typeof source === "object") {
|
||||
for (const value of Object.values(source as Record<string, unknown>)) {
|
||||
collectReferenceStrings(value, found);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** 取出 `${a.b}` 或 `a.b` 形态的引用目标;无法判定为引用时返回 undefined。 */
|
||||
function referenceTargetOf(raw: string): string | undefined {
|
||||
const trimmed = raw.trim();
|
||||
const bracketed = /^\$\{([^}]+)\}$/.exec(trimmed);
|
||||
const candidate = (bracketed ? bracketed[1] : trimmed).trim();
|
||||
return candidate || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定条件节点是否真正守卫了某个节点的执行状态。
|
||||
* 必须整体等于 `<节点名>.$status` 等形态,不能靠子串包含:
|
||||
* 子串匹配会让 `task_1` 命中 `task_10` 之类无关引用,从而把「未守卫」误判为「已守卫」,
|
||||
* 使这条安全建议静默失效。
|
||||
*/
|
||||
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("是否运行成功"))
|
||||
);
|
||||
const expected = new Set(EXECUTION_STATUS_PROPERTIES.map((property) => `${targetTaskName}.${property}`));
|
||||
return collectReferenceStrings(collectFilterSource(task)).some((item) => {
|
||||
const target = referenceTargetOf(item);
|
||||
return target !== undefined && expected.has(target);
|
||||
});
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
|
||||
@@ -434,5 +434,121 @@ describe("Workflow static analysis", () => {
|
||||
expect(result.summary.hardBlocks).toBe(1);
|
||||
expect(result.summary.softAdvices).toBe(1);
|
||||
});
|
||||
|
||||
describe("状态守卫判定", () => {
|
||||
/** 构造「循环内建单(SKIP) + 条件节点 + 台账更新」的最小工作流。 */
|
||||
const buildSkipWorkflow = (guardValue: string) => ({
|
||||
id: "wf-guard",
|
||||
label: "状态守卫校验",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "every_0",
|
||||
type: "every",
|
||||
label: "依次执行",
|
||||
groupName: "control",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
tasks: [
|
||||
{
|
||||
name: "create_task_0",
|
||||
type: "flow-create-task",
|
||||
label: "创建单据",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 0],
|
||||
status: "",
|
||||
onError: { defaultAction: "SKIP" },
|
||||
},
|
||||
{
|
||||
name: "condition_0",
|
||||
type: "condition",
|
||||
label: "是否创建成功",
|
||||
groupName: "control",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0, 1],
|
||||
status: "",
|
||||
combineFilters: {
|
||||
condition: "and",
|
||||
filters: [
|
||||
{ key: guardValue, compare: "eq", value: "SUCCESS" },
|
||||
],
|
||||
},
|
||||
// 状态守卫的典型写法:把台账更新放进条件分支内部
|
||||
tasks: [
|
||||
{
|
||||
name: "datalink_edit_0",
|
||||
type: "ekuaibao-datalink-edit",
|
||||
label: "更新台账",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 1, 0],
|
||||
status: "",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const guardCodes = (guardValue: string) =>
|
||||
analyzeWorkflow(buildSkipWorkflow(guardValue) as any).diagnostics.map((d) => d.code);
|
||||
|
||||
it("把 ${节点名}.$status 判定为已守卫", () => {
|
||||
expect(guardCodes("${create_task_0.$status}")).not.toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
|
||||
it("把裸写 节点名.status 也判定为已守卫", () => {
|
||||
expect(guardCodes("create_task_0.status")).not.toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
|
||||
it("不因为节点名子串而误判为已守卫", () => {
|
||||
// create_task_0 是另一个节点的名字前缀时,不能当成对 create_task_0 的守卫
|
||||
expect(guardCodes("${create_task_0_extended.$status}")).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
|
||||
it("无关引用与注释文本不构成守卫", () => {
|
||||
expect(guardCodes("${every_0.item.id}")).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
});
|
||||
});
|
||||
|
||||
describe("未知节点类型与权限证据边界", () => {
|
||||
const build = (type: string) => ({
|
||||
id: "wf-node-type",
|
||||
label: "节点类型校验",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "task_0",
|
||||
type,
|
||||
label: "被测节点",
|
||||
groupName: "action",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
it("对未收录的节点类型给出软建议", () => {
|
||||
const codes = analyzeWorkflow(build("brand-new-node") as any).diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("UNKNOWN_TASK_TYPE");
|
||||
});
|
||||
|
||||
it("已收录的节点类型不产生该建议", () => {
|
||||
const codes = analyzeWorkflow(build("http") as any).diagnostics.map((d) => d.code);
|
||||
expect(codes).not.toContain("UNKNOWN_TASK_TYPE");
|
||||
});
|
||||
|
||||
it("拿不到开通清单时既不谎报通过也不误报缺失", () => {
|
||||
const codes = analyzeWorkflow(build("code-js2") as any, { availableNodeTypes: [] })
|
||||
.diagnostics.map((d) => d.code);
|
||||
expect(codes).not.toContain("PERMISSION_MISSING_NODE");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { OP_MAP, cleanRuleValue, evaluateRule, parseChooseTag, parseValueTag } from "./explain.js";
|
||||
|
||||
/**
|
||||
* 条件解释器的值比较:此前只有 eq/gt 有覆盖,其余九个比较符完全裸奔。
|
||||
* `evaluateRule` 返回 `null` 表示「无法确定」,UI 侧据此不声称分支判定为 False。
|
||||
*/
|
||||
describe("evaluateRule equality operators", () => {
|
||||
it("compares scalars after string coercion", () => {
|
||||
expect(evaluateRule(10, "10", "eq")).toBe(true);
|
||||
expect(evaluateRule(10, "11", "eq")).toBe(false);
|
||||
expect(evaluateRule(10, "11", "neq")).toBe(true);
|
||||
expect(evaluateRule("a", "b", "neq")).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a single-element array as its item", () => {
|
||||
expect(evaluateRule(["SUCCESS"], "SUCCESS", "eq")).toBe(true);
|
||||
expect(evaluateRule("SUCCESS", ["SUCCESS"], "eq")).toBe(true);
|
||||
expect(evaluateRule(["A", "B"], "A", "eq")).toBe(false);
|
||||
});
|
||||
|
||||
it("unwraps identifier objects before comparing", () => {
|
||||
// 带 id 的对象会被归一成 id 本身
|
||||
expect(evaluateRule({ id: 1 }, 1, "eq")).toBe(true);
|
||||
});
|
||||
|
||||
it("reports null (unknown) when a non-identifier object survives normalization", () => {
|
||||
expect(evaluateRule({ amount: 10 }, 10, "eq")).toBeNull();
|
||||
expect(evaluateRule({ amount: 10 }, 10, "gt")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns false rather than unknown when the actual value is undefined", () => {
|
||||
expect(evaluateRule(undefined, "x", "eq")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns null for unsupported operators", () => {
|
||||
expect(evaluateRule("a", "b", "like")).toBeNull();
|
||||
expect(OP_MAP.like).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateRule emptiness", () => {
|
||||
it("detects empty values including empty arrays", () => {
|
||||
expect(evaluateRule(null, null, "empty")).toBe(true);
|
||||
expect(evaluateRule(undefined, null, "empty")).toBe(true);
|
||||
expect(evaluateRule("", null, "empty")).toBe(true);
|
||||
expect(evaluateRule([], null, "empty")).toBe(true);
|
||||
expect(evaluateRule(0, null, "empty")).toBe(false);
|
||||
});
|
||||
|
||||
it("negates emptiness", () => {
|
||||
expect(evaluateRule("x", null, "not_empty")).toBe(true);
|
||||
expect(evaluateRule([], null, "not_empty")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateRule membership", () => {
|
||||
it("checks membership against an expected list", () => {
|
||||
expect(evaluateRule("A", ["A", "B"], "in")).toBe(true);
|
||||
expect(evaluateRule("C", ["A", "B"], "in")).toBe(false);
|
||||
expect(evaluateRule("C", ["A", "B"], "not_in")).toBe(true);
|
||||
});
|
||||
|
||||
it("cannot decide when the actual value itself is a list", () => {
|
||||
expect(evaluateRule(["A"], ["A"], "in")).toBeNull();
|
||||
expect(evaluateRule("A", "A", "in")).toBeNull();
|
||||
});
|
||||
|
||||
it("checks containment for strings and arrays", () => {
|
||||
expect(evaluateRule("abc", "b", "include")).toBe(true);
|
||||
expect(evaluateRule(["a", "b"], ["a"], "include")).toBe(true);
|
||||
expect(evaluateRule(["a", "b"], ["a", "c"], "include")).toBe(false);
|
||||
expect(evaluateRule(["a"], ["b"], "not_include")).toBe(true);
|
||||
});
|
||||
|
||||
it("cannot decide containment for non-collection actual values", () => {
|
||||
expect(evaluateRule(5, [5], "include")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateRule numeric comparison", () => {
|
||||
it("compares numeric strings", () => {
|
||||
expect(evaluateRule("11", "10", "gt")).toBe(true);
|
||||
expect(evaluateRule("10", "10", "gte")).toBe(true);
|
||||
expect(evaluateRule("9", "10", "lt")).toBe(true);
|
||||
expect(evaluateRule("10", "10", "lte")).toBe(true);
|
||||
expect(evaluateRule("10", "10", "gt")).toBe(false);
|
||||
});
|
||||
|
||||
it("cannot compare non-numeric values", () => {
|
||||
expect(evaluateRule("abc", "10", "gt")).toBeNull();
|
||||
expect(evaluateRule("", "10", "lt")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("rule value descriptors", () => {
|
||||
it("unwraps @{value('...')} selectors and identifier objects", () => {
|
||||
expect(cleanRuleValue(`@{value('{"key":"k1","label":"预算"}')}`)).toBe("k1");
|
||||
expect(cleanRuleValue({ id: "k2" })).toBe("k2");
|
||||
expect(cleanRuleValue(["@{value('{\"key\":\"k3\"}')}"])).toEqual(["k3"]);
|
||||
});
|
||||
|
||||
it("keeps value tags readable for display", () => {
|
||||
expect(parseValueTag(`@{value('{"key":"k1","label":"预算"}')}`)).toBe("预算 (k1)");
|
||||
expect(parseValueTag(`@{value('{"bad json"}')}`)).toContain("@{value");
|
||||
});
|
||||
|
||||
it("extracts upstream nodes from choose descriptors", () => {
|
||||
expect(parseChooseTag(`@{choose('{"key":"webhook_1","properties":[{"key":"body"}],"label":"触发人"}')}`)).toEqual({
|
||||
upstreamNode: "webhook_1",
|
||||
upstreamProp: "body",
|
||||
label: "触发人",
|
||||
});
|
||||
expect(parseChooseTag("plain.key")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -119,6 +119,7 @@ export async function grantWorkflowNodes(
|
||||
corpId,
|
||||
nodes: normalizedNodes,
|
||||
baseUrl,
|
||||
gatewayUrl: options.gatewayUrl,
|
||||
});
|
||||
|
||||
return result;
|
||||
|
||||
@@ -2,7 +2,15 @@
|
||||
|
||||
- [tree.ts](./tree.ts):执行树展开、失败识别和节点查找,也提供工作流任务树展开。
|
||||
- [context.ts](./context.ts):构建执行实例索引,供条件解释与 Job 差异比较复用。
|
||||
- [job-status.ts](./job-status.ts):Job 状态归一化与终态判定,**watch 监听与 debug 轮询共用同一实现**。
|
||||
- [debug.ts](./debug.ts):调试输入、发起 Job、轮询和诊断汇总。
|
||||
- [queries.ts](./queries.ts):Job、执行树与日志读取服务出口。
|
||||
|
||||
执行监听位于同级 [watch](../watch/README.watch.md),条件解释位于 `branch/`;HTTP 传输位于上级 `api.ts`。
|
||||
|
||||
## Job 状态语义
|
||||
|
||||
Job 可能只返回字符串 `status`,也可能只返回数字 `state`(0 完成、1 运行中、2 失败)。
|
||||
归一化逻辑只在 `job-status.ts` 定义一次:过去 debug 侧自行判定时把 `state: 0` 当成未知而继续轮询,
|
||||
watch 侧却视为已完成,同一个 Job 在两条路径上会得到相反的结论。
|
||||
修改状态时必须同时考虑这两个入口,并在两侧补回归用例。
|
||||
@@ -3,6 +3,7 @@ import { ValidationError } from "../../../../core/errors.js";
|
||||
import { explainConditionBranches } from "../branch/index.js";
|
||||
import { WorkflowJobDetail } from "../types.js";
|
||||
import { extractFailureExecutions } from "./tree.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./job-status.js";
|
||||
|
||||
|
||||
export function getWebhookInfo(...args: Parameters<typeof api.getWebhookInfo>) {
|
||||
@@ -74,8 +75,6 @@ export async function runWorkflowDebugTest(
|
||||
const start = Date.now();
|
||||
const diagnosticsErrors: Array<{ source: string; message: string }> = [];
|
||||
const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) });
|
||||
const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase();
|
||||
let finalJob: WorkflowJobDetail | undefined;
|
||||
let pollingFailed = false;
|
||||
|
||||
@@ -83,7 +82,7 @@ export async function runWorkflowDebugTest(
|
||||
try {
|
||||
const job = await api.getJob(client, jobId);
|
||||
finalJob = job;
|
||||
if (terminal.has(jobState(job))) break;
|
||||
if (isJobTerminal(normalizeJobStatus(job))) break;
|
||||
} catch (error) {
|
||||
// 任务刚创建可能存在短延时,继续轮询
|
||||
const status = (error as { status?: number; response?: { status?: number } } | null)?.status
|
||||
@@ -101,7 +100,7 @@ export async function runWorkflowDebugTest(
|
||||
try { finalJob = await api.getJob(client, jobId); }
|
||||
catch (error) { recordError("job", error); pollingFailed = true; }
|
||||
}
|
||||
const timedOut = !pollingFailed && !terminal.has(jobState(finalJob));
|
||||
const timedOut = !pollingFailed && !isJobTerminal(normalizeJobStatus(finalJob));
|
||||
const [treeResult, failuresResult] = await Promise.allSettled([
|
||||
api.getJobExecutionTree(client, jobId),
|
||||
api.getJobFailedExecutions(client, jobId),
|
||||
@@ -113,11 +112,11 @@ export async function runWorkflowDebugTest(
|
||||
|
||||
const rawFailed = extractFailureExecutions(tree, failedItems);
|
||||
const diagnosticsComplete = diagnosticsErrors.length === 0;
|
||||
const status = jobState(finalJob);
|
||||
const status = normalizeJobStatus(finalJob);
|
||||
const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0;
|
||||
let outcome: import("../types.js").WorkflowTestReport["outcome"] = "incomplete";
|
||||
if (timedOut) outcome = "timed_out";
|
||||
else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed";
|
||||
else if (isJobTerminal(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed";
|
||||
else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed";
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { WorkflowJobDetail } from "../types.js";
|
||||
|
||||
/**
|
||||
* Job 状态归一化。Job 可能只返回字符串 `status`,也可能只返回数字 `state`,
|
||||
* 两个入口(watch 监听与 debug 轮询)必须给出一致的解释,否则同一个 Job
|
||||
* 在一处被视为已完成、在另一处被视为仍在运行。
|
||||
*
|
||||
* 数字 state 的语义:0 完成、1 运行中、2 失败(与 watch 侧既有约定一致)。
|
||||
*/
|
||||
export const TERMINAL_JOB_STATES = new Set([
|
||||
"COMPLETED",
|
||||
"FAILED",
|
||||
"STOP",
|
||||
"STOPPED",
|
||||
"CANCELLED",
|
||||
"CANCELED",
|
||||
]);
|
||||
|
||||
export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<string, unknown> | null): string {
|
||||
if (!job) return "UNKNOWN";
|
||||
const rawStatus = (job as Record<string, unknown>).status;
|
||||
const rawState = (job as Record<string, unknown>).state;
|
||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||
const normalized = rawStatus.trim().toUpperCase();
|
||||
return normalized === "STARTED" ? "RUNNING" : normalized;
|
||||
}
|
||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
export function isJobTerminal(status: string): boolean {
|
||||
return TERMINAL_JOB_STATES.has(status.toUpperCase());
|
||||
}
|
||||
@@ -63,6 +63,35 @@ describe("workflow debug completion evidence", () => {
|
||||
await expect(runWorkflowDebugTest(client, "pipe", { flowCodeOrId: "ID01-record", timeoutMs: -1 })).rejects.toThrow("timeoutMs");
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
|
||||
describe("numeric job state must agree with the watch pipeline", () => {
|
||||
const withState = (state: number) => {
|
||||
const { client } = setup();
|
||||
const get = client.get;
|
||||
client.get = async (path: string) => {
|
||||
if (path.endsWith("/job")) {
|
||||
return new Response(JSON.stringify({ code: 200, data: { id: "job", state } }), {
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
return get(path);
|
||||
};
|
||||
return client;
|
||||
};
|
||||
|
||||
it("reads state 0 as completed instead of polling until timeout", async () => {
|
||||
const result = await runWorkflowDebugTest(withState(0), "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 100, pollIntervalMs: 1 });
|
||||
expect(result.status).toBe("COMPLETED");
|
||||
expect(result.outcome).toBe("completed");
|
||||
expect(result.timedOut).toBe(false);
|
||||
});
|
||||
|
||||
it("reads state 1 as still running", async () => {
|
||||
const result = await runWorkflowDebugTest(withState(1), "pipe", { flowCodeOrId: "ID01-record", timeoutMs: 0 });
|
||||
expect(result.status).toBe("RUNNING");
|
||||
expect(result.outcome).toBe("timed_out");
|
||||
});
|
||||
});
|
||||
it("retries a newly created job's HTTP 404 instead of reporting an authorization failure", async () => {
|
||||
const { client } = setup();
|
||||
const get = client.get;
|
||||
|
||||
@@ -5,3 +5,18 @@
|
||||
- [save-error.ts](./save-error.ts):主保存成功而元数据刷新失败时的部分成功异常。
|
||||
|
||||
HTTP 传输和共享模型仍位于上级 `api.ts`、`types.ts`,对外业务出口为上级 `services.ts`。
|
||||
|
||||
## 保存与并发保护
|
||||
|
||||
`updateWorkflow(client, workflow, options)` 的第三参数支持两种写法:
|
||||
|
||||
| 写法 | 语义 |
|
||||
|---|---|
|
||||
| `updateWorkflow(client, wf, "platform-id")` | 兼容旧调用,等价于 `{ platformId }` |
|
||||
| `updateWorkflow(client, wf, { platformId, expectedVersion })` | 提供 `expectedVersion: { version, tasksVersion }` 时,提交前重读远端比对,不一致抛 `ValidationError`(`WORKFLOW_VERSION_CONFLICT`) |
|
||||
|
||||
并发保护必须由调用方显式声明期望值才会启用:这是一项客户端检查而非原子条件写入,检查与提交之间仍存在窗口。任何绕过 CLI 的调用方都应走这条路径,而不是各自再实现一遍重读逻辑。
|
||||
|
||||
## 启停
|
||||
|
||||
`toggleWorkflow` 先按 EASO 业务码判定写请求,再回读详情确认 `state` 确实变化;回读失败返回 `verified: false`,交由调用方如实呈现,不谎称已生效。详见 [README.workflow.md](../README.workflow.md)。
|
||||
@@ -1,3 +1,4 @@
|
||||
import { BusinessError, ValidationError } from "../../../../core/errors.js";
|
||||
import { KyInstance } from "ky";
|
||||
import { WorkflowSavePartialError } from "./save-error.js";
|
||||
import * as api from "../api.js";
|
||||
@@ -24,14 +25,33 @@ export function sanitizeWorkflowSnapshot(
|
||||
}
|
||||
|
||||
|
||||
export interface UpdateWorkflowOptions {
|
||||
/** 前端保存时带上的触发输入 $platformId,缺少它会让平台把内置节点 desc 重置为「」。 */
|
||||
platformId?: string;
|
||||
/**
|
||||
* 读取工作流时的版本快照。提供时会在提交前重读远端做比对,
|
||||
* 不一致抛 ValidationError,避免静默覆盖中间发生的修改。
|
||||
* 这是客户端检查而非原子条件写入,检查与提交之间仍存在并发窗口。
|
||||
*/
|
||||
expectedVersion?: { version?: unknown; tasksVersion?: unknown };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按前端「保存更新」语义提交工作流。
|
||||
* 第三参数兼容旧的 platformId 字符串写法;需要并发保护时改用对象形式并传入 expectedVersion。
|
||||
*/
|
||||
export async function updateWorkflow(
|
||||
client: KyInstance,
|
||||
workflow: import("../types.js").WorkflowDetail,
|
||||
platformId?: string
|
||||
options: string | UpdateWorkflowOptions = {}
|
||||
) {
|
||||
const opts: UpdateWorkflowOptions = typeof options === "string" ? { platformId: options } : options ?? {};
|
||||
if (opts.expectedVersion) {
|
||||
await assertVersionUnchanged(client, workflow.id, opts.expectedVersion);
|
||||
}
|
||||
// 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。
|
||||
const payload: import("../types.js").WorkflowDetail = platformId && !workflow.inputs?.length
|
||||
? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] }
|
||||
const payload: import("../types.js").WorkflowDetail = opts.platformId && !workflow.inputs?.length
|
||||
? { ...workflow, inputs: [{ key: "$platformId", value: opts.platformId }] }
|
||||
: workflow;
|
||||
const sanitized = sanitizeWorkflowSnapshot(payload);
|
||||
const updated = await api.updateWorkflow(client, sanitized);
|
||||
@@ -44,6 +64,22 @@ export async function updateWorkflow(
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** 提交前的事实校验:远端版本与读取时不一致则拒绝写入。 */
|
||||
async function assertVersionUnchanged(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
expected: { version?: unknown; tasksVersion?: unknown }
|
||||
): Promise<void> {
|
||||
const remote = await api.getWorkflowDetail(client, pipelineId);
|
||||
const versionMatches = expected.version === undefined || remote.version === expected.version;
|
||||
const tasksMatches = expected.tasksVersion === undefined || remote.tasksVersion === expected.tasksVersion;
|
||||
if (versionMatches && tasksMatches) return;
|
||||
throw new ValidationError(
|
||||
`工作流版本已变化,拒绝覆盖:远端 version=${remote.version}/tasksVersion=${remote.tasksVersion},读取时 version=${expected.version}/tasksVersion=${expected.tasksVersion}。请重新执行命令。`,
|
||||
"WORKFLOW_VERSION_CONFLICT"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/** 只重试元数据刷新,不重新提交完整工作流快照。 */
|
||||
export function refreshWorkflowChooses(client: KyInstance, pipelineId: string): Promise<void> {
|
||||
@@ -136,6 +172,48 @@ export function deleteWorkflow(...args: Parameters<typeof api.deleteWorkflow>) {
|
||||
}
|
||||
|
||||
|
||||
export function toggleWorkflow(...args: Parameters<typeof api.toggleWorkflow>) {
|
||||
return api.toggleWorkflow(...args);
|
||||
/**
|
||||
* 启停是生产开关:写请求按 EASO 业务码判定成败,写成功之后再回读详情确认状态确实变化。
|
||||
* 回读失败(网络、鉴权、详情不可用)时不得宣称已生效,返回 `verified: false` 交由调用方如实呈现。
|
||||
* `verify: false` 仅用于无法回读的场景(如只需要触发写写的内部场景),默认为确认模式。
|
||||
*/
|
||||
export async function toggleWorkflow(
|
||||
client: import("ky").KyInstance,
|
||||
pipelineId: string,
|
||||
state: import("../types.js").WorkflowState,
|
||||
options: { verify?: boolean } = {}
|
||||
): Promise<import("../types.js").WorkflowToggleResult> {
|
||||
await api.toggleWorkflowState(client, pipelineId, state);
|
||||
const notVerified = (reason: string): import("../types.js").WorkflowToggleResult => ({
|
||||
pipelineId,
|
||||
requestedState: state,
|
||||
state: null,
|
||||
success: true,
|
||||
verified: false,
|
||||
message: `已提交启停请求,但${reason},服务端实际状态未能确认。请稍后用 workflow get 核对。`,
|
||||
});
|
||||
|
||||
if (options.verify === false) return notVerified("未请求回读");
|
||||
|
||||
try {
|
||||
const remote = await api.getWorkflowDetail(client, pipelineId);
|
||||
const actual: import("../types.js").WorkflowState = remote.state === 1 ? 1 : 0;
|
||||
if (actual !== state) {
|
||||
throw new BusinessError(
|
||||
`工作流 [${pipelineId}] 启停未生效:期望 state=${state},服务端回读 state=${actual}。请勿据此认为已发布或已停用。`,
|
||||
"WORKFLOW_STATE_NOT_APPLIED"
|
||||
);
|
||||
}
|
||||
return {
|
||||
pipelineId,
|
||||
requestedState: state,
|
||||
state: actual,
|
||||
success: true,
|
||||
verified: true,
|
||||
message: state === 1 ? "已确认启用" : "已确认停用",
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError) throw error;
|
||||
return notVerified(`回读详情失败(${error instanceof Error ? error.message : String(error)})`);
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,8 @@ export interface AvailableWorkflowNodes {
|
||||
export interface GrantWorkflowNodesOptions {
|
||||
nodes: string[];
|
||||
password?: string;
|
||||
/** 覆盖灰度开通网关地址;缺省使用环境变量 HOSE_GRAY_GATEWAY_URL。 */
|
||||
gatewayUrl?: string;
|
||||
}
|
||||
|
||||
export interface GrantWorkflowNodesResult {
|
||||
|
||||
@@ -174,3 +174,19 @@ 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>;
|
||||
|
||||
// ── 启停结果 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 工作流启停结果。启停是生产开关,必须在写操作之后回读确认:
|
||||
* `verified` 区分「已确认生效」与「已提交但未能确认」,两者都不能谎称成功。
|
||||
* `state` 为 null 表示未能读到服务端实际状态。
|
||||
*/
|
||||
export interface WorkflowToggleResult {
|
||||
pipelineId: string;
|
||||
requestedState: WorkflowState;
|
||||
state: WorkflowState | null;
|
||||
success: boolean;
|
||||
verified: boolean;
|
||||
message: string;
|
||||
}
|
||||
@@ -17,6 +17,8 @@
|
||||
|
||||
JavaScript 在独立 QuickJS 运行时中执行,设置超时、内存及输入/输出、日志限制;输入同时提供变量和 `inputs` 命名空间。求值仅支持同步结果,不共享宿主构造器,不把本地求值视为服务端脚本执行的完整替代。
|
||||
|
||||
return 识别先剔除注释与字符串字面量(`stripCommentsAndStrings`)再匹配关键字,避免行尾注释、块注释内部行和字符串里的 `return` 让 `missing-return` 告警失效。该能力同样需要增加回归案例。
|
||||
|
||||
MVEL 本地支持范围以 `mvel-subset.ts` 为准,不等价完整 Java/MVEL 运行时。静态检查与本地求值分别报告问题和结果;不能用“本地通过”推断租户权限、服务端上下文或业务写入一定成功。
|
||||
|
||||
修改语法支持时增加支持/拒绝的回归案例,并保持沙箱资源释放。测试见 [index.test.ts](./index.test.ts)、[mvel-subset.test.ts](./mvel-subset.test.ts);命令适配在 [script.ts](../../../../cli/commands/workflow/script.ts),业务脚本编写参考位于 [MVEL 产品技能](../../../../../skills/hose-use/multi/ekuaibao-mvel/SKILL.md)。
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { hasReturnStatement, stripCommentsAndStrings, lintJavaScriptCode } from "./lint-js.js";
|
||||
|
||||
/**
|
||||
* return 检测曾经只跳过整行注释,行尾注释、块注释内部行和字符串里的 "return"
|
||||
* 都会让 missing-return 告警彻底失效。以下用例固定住这一修复。
|
||||
*/
|
||||
describe("JavaScript return detection", () => {
|
||||
it("finds real return statements", () => {
|
||||
expect(hasReturnStatement("return a + b;")).toBe(true);
|
||||
expect(hasReturnStatement("const x = 1;\nif (x) { return x; }\nreturn 0;")).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores returns in trailing comments", () => {
|
||||
expect(hasReturnStatement("const total = sum;\n// 记得 return 结果给下游")).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores returns inside block comments", () => {
|
||||
expect(hasReturnStatement("/*\nreturn 1;\n*/\nprepare();")).toBe(false);
|
||||
expect(hasReturnStatement("/* return 1 */ prepare();")).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores returns inside string literals", () => {
|
||||
expect(hasReturnStatement('log("return value: ");')).toBe(false);
|
||||
expect(hasReturnStatement("log('return value');")).toBe(false);
|
||||
expect(hasReturnStatement("log(`return ${x}`);")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat identifiers containing return as a return", () => {
|
||||
expect(hasReturnStatement("returnValue = 1;")).toBe(false);
|
||||
expect(hasReturnStatement("const return_of_day = 3;")).toBe(false);
|
||||
});
|
||||
|
||||
it("still detects a return that follows commented-out code", () => {
|
||||
expect(hasReturnStatement("// return 1;\nreturn 2;")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stripCommentsAndStrings", () => {
|
||||
it("keeps code characters and blanks out comment bodies", () => {
|
||||
expect(stripCommentsAndStrings("// c\nkeep")).toBe(`${" ".repeat(4)}\nkeep`);
|
||||
const blockStripped = stripCommentsAndStrings("/* x */ keep");
|
||||
expect(blockStripped).toMatch(/^\s+keep$/);
|
||||
});
|
||||
|
||||
it("handles escaped quotes inside strings", () => {
|
||||
const stripped = stripCommentsAndStrings('"a\\"b" + x');
|
||||
expect(stripped).not.toContain('"');
|
||||
expect(stripped).toMatch(/\+\s*x$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lintJavaScriptCode missing-return reporting", () => {
|
||||
it("warns when only comments mention return", () => {
|
||||
const { issues } = lintJavaScriptCode("// 记得 return 值\nnormalize(data);");
|
||||
expect(issues.map((i) => i.rule)).toContain("missing-return");
|
||||
});
|
||||
|
||||
it("stays quiet when a real return exists", () => {
|
||||
const { issues, hasReturn } = lintJavaScriptCode("normalize(data);\nreturn data;");
|
||||
expect(hasReturn).toBe(true);
|
||||
expect(issues.map((i) => i.rule)).not.toContain("missing-return");
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,61 @@
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
|
||||
type ScanState = "code" | "lineComment" | "blockComment" | "singleQuote" | "doubleQuote" | "template";
|
||||
|
||||
/**
|
||||
* 检查代码中是否存在 return 关键字(排除纯注释中的 return)
|
||||
* 剔除注释与字符串字面量,其余字符原样保留、被剔除部分用空格占位(保持偏移便于将来定位)。
|
||||
* 覆盖行注释、块注释、单/双引号与模板串(含转义)。正则字面量中的 return 仍可能误判,
|
||||
* 由后续语法解析兜底。
|
||||
*/
|
||||
export function hasReturnStatement(code: string): boolean {
|
||||
const lines = code.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
||||
continue;
|
||||
}
|
||||
if (/\breturn\b/.test(trimmed)) {
|
||||
return true;
|
||||
export function stripCommentsAndStrings(code: string): string {
|
||||
let output = "";
|
||||
let state: ScanState = "code";
|
||||
let index = 0;
|
||||
while (index < code.length) {
|
||||
const char = code[index]!;
|
||||
const next = code[index + 1];
|
||||
switch (state) {
|
||||
case "code":
|
||||
if (char === "/" && next === "/") { state = "lineComment"; output += " "; index += 2; continue; }
|
||||
if (char === "/" && next === "*") { state = "blockComment"; output += " "; index += 2; continue; }
|
||||
if (char === "'" || char === '"' || char === "`") {
|
||||
state = char === "'" ? "singleQuote" : char === '"' ? "doubleQuote" : "template";
|
||||
output += " ";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
output += char;
|
||||
index += 1;
|
||||
continue;
|
||||
case "lineComment":
|
||||
if (char === "\n") { state = "code"; output += char; } else if (char !== "\r") { output += " "; }
|
||||
index += 1;
|
||||
continue;
|
||||
case "blockComment":
|
||||
if (char === "*" && next === "/") { state = "code"; output += " "; index += 2; continue; }
|
||||
output += char === "\n" ? char : " ";
|
||||
index += 1;
|
||||
continue;
|
||||
default: {
|
||||
if (char === "\\") { output += " "; index += 2; continue; }
|
||||
const closer = state === "singleQuote" ? "'" : state === "doubleQuote" ? '"' : "`";
|
||||
if (char === closer) { state = "code"; output += " "; index += 1; continue; }
|
||||
output += char === "\n" ? char : " ";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断脚本是否真的写了 return。
|
||||
* 先前只跳过整行注释,行尾注释 `// return`、块注释内部行与字符串里的 "return"
|
||||
* 都会被当成真语句,导致 missing-return 告警永不触发。
|
||||
*/
|
||||
export function hasReturnStatement(code: string): boolean {
|
||||
return /\breturn\b/.test(stripCommentsAndStrings(code));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,10 +34,9 @@ export {
|
||||
createWorkflow,
|
||||
deleteWorkflow,
|
||||
toggleWorkflow,
|
||||
type CreateWorkflowOptions,
|
||||
} from "./management/configuration.js";
|
||||
export type {
|
||||
CreateWorkflowOptions,
|
||||
} from "./management/configuration.js";
|
||||
export type { WorkflowToggleResult } from "./models/workflow.js";
|
||||
export {
|
||||
listDsl,
|
||||
listStaffs,
|
||||
|
||||
@@ -19,8 +19,8 @@ import {
|
||||
getWorkflowDetail,
|
||||
listWorkflowSnapshots,
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
} from "../api.js";
|
||||
import { toggleWorkflow } from "../management/configuration.js";
|
||||
import {
|
||||
extractFailureExecutions,
|
||||
findExecutionNode,
|
||||
@@ -30,9 +30,6 @@ import {
|
||||
sanitizeWorkflowSnapshot,
|
||||
} from "../services.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "../alert/index.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const workflow = (overrides: Partial<WorkflowDetail> = {}): WorkflowDetail => WorkflowDetailSchema.parse({
|
||||
id: "wf-1",
|
||||
@@ -144,45 +141,47 @@ describe("workflow draft state machine", () => {
|
||||
expect(result.items[0]?.message).toBe("测试错误");
|
||||
});
|
||||
|
||||
it("uses the state endpoint for publishing a workflow", async () => {
|
||||
it("uses the state endpoint for publishing a workflow and confirms the new state", async () => {
|
||||
let request: { url: string; options: any } | undefined;
|
||||
const client = {
|
||||
put: async (url: string, options: any) => {
|
||||
request = { url, options };
|
||||
return new Response(JSON.stringify({ code: 200, msg: "更新成功", data: null }), { status: 200 });
|
||||
},
|
||||
get: async () => new Response(JSON.stringify({ code: 200, data: { id: "wf-1", state: 1, version: "v1", tasksVersion: 1, tasks: [] } }), { status: 200 }),
|
||||
} as any;
|
||||
const result = await toggleWorkflow(client, "wf-1", 1);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.verified).toBe(true);
|
||||
expect(result.state).toBe(1);
|
||||
expect(request?.url).toBe("api/easo/pipelines/state/wf-1");
|
||||
expect(request?.options.searchParams).toEqual({ state: "1" });
|
||||
});
|
||||
|
||||
it("persists workflow alert fingerprints and only reports new counts", () => {
|
||||
const dir = mkdtempSync("hose-workflow-alert-");
|
||||
const file = join(dir, "alerts.json");
|
||||
const store = new WorkflowAlertStore(file);
|
||||
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
|
||||
expect(store.observe([alert]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([{ ...alert, observedAt: 2 }]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([{ ...alert, errorCount: 2, observedAt: 3 }]).newAlerts).toHaveLength(1);
|
||||
expect(store.observe([]).newAlerts).toHaveLength(0);
|
||||
expect(store.observe([{ ...alert, observedAt: 4 }]).newAlerts).toHaveLength(1);
|
||||
expect(JSON.parse(readFileSync(file, "utf8")).version).toBe(1);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
it("refuses to claim success when the server keeps the old state", async () => {
|
||||
const client = {
|
||||
put: async () => new Response(JSON.stringify({ code: 200, data: null }), { status: 200 }),
|
||||
get: async () => new Response(JSON.stringify({ code: 200, data: { id: "wf-1", state: 0, version: "v1", tasksVersion: 1, tasks: [] } }), { status: 200 }),
|
||||
} as any;
|
||||
await expect(toggleWorkflow(client, "wf-1", 1)).rejects.toThrow("启停未生效");
|
||||
});
|
||||
|
||||
it("preserves previously observed alerts when a scan is incomplete", () => {
|
||||
const dir = mkdtempSync("hose-workflow-alert-partial-");
|
||||
const file = join(dir, "alerts.json");
|
||||
const store = new WorkflowAlertStore(file);
|
||||
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
|
||||
expect(store.observe([alert]).newAlerts).toHaveLength(1);
|
||||
store.observe([], { complete: false });
|
||||
expect(store.observe([{ ...alert, observedAt: 2 }], { complete: false }).newAlerts).toHaveLength(0);
|
||||
store.observe([], { complete: true });
|
||||
expect(store.observe([alert]).newAlerts).toHaveLength(1);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
it("reports business failures carried by HTTP 200 responses", async () => {
|
||||
const client = {
|
||||
put: async () => new Response(JSON.stringify({ code: 500, msg: "流程存在非法节点" }), { status: 200 }),
|
||||
} as any;
|
||||
await expect(toggleWorkflow(client, "wf-1", 1)).rejects.toThrow("流程存在非法节点");
|
||||
});
|
||||
|
||||
it("does not claim success when the confirmation read fails", async () => {
|
||||
const client = {
|
||||
put: async () => new Response(JSON.stringify({ code: 200, data: null }), { status: 200 }),
|
||||
get: async () => new Response(JSON.stringify({ code: 401, msg: "凭证过期" }), { status: 200 }),
|
||||
} as any;
|
||||
const result = await toggleWorkflow(client, "wf-1", 0);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.verified).toBe(false);
|
||||
expect(result.state).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks dirty revisions and commits the server snapshot", () => {
|
||||
|
||||
@@ -7,3 +7,18 @@
|
||||
- [response.ts](./response.ts):EASO/Piper 响应和写入结果校验。
|
||||
|
||||
上级 [api.ts](../api.ts) 保留统一传输出口。入口层应使用 `services.ts`,不能直接依赖此目录的 API。
|
||||
|
||||
## 写入结果判定
|
||||
|
||||
所有写操作(保存、刷新 chooses、删除、启停)统一走 `readEasoWriteResponse`:先按 HTTP 状态,再解析 body 中的业务码 `code`。
|
||||
**HTTP 200 不等于业务成功**,只看状态码会把未生效的写操作报成成功。
|
||||
|
||||
## 灰度开通网关 (grantWorkflowNodesApi)
|
||||
|
||||
| 项目 | 说明 |
|
||||
|---|---|
|
||||
| 请求地址 | `resolveGrayGatewayUrl()`:显式 `gatewayUrl` 参数 > 环境变量 `HOSE_GRAY_GATEWAY_URL` > 内置默认 `DEFAULT_GRAY_GATEWAY_URL` |
|
||||
| 环境变量用途 | 网关托管在第三方域,实例可能被回收或迁移;配置环境变量可在不改代码的情况下切换网关 |
|
||||
| `baseUrl` 参数 | 目标合思租户地址,作为 body 字段交给网关定位企业,与网关自身地址无关 |
|
||||
| 成功判定 | 优先取显式 `success` 布尔值,其次取 `code === 200`;**两者都缺失时判为失败**,不默认成功 |
|
||||
| 失败信息 | 传输异常抛 `EkbApiError`(`GATEWAY_ERROR`),消息带上实际请求的网关地址 |
|
||||
@@ -71,11 +71,45 @@ export async function getWorkflowEnumOptions(
|
||||
|
||||
// ── 灰度节点开通网关 ──────────────────────────────────────────────────────────
|
||||
|
||||
/** 网关地址环境变量。网关托管在第三方域,实例可能被回收或迁移,必须允许覆盖。 */
|
||||
export const GRAY_GATEWAY_URL_ENV = "HOSE_GRAY_GATEWAY_URL";
|
||||
export const DEFAULT_GRAY_GATEWAY_URL = "https://d9jxeccs5j.sealosgzg.site";
|
||||
export const GRAY_GATEWAY_PATH = "/hose-workflow-node";
|
||||
|
||||
/**
|
||||
* 解析网关请求地址:显式参数 > 环境变量 > 内置默认。
|
||||
* 网关默认地址指向第三方托管实例(`.sealosgzg.site`),同类实例曾被回收;
|
||||
* 硬编码且无逃生口会导致 `workflow nodes grant` 全线瘫痪且无从切换。
|
||||
*/
|
||||
export function resolveGrayGatewayUrl(explicit?: string): string {
|
||||
const candidate = (
|
||||
explicit ??
|
||||
process.env[GRAY_GATEWAY_URL_ENV] ??
|
||||
DEFAULT_GRAY_GATEWAY_URL
|
||||
).trim();
|
||||
return `${candidate.replace(/\/+$/, "")}${GRAY_GATEWAY_PATH}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定网关是否真的开通成功。缺字段不默认为成功:开通未生效会让下游
|
||||
* `analyze` 依旧报 PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
|
||||
*/
|
||||
export function interpretGatewayOutcome(json: any): boolean {
|
||||
if (typeof json?.success === "boolean") return json.success;
|
||||
if (json?.code !== undefined && json?.code !== null) return Number(json.code) === 200;
|
||||
// 缺少明确成功/失败标记时不默认成功:开通未生效会让下游 analyze 依旧报
|
||||
// PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function grantWorkflowNodesApi(options: {
|
||||
token: string;
|
||||
corpId: string;
|
||||
nodes: string[];
|
||||
/** 目标合思租户地址,网关据此定位要开通的企业。 */
|
||||
baseUrl?: string;
|
||||
/** 网关自身地址;缺省依次使用环境变量 HOSE_GRAY_GATEWAY_URL 与内置默认地址。 */
|
||||
gatewayUrl?: string;
|
||||
}): Promise<import("../../types.js").GrantWorkflowNodesResult> {
|
||||
const payload = {
|
||||
token: options.token,
|
||||
@@ -83,22 +117,23 @@ export async function grantWorkflowNodesApi(options: {
|
||||
nodes: options.nodes.join(","),
|
||||
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
||||
};
|
||||
const gatewayUrl = resolveGrayGatewayUrl(options.gatewayUrl);
|
||||
|
||||
try {
|
||||
const response = await ky.post("https://d9jxeccs5j.sealosgzg.site/hose-workflow-node", {
|
||||
const response = await ky.post(gatewayUrl, {
|
||||
json: payload,
|
||||
timeout: 30000,
|
||||
});
|
||||
const json = (await response.json()) as any;
|
||||
const innerData = json?.data?.data ?? json?.data ?? {};
|
||||
return {
|
||||
success: Boolean(json?.success ?? true),
|
||||
success: interpretGatewayOutcome(json),
|
||||
saved: Array.isArray(innerData.saved) ? innerData.saved : [],
|
||||
skipped: Array.isArray(innerData.skipped) ? innerData.skipped : [],
|
||||
rawMessage: json?.data?.msg || json?.msg || json?.message || "",
|
||||
};
|
||||
} catch (err: any) {
|
||||
const message = err?.message || String(err);
|
||||
throw new EkbApiError(`灰度节点开通网关调用失败: ${message}`, "GATEWAY_ERROR", 502);
|
||||
throw new EkbApiError(`灰度节点开通网关调用失败 (${gatewayUrl}): ${message}`, "GATEWAY_ERROR", 502);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
|
||||
/**
|
||||
* 灰度开通网关的行为测试。网关地址托管在第三方域,且历史实例曾被回收,
|
||||
* 必须保证「地址可覆盖」与「成功判定不默认为真」这两件事被固化下来。
|
||||
*
|
||||
* 这里刻意只用纯函数断言 + 对 ky.post 的可恢复 spy:
|
||||
* `mock.module("ky")` 会污染同进程其他用例的 ky 引用。
|
||||
*/
|
||||
const {
|
||||
grantWorkflowNodesApi,
|
||||
resolveGrayGatewayUrl,
|
||||
interpretGatewayOutcome,
|
||||
GRAY_GATEWAY_URL_ENV,
|
||||
DEFAULT_GRAY_GATEWAY_URL,
|
||||
GRAY_GATEWAY_PATH,
|
||||
} = await import("./catalog/api.js");
|
||||
|
||||
const ORIGINAL_ENV = process.env[GRAY_GATEWAY_URL_ENV];
|
||||
|
||||
function restoreEnv(): void {
|
||||
if (ORIGINAL_ENV === undefined) delete process.env[GRAY_GATEWAY_URL_ENV];
|
||||
else process.env[GRAY_GATEWAY_URL_ENV] = ORIGINAL_ENV;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv();
|
||||
});
|
||||
|
||||
describe("gray gateway address resolution", () => {
|
||||
it("falls back to the built-in default host", () => {
|
||||
delete process.env[GRAY_GATEWAY_URL_ENV];
|
||||
expect(resolveGrayGatewayUrl()).toBe(`${DEFAULT_GRAY_GATEWAY_URL}${GRAY_GATEWAY_PATH}`);
|
||||
});
|
||||
|
||||
it("prefers the environment override and normalizes trailing slashes", () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com///";
|
||||
expect(resolveGrayGatewayUrl()).toBe(`https://gw.example.com${GRAY_GATEWAY_PATH}`);
|
||||
});
|
||||
|
||||
it("lets the explicit argument win over the environment", () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://ignored.example.com";
|
||||
expect(resolveGrayGatewayUrl("https://explicit.example.com")).toBe(
|
||||
`https://explicit.example.com${GRAY_GATEWAY_PATH}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gray gateway outcome interpretation", () => {
|
||||
it("honours an explicit success flag", () => {
|
||||
expect(interpretGatewayOutcome({ success: true })).toBe(true);
|
||||
expect(interpretGatewayOutcome({ success: false })).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a non-200 business code as failure", () => {
|
||||
expect(interpretGatewayOutcome({ code: 200 })).toBe(true);
|
||||
expect(interpretGatewayOutcome({ code: 500 })).toBe(false);
|
||||
});
|
||||
|
||||
it("does not assume success when the gateway omits any verdict", () => {
|
||||
expect(interpretGatewayOutcome({ msg: "ok" })).toBe(false);
|
||||
expect(interpretGatewayOutcome({})).toBe(false);
|
||||
expect(interpretGatewayOutcome(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("grantWorkflowNodesApi request contract", () => {
|
||||
it("posts to the resolved gateway and keeps tenant baseUrl in the payload", async () => {
|
||||
let requestedUrl = "";
|
||||
let payload: Record<string, unknown> = {};
|
||||
spyOn(ky, "post").mockImplementation((async (url: string, options: any) => {
|
||||
requestedUrl = String(url);
|
||||
payload = options?.json ?? {};
|
||||
return { ok: true, status: 200, json: async () => ({ success: true, data: { saved: ["code-js2"], skipped: [] } }) };
|
||||
}) as never);
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "tok",
|
||||
corpId: "corp-1",
|
||||
nodes: ["code-js2"],
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.saved).toEqual(["code-js2"]);
|
||||
expect(requestedUrl).toContain("/hose-workflow-node");
|
||||
expect(payload.corpId).toBe("corp-1");
|
||||
expect(payload.baseUrl).toBe("https://app.ekuaibao.com");
|
||||
});
|
||||
|
||||
it("includes the gateway url in transport failures", async () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com";
|
||||
spyOn(ky, "post").mockImplementation((async () => {
|
||||
throw new Error("connect ETIMEDOUT");
|
||||
}) as never);
|
||||
|
||||
await expect(
|
||||
grantWorkflowNodesApi({ token: "tok", corpId: "corp-1", nodes: ["code-js2"] })
|
||||
).rejects.toThrow(/https:\/\/gw\.example\.com\/hose-workflow-node/);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { WorkflowPageSchema, WorkflowStatsSchema, WorkflowChargeSchema, WorkflowDetailSchema, WorkflowSnapshotSchema, WorkflowSnapshotPageSchema, WorkflowLogPageSchema } from "../../types.js";
|
||||
import type { WorkflowState } from "../../types.js";
|
||||
import { unwrap, readEasoWriteResponse, ok } from "../response.js";
|
||||
import { unwrap, readEasoWriteResponse } from "../response.js";
|
||||
|
||||
// ── 工作流(EASO)─────────────────────────────────────────────────────────────
|
||||
// 注意:EASO 客户端已自动注入 corpId,无需再传
|
||||
@@ -166,13 +166,18 @@ export async function listWorkflowLogs(
|
||||
|
||||
// ── 工作流启停(Piper)────────────────────────────────────────────────────────
|
||||
|
||||
export async function toggleWorkflow(
|
||||
/**
|
||||
* 工作流启停写操作。响应必须走 `readEasoWriteResponse` 校验业务码:
|
||||
* HTTP 200 也可能携带 code != 200 的业务失败,只看状态码会把未生效的启停报成成功。
|
||||
* 是否真的生效由上层回读详情确认,本层不做推断。
|
||||
*/
|
||||
export async function toggleWorkflowState(
|
||||
client: KyInstance,
|
||||
pipelineId: string,
|
||||
state: WorkflowState
|
||||
): Promise<{ success: boolean }> {
|
||||
): Promise<void> {
|
||||
const response = await client.put(`api/easo/pipelines/state/${pipelineId}`, {
|
||||
searchParams: { state: String(state) },
|
||||
});
|
||||
return ok(response);
|
||||
await readEasoWriteResponse(response);
|
||||
}
|
||||
@@ -54,8 +54,3 @@ export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promi
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
|
||||
// Helper for simple success responses
|
||||
export async function ok(response: Response): Promise<{ success: boolean }> {
|
||||
return { success: response.status === 200 };
|
||||
}
|
||||
@@ -1,25 +1,25 @@
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
||||
import type { WorkflowTaskExecution } from "../types.js";
|
||||
import type { WatchWorkflowOptions, WorkflowWatchEvent } from "./types.js";
|
||||
|
||||
export const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
|
||||
// Job 状态判定统一来自 execution/job-status.ts,watch 与 debug 共用同一套语义。
|
||||
export { normalizeJobStatus, isJobTerminal, TERMINAL_JOB_STATES } from "../execution/job-status.js";
|
||||
|
||||
export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<string, unknown> | null): string {
|
||||
if (!job) return "UNKNOWN";
|
||||
const rawStatus = (job as any).status;
|
||||
const rawState = (job as any).state;
|
||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||
const s = rawStatus.trim().toUpperCase();
|
||||
if (s === "STARTED") return "RUNNING";
|
||||
return s;
|
||||
}
|
||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
export function isJobTerminal(status: string): boolean {
|
||||
return TERMINAL_STATES.has(status.toUpperCase());
|
||||
/**
|
||||
* `--failed-only` 的事件过滤。此前的实现在两个监听入口各写了一份且逐字相同,
|
||||
* 任一侧漏改都会让两种监听模式给出不同的结果。
|
||||
*/
|
||||
export function shouldEmitWatchEvent(
|
||||
event: WorkflowWatchEvent,
|
||||
options: Pick<WatchWorkflowOptions, "failedOnly">
|
||||
): boolean {
|
||||
if (!options.failedOnly) return true;
|
||||
return (
|
||||
event.type === "task_failed" ||
|
||||
(event.type === "task_skipped" && Boolean(event.error)) ||
|
||||
event.type === "job_completed" ||
|
||||
event.type === "timeout" ||
|
||||
event.type === "cancelled"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
|
||||
import { AuthenticationError } from "../../../../core/errors.js";
|
||||
import * as api from "../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { normalizeJobStatus, isJobTerminal, shouldEmitWatchEvent } from "./helpers.js";
|
||||
import { watchSingleJob } from "./single-job.js";
|
||||
|
||||
/**
|
||||
@@ -21,16 +21,7 @@ export async function watchWorkflowPipeline(
|
||||
const seenJobIds = new Set<string>();
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout" && event.type !== "cancelled"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!shouldEmitWatchEvent(event, options)) return;
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
|
||||
import type { WorkflowJobDetail, WorkflowTaskExecution } from "../types.js";
|
||||
import * as api from "../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
import { normalizeJobStatus, isJobTerminal, shouldEmitWatchEvent } from "./helpers.js";
|
||||
import { TaskExecutionTracker } from "./tracker.js";
|
||||
|
||||
/**
|
||||
@@ -20,16 +20,7 @@ export async function watchSingleJob(
|
||||
const events: WorkflowWatchEvent[] = [];
|
||||
|
||||
const emit = async (event: WorkflowWatchEvent) => {
|
||||
if (options.failedOnly) {
|
||||
if (
|
||||
event.type !== "task_failed" &&
|
||||
!(event.type === "task_skipped" && event.error) &&
|
||||
event.type !== "job_completed" &&
|
||||
event.type !== "timeout" && event.type !== "cancelled"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!shouldEmitWatchEvent(event, options)) return;
|
||||
events.push(event);
|
||||
if (options.onEvent) {
|
||||
await options.onEvent(event);
|
||||
|
||||
+49
-16
@@ -1,6 +1,7 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { URL } from "node:url";
|
||||
import { runCli } from "../cli/runner.js";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { getOpenApiSchema } from "../packaging/embedded-openapi.js";
|
||||
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
@@ -28,7 +29,12 @@ function checkHttpAuth(req: IncomingMessage): boolean {
|
||||
return authHeader === `Bearer ${requiredToken}`;
|
||||
}
|
||||
|
||||
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
export async function handleHttpRequest(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
options: { app?: "hose-use" | "hose-aipro" } = {}
|
||||
): Promise<void> {
|
||||
const isAiPro = options.app === "hose-aipro";
|
||||
const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
|
||||
const trustedOrigin = isTrustedOrigin(origin);
|
||||
|
||||
@@ -59,32 +65,59 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
try {
|
||||
// 2. Metadata & Health
|
||||
if (method === "GET" && pathname === "/") {
|
||||
sendJson(res, 200, {
|
||||
name: "hose-use",
|
||||
version: VERSION,
|
||||
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
|
||||
docs: "/docs",
|
||||
openapi: "/openapi.json",
|
||||
rawOpenapi: "/raw-openapi.json",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
corps: "GET /v1/corps",
|
||||
},
|
||||
});
|
||||
sendJson(
|
||||
res,
|
||||
200,
|
||||
isAiPro
|
||||
? {
|
||||
name: "hose-aipro",
|
||||
version: VERSION,
|
||||
description: "合思 AI PRO 确定性审批仲裁网关 HTTP 服务",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
status: "GET /v1/status",
|
||||
},
|
||||
}
|
||||
: {
|
||||
name: "hose-use",
|
||||
version: VERSION,
|
||||
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
|
||||
docs: "/docs",
|
||||
openapi: "/openapi.json",
|
||||
rawOpenapi: "/raw-openapi.json",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
corps: "GET /v1/corps",
|
||||
},
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/health") {
|
||||
sendJson(res, 200, {
|
||||
status: "ok",
|
||||
name: "hose-use",
|
||||
name: isAiPro ? "hose-aipro" : "hose-use",
|
||||
version: VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAiPro && method === "GET" && pathname === "/v1/status") {
|
||||
const statusRes = await runAiProCli(["status", "--json"]);
|
||||
let parsedData: any = {};
|
||||
try {
|
||||
parsedData = JSON.parse(statusRes.stdout);
|
||||
} catch {
|
||||
parsedData = { stdout: statusRes.stdout };
|
||||
}
|
||||
sendJson(res, 200, parsedData);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
@@ -119,7 +152,7 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
|
||||
const tokens = tokenizeCommand(command);
|
||||
const cliArgs = normalizeCliArgs(tokens);
|
||||
const result = await runCli(cliArgs);
|
||||
const result = isAiPro ? await runAiProCli(cliArgs) : await runCli(cliArgs);
|
||||
|
||||
let parsedData: unknown = undefined;
|
||||
const trimmedStdout = result.stdout.trim();
|
||||
|
||||
+17
-6
@@ -6,18 +6,22 @@ export type HttpServerOptions = {
|
||||
port?: number;
|
||||
host?: string;
|
||||
silent?: boolean;
|
||||
app?: "hose-use" | "hose-aipro";
|
||||
};
|
||||
|
||||
export const DEFAULT_HTTP_PORT = 8888;
|
||||
export const DEFAULT_AIPRO_HTTP_PORT = 8889;
|
||||
export const DEFAULT_HTTP_HOST = "127.0.0.1";
|
||||
|
||||
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||
const isAiPro = options.app === "hose-aipro";
|
||||
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
||||
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
await handleHttpRequest(req, res);
|
||||
await handleHttpRequest(req, res, { app: options.app || "hose-use" });
|
||||
} catch (err) {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
|
||||
@@ -33,12 +37,19 @@ export async function startHttpServer(options: HttpServerOptions = {}): Promise<
|
||||
|
||||
server.listen(port, host, () => {
|
||||
if (!options.silent) {
|
||||
console.error(`\n⚡ hose-use HTTP Server (v${VERSION}) 已启动`);
|
||||
const appName = isAiPro ? "hose-aipro" : "hose-use";
|
||||
console.error(`\n⚡ ${appName} HTTP Server (v${VERSION}) 已启动`);
|
||||
console.error(` 主服务地址: http://${host}:${port}`);
|
||||
console.error(` 交互式文档: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
|
||||
if (!isAiPro) {
|
||||
console.error(` 交互式文档: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
|
||||
}
|
||||
console.error(` CLI执行网关: POST http://${host}:${port}/api/cli`);
|
||||
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||
if (!isAiPro) {
|
||||
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||
} else {
|
||||
console.error(` 网关状态接口: GET http://${host}:${port}/v1/status\n`);
|
||||
}
|
||||
}
|
||||
resolve(server);
|
||||
});
|
||||
|
||||
@@ -2,65 +2,86 @@ import { describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EMBEDDED_SKILL_FILES, getDefaultGlobalSkillDir, getSkillContent, installSkillFiles } from "./embedded-skill.js";
|
||||
import {
|
||||
EMBEDDED_HOSE_USE_SKILL_FILES,
|
||||
EMBEDDED_AIPRO_SKILL_FILES,
|
||||
getDefaultGlobalSkillDir,
|
||||
getDefaultAiProGlobalSkillDir,
|
||||
getSkillContent,
|
||||
getAiProSkillContent,
|
||||
installSkillFiles,
|
||||
installHoseUseSkillFiles,
|
||||
installAiProSkillFiles,
|
||||
} from "./embedded-skill.js";
|
||||
|
||||
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
test("全局 Skill 目录固定为 ~/.agents/skills/hose-use", () => {
|
||||
describe("embedded-skill - 双 Skill 体系内嵌与分发 (hose-use 与 hose-aipro)", () => {
|
||||
test("全局 Skill 目录分别固定为 ~/.agents/skills/hose-use 与 hose-aipro", () => {
|
||||
expect(getDefaultGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-use"));
|
||||
expect(getDefaultAiProGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-aipro"));
|
||||
});
|
||||
|
||||
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
test("hose-use: 正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
expect(getSkillContent()).toContain("name: hose-use");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toContain("RSA");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/auth.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/auth.md"]).toContain("RSA");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toContain("bill get");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/bill.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/bill.md"]).toContain("bill get");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/workflow.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toContain("POST /api/cli");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/service.md"]).toContain("hose-use aipro");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro");
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
|
||||
expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toContain("assist-platform");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("--reveal -o <path>");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("references/store.md");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/store.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/assist-platform.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/assist-platform.md"]).toContain("assist-platform");
|
||||
|
||||
// 套件结构:根入口路由到 multi/ 下的子技能
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("multi/ekuaibao-mvel/SKILL.md");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/SKILL.md"]).toContain("name: ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/agents/openai.yaml"]).toContain("ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/SKILL.md"]).toContain("name: ekuaibao-nodes");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/references/gray-nodes.md"]).toContain("灰度节点清单");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toContain("multi/ekuaibao-mvel/SKILL.md");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-mvel/SKILL.md"]).toContain("name: ekuaibao-mvel");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-mvel/agents/openai.yaml"]).toContain("ekuaibao-mvel");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-nodes/SKILL.md"]).toContain("name: ekuaibao-nodes");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-nodes/references/gray-nodes.md"]).toContain("灰度节点清单");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
test("hose-aipro: 正确内嵌 SKILL.md、agents/openai.yaml、approval.md 与 service.md", () => {
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"]).toContain("name: hose-aipro");
|
||||
expect(getAiProSkillContent()).toContain("name: hose-aipro");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["agents/openai.yaml"]).toContain("command: \"hose-aipro\"");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/approval.md"]).toContain("hose-aipro decide");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/service.md"]).toContain("8889");
|
||||
});
|
||||
|
||||
test("installSkillFiles 显式路径安装保留层级结构", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "hose-skill-test-"));
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
const res = installHoseUseSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(19);
|
||||
expect(res.files.length).toBe(18);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "feetype.md"))).toBe(true);
|
||||
@@ -74,4 +95,19 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("installAiProSkillFiles 正确落盘 hose-aipro 专属技能文件", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "aipro-skill-test-"));
|
||||
try {
|
||||
const res = installAiProSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(5);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
// ── hose-use Skill 文件 ────────────────────────────────────────────────────────
|
||||
import skillMain from "../../skills/hose-use/SKILL.md" with { type: "text" };
|
||||
import agentOpenAi from "../../skills/hose-use/agents/openai.yaml" with { type: "text" };
|
||||
import refAuth from "../../skills/hose-use/references/auth.md" with { type: "text" };
|
||||
@@ -13,7 +14,6 @@ import refTask from "../../skills/hose-use/references/task.md" with { type: "tex
|
||||
import refMessage from "../../skills/hose-use/references/message.md" with { type: "text" };
|
||||
import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" };
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" };
|
||||
import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" };
|
||||
import refStore from "../../skills/hose-use/references/store.md" with { type: "text" };
|
||||
import refAssistPlatform from "../../skills/hose-use/references/assist-platform.md" with { type: "text" };
|
||||
@@ -22,11 +22,17 @@ import multiMvelAgent from "../../skills/hose-use/multi/ekuaibao-mvel/agents/ope
|
||||
import multiNodes from "../../skills/hose-use/multi/ekuaibao-nodes/SKILL.md" with { type: "text" };
|
||||
import multiNodesGray from "../../skills/hose-use/multi/ekuaibao-nodes/references/gray-nodes.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
// ── hose-aipro Skill 文件 ──────────────────────────────────────────────────────
|
||||
import aiproSkillMain from "../../skills/hose-aipro/SKILL.md" with { type: "text" };
|
||||
import aiproAgentOpenAi from "../../skills/hose-aipro/agents/openai.yaml" with { type: "text" };
|
||||
import aiproRefApproval from "../../skills/hose-aipro/references/approval.md" with { type: "text" };
|
||||
import aiproRefService from "../../skills/hose-aipro/references/service.md" with { type: "text" };
|
||||
import aiproRefReadme from "../../skills/hose-aipro/references/README.references.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_HOSE_USE_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
"agents/openai.yaml": agentOpenAi,
|
||||
"references/auth.md": refAuth,
|
||||
"references/approval.md": refApproval,
|
||||
"references/bill.md": refBill,
|
||||
"references/feetype.md": refFeeType,
|
||||
"references/contact.md": refContact,
|
||||
@@ -44,36 +50,92 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"multi/ekuaibao-nodes/references/gray-nodes.md": multiNodesGray,
|
||||
};
|
||||
|
||||
export const EMBEDDED_AIPRO_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": aiproSkillMain,
|
||||
"agents/openai.yaml": aiproAgentOpenAi,
|
||||
"references/approval.md": aiproRefApproval,
|
||||
"references/service.md": aiproRefService,
|
||||
"references/README.references.md": aiproRefReadme,
|
||||
};
|
||||
|
||||
// 保持模块级向后兼容
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = EMBEDDED_HOSE_USE_SKILL_FILES;
|
||||
|
||||
export function getSkillContent(): string {
|
||||
return EMBEDDED_SKILL_FILES["SKILL.md"] || "";
|
||||
return EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"] || "";
|
||||
}
|
||||
|
||||
export function getAiProSkillContent(): string {
|
||||
return EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"] || "";
|
||||
}
|
||||
|
||||
export function getDefaultGlobalSkillDir(): string {
|
||||
return join(homedir(), ".agents", "skills", "hose-use");
|
||||
}
|
||||
|
||||
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
export function getDefaultAiProGlobalSkillDir(): string {
|
||||
return join(homedir(), ".agents", "skills", "hose-aipro");
|
||||
}
|
||||
|
||||
export function installHoseUseSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
} {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const installed: string[] = [];
|
||||
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_SKILL_FILES)) {
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_HOSE_USE_SKILL_FILES)) {
|
||||
const fullPath = join(targetDir, relPath);
|
||||
mkdirSync(dirname(fullPath), { recursive: true });
|
||||
writeFileSync(fullPath, content, "utf8");
|
||||
installed.push(relPath);
|
||||
}
|
||||
|
||||
return {
|
||||
targetDir,
|
||||
files: installed,
|
||||
};
|
||||
return { targetDir, files: installed };
|
||||
}
|
||||
|
||||
export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string } {
|
||||
const globalDir = getDefaultGlobalSkillDir();
|
||||
installSkillFiles(globalDir);
|
||||
return { synced: true, targetDir: globalDir };
|
||||
export function installAiProSkillFiles(targetDir: string = getDefaultAiProGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
} {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const installed: string[] = [];
|
||||
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_AIPRO_SKILL_FILES)) {
|
||||
const fullPath = join(targetDir, relPath);
|
||||
mkdirSync(dirname(fullPath), { recursive: true });
|
||||
writeFileSync(fullPath, content, "utf8");
|
||||
installed.push(relPath);
|
||||
}
|
||||
|
||||
return { targetDir, files: installed };
|
||||
}
|
||||
|
||||
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
skills?: string[];
|
||||
} {
|
||||
const defaultGlobalDir = getDefaultGlobalSkillDir();
|
||||
// 当为全局默认目录时,自动同时安装两个 Skill
|
||||
if (targetDir === defaultGlobalDir) {
|
||||
const hoseRes = installHoseUseSkillFiles(defaultGlobalDir);
|
||||
const aiproRes = installAiProSkillFiles(getDefaultAiProGlobalSkillDir());
|
||||
return {
|
||||
targetDir,
|
||||
files: [...hoseRes.files, ...aiproRes.files.map((f) => `hose-aipro/${f}`)],
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
};
|
||||
}
|
||||
|
||||
// 显式指定自定义目录时,在该目录下安装 hose-use 文件
|
||||
return installHoseUseSkillFiles(targetDir);
|
||||
}
|
||||
|
||||
export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string; targetDirs: string[] } {
|
||||
const hoseDir = getDefaultGlobalSkillDir();
|
||||
const aiproDir = getDefaultAiProGlobalSkillDir();
|
||||
installHoseUseSkillFiles(hoseDir);
|
||||
installAiProSkillFiles(aiproDir);
|
||||
return { synced: true, targetDir: hoseDir, targetDirs: [hoseDir, aiproDir] };
|
||||
}
|
||||
Reference in new issue
Block a user